I have two models with two update forms.
Now I want to achieve two things:
be able to edit a certificate and set all the servers this certificate is used on
be able to update a server and set all the certificates which are used on this server.
class Certificate(models.Model):
internal_name = models.CharField(max_length=1024)
pem_representation = models.TextField(unique=True)
servers = models.ManyToManyField(
Server, related_name='certificates', blank=True)
class Server(models.Model):
name = models.CharField(max_length=1024, unique=True)
class CertificateUpdateForm(forms.ModelForm):
class Meta:
model = models.Certificate
fields = ['internal_name', 'pem_representation', 'servers']
class ServerUpdateForm(forms.ModelForm):
class Meta:
model = models.Server
fields = ['name', 'certificates']
Without the field "certificates" in ServerUpdateForm I get no error but when updating via the form the changes for the certificates just aren't recognized.
The error message I get with this code is:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib64/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib64/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File " venv/lib64/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File " venv/lib64/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File " venv/lib64/python3.8/site-packages/django/core/management/base.py", line 392, in check
all_issues = checks.run_checks(
File " venv/lib64/python3.8/site-packages/django/core/checks/registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File " venv/lib64/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File " venv/lib64/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File " venv/lib64/python3.8/site-packages/django/urls/resolvers.py", line 408, in check
for pattern in self.url_patterns:
File " venv/lib64/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File " venv/lib64/python3.8/site-packages/django/urls/resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File " venv/lib64/python3.8/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File " venv/lib64/python3.8/site-packages/django/urls/resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib64/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File " certmanager/certmanager/urls.py", line 26, in <module>
path('servers/', include('servers.urls')),
File " venv/lib64/python3.8/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib64/python3.8/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File " certmanager/servers/urls.py", line 3, in <module>
from . import views
File " certmanager/servers/views.py", line 9, in <module>
from . import forms, models
File " certmanager/servers/forms.py", line 12, in <module>
class ServerUpdateForm(forms.ModelForm):
File " venv/lib64/python3.8/site-packages/django/forms/models.py", line 268, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (certificates) specified for Server
How can I update the M2M relation on both objects?
So I asked the same question in a post on the Django forum and got a working suggestion.
For better viewability:
I overrode the post-method of the UpdateView I use and managed the Many2Many relationship there. I also had to remove the 'certificates' field form the UpdateForm obviously because it thew an exception.
Here is the full UpdateView class I use:
class ServerUpdate(PermissionRequiredMixin, generic.UpdateView):
model = models.Server
template_name = 'servers/update.html'
form_class = forms.ServerUpdateForm
queryset = models.Server.objects.all()
success_url = reverse_lazy('servers:server-index')
permission_required = ('servers.change_server')
def get_context_data(self, **kwargs):
context = super(ServerUpdate, self).get_context_data(**kwargs)
context['all_certificates'] = Certificate.objects.all()
context['selected_certificates'] = self.object.certificates.all()
return context
def post(self, request, *args, **kwargs):
selected_certificates = request.POST.getlist('certificates')
self.object = self.get_object()
self.object.certificates.set(selected_certificates)
return super().post(request, *args, **kwargs)
Related
Sorry for my bad English in advance.
I'm trying to discover django, so I decided to write my own sign in/sign up views.
So I just wrote something like that -
class RegisterView(CreateView):
template_name = 'auth/user_create_form.html'
model = User
fields = ['username', 'password', 'email']
So, it's basically working with GET requests. We can see the form on specified url.
But after altering all fields and submitting form, I've got a mistake what suggested to specify get_absolute_url for model to redirect after submitting. So I decided to give success_url to RegisterView -
class RegisterView(CreateView):
template_name = 'auth/user_create_form.html'
model = User
fields = ['username', 'password', 'email']
success_url = reverse('words:main_page')
And got a mistake
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/urls/resolvers.py", line 600, in url_patterns
iter(patterns)
TypeError: 'module' object is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/linuxbrew/.linuxbrew/opt/python#3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner
self.run()
File "/home/linuxbrew/.linuxbrew/opt/python#3.9/lib/python3.9/threading.py", line 892, in run
self._target(*self._args, **self._kwargs)
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/core/management/base.py", line 419, in check
all_issues = checks.run_checks(
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/core/checks/registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/core/checks/urls.py", line 23, in check_resolver
return check_method()
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/urls/resolvers.py", line 412, in check
for pattern in self.url_patterns:
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/urls/resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/urls/resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "/home/linuxbrew/.linuxbrew/opt/python#3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 790, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/home/yegor/projects/word_collector/word_collector/urls.py", line 23, in <module>
path('', include('words.urls'))
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/urls/conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "/home/linuxbrew/.linuxbrew/opt/python#3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 790, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/home/yegor/projects/word_collector/words/urls.py", line 2, in <module>
from words.views import MainView, RegisterView, LoginView
File "/home/yegor/projects/word_collector/words/views.py", line 12, in <module>
class RegisterView(CreateView):
File "/home/yegor/projects/word_collector/words/views.py", line 17, in RegisterView
success_url = reverse('words:main_page')
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/urls/base.py", line 54, in reverse
app_list = resolver.app_dict[ns]
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/urls/resolvers.py", line 526, in app_dict
self._populate()
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/urls/resolvers.py", line 460, in _populate
for url_pattern in reversed(self.url_patterns):
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/yegor/.cache/pypoetry/virtualenvs/word-collector-g9LS8W6v-py3.9/lib/python3.9/site-packages/django/urls/resolvers.py", line 607, in url_patterns
raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf 'word_collector.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
I'm sure that urlconf is great. Where this thing getting circular import? And how I should use success_url?
By the way, if I assign POST method to class -
def post(self, *args, **kwargs):
self.success_url = reverse('words:main_page')
return super().post(*args, **kwargs)
then everything work properly, but I still don't understand why?
I have a set of models:
class DebugConf(models.Model):
is_setup = models.BooleanField(default=False)
debug_setup_date = models.DateTimeField()
def __str__(self):
return self.is_setup
class Currency(models.Model):
currency_name = models.CharField(max_length=100)
currency_value_in_dollars = models.FloatField()
currency_value_in_dollars_date = models.DateTimeField()
def __str__(self):
return self.currency_name
class User(models.Model):
user_name = models.CharField(max_length=200)
user_pass = models.CharField(max_length=200)
join_date = models.DateTimeField()
def __str__(self):
return self.user_name
class Transaction(models.Model):
transaction_type = models.CharField(max_length=200)
transaction_amount = models.FloatField()
transaction_date = models.DateTimeField()
transaction_currency = models.ForeignKey(Currency, on_delete=models.CASCADE)
transaction_users = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.headline
a project 'crypto' and an app 'manage_crypto_currency' nested into it:
The app's views contains some initialization code:
views.py:
if IS_DEBUG_MODE:
print('[!!!INFO!!!] DEBUG MODE SET! USING GENERATED TABLES')
init_debug_tables()
def init_debug_tables():
# Check if debug table has already been initialized
debug_conf = DebugConf.objects.all()
if debug_conf.objects.exists():
return
At the moment, the db is not initialized; when running:
python manage.py makemigrations manage_crypto_currency
in the root (project dir):
I get:
[!!!INFO!!!] DEBUG MODE SET! USING GENERATED TABLES
Traceback (most recent call last):
File "manage.py", line 24, in <module>
main()
File "manage.py", line 20, in main
execute_from_command_line(sys.argv)
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
utility.execute()
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\base.py", line 368, in execute
self.check()
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = checks.run_checks(
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check
for pattern in self.url_patterns:
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\msebi\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\projects\django\crypto-currency-board\crypto\crypto\urls.py", line 21, in <module>
path('', include('manage_crypto_currency.urls')),
File "C:\projects\django\crypto-currency-board\venv\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\msebi\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\projects\django\crypto-currency-board\crypto\manage_crypto_currency\urls.py", line 5, in <module>
from . import views
File "C:\projects\django\crypto-currency-board\crypto\manage_crypto_currency\views.py", line 24, in <module>
init_debug_tables()
File "C:\projects\django\crypto-currency-board\crypto\manage_crypto_currency\setup_test_db\setup_debug_tables.py", line 14, in init_debug_tables
if debug_conf.objects.exists():
AttributeError: 'QuerySet' object has no attribute 'objects'
The line:
[!!!INFO!!!] DEBUG MODE SET! USING GENERATED TABLES
is in views. Apparently, the migrations tool feels the need to execute views.py. Why on Earth, I have no clue. Is it possible to make makemigrations NOT execute code that it shouldn't, e.g. just create the models given that the db is not initialized?
EDIT
The answers don't answer WHY migrate runs views.py (I don't know either), but commenting out:
# if IS_DEBUG_MODE:
# print('[!!!INFO!!!] DEBUG MODE SET! USING GENERATED TABLES')
# init_debug_tables()
leads to successful migration. Is there a less cumbersome way to go about it? (Un)comment is ugly.
You don't need to use call the objects of a QuerySet
def init_debug_tables():
# Check if debug table has already been initialized
debug_conf = DebugConf.objects.all()
if debug_conf.exists(): # instead of `debug_conf.objects.exists()`
return
As the error message suggest, debug_conf is the the model class, it is an instance of a QuerySet.
objects is the Manager attached to a model class. This managers creates QuerySet for you (in your code, by the return value of the all method).
So you want to do this:
def init_debug_tables():
# Check if debug table has already been initialized
debug_conf = DebugConf.objects.all()
if debug_conf.exists():
return
I am learning django through the 'Django 3 by example' book, and right now i am trying to build an e - learning platform. But, I am getting a weird error in my views.py file.
Here is my views file:
from django.views.generic.list import ListView
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from .models import Course
class ManageCourseListView(ListView):
model = Course
template_name = 'educa/manage/educa/list.html'
permission_required = 'educa.view_course'
def get_queryset(self):
qs = super().get_queryset()
return qs.filter(owner=self.request.user)
class OwnerMixin(object):
def get_queryset(self):
qs = super().get_queryset()
return qs.filter(owner=self.request.owner)
class OwnerEditMixin(object):
def form_valid(self, form):
form.instance.onwer = self.request.user
return super().form_valid(form)
class OwnerCourseMixin(object, LoginRequiredMixin, PermissionRequiredMixin):
model = Course
fields = ['subject', 'title', 'slug', 'overview']
success_url = reverse_lazy('manage_course_list')
class OwnerCourseEditMixin(OwnerCourseMixin, OwnerEditMixin):
template_name = 'educa/manage/course/list.html'
class CourseCreateView(OwnerEditMixin, CreateView):
permission_required = 'educa.add_course'
class CourseUpdateView(OwnerCourseEditMixin, UpdateView):
permission_required = 'educa.change_course'
class CourseDeleteView(OwnerCourseMixin, DeleteView):
template_name = 'educa/manage/course/delete.html'
permission_required = 'educa.delete_course'
The error is on line 30.
Here is the full error message:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = checks.run_checks(
File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check
for pattern in self.url_patterns:
File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Padma Jain\Desktop\django\educa\elearn\elearn\urls.py", line 24, in <module>
path('course/',include('educa.urls')),
File "C:\Users\Padma Jain\Desktop\django\educa\venv\lib\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\Padma Jain\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Padma Jain\Desktop\django\educa\elearn\educa\urls.py", line 2, in <module>
from .views import *
File "C:\Users\Padma Jain\Desktop\django\educa\elearn\educa\views.py", line 30, in <module>
class OwnerCourseMixin(object, LoginRequiredMixin, PermissionRequiredMixin):
TypeError: Cannot create a consistent method resolution
order (MRO) for bases object, LoginRequiredMixin, PermissionRequiredMixin
And just if it is required, here is the urls.py file of the educa application:
from django.urls import path
from .views import *
urlpatterns = [
path('mine/',ManageCourseListView.as_view(),name='manage_course_list'),
path('create/',CourseCreateView.as_view(),name='course_create'),
path('<pk>/edit/',CourseUpdateView.as_view(),name='course_edit'),
path('<pk>/delete/',CourseDeleteView.as_view(),name='course_delete'),
]
This is my first time building such a large application. Can someone please tell where I'm wrong?
EDIT:
I solved this problem by editing line 30 of my views.py file from this:
class OwnerCourseMixin(object, LoginRequiredMixin, PermissionRequiredMixin):
....
to this:
class OwnerCourseMixin(OwnerMixin, LoginRequiredMixin, PermissionRequiredMixin):
....
In Python, every class inherits from a built-in basic class called object.
Your OwnerCourseMixin is inheriting from object and some other class. Because the other class(es), in this case, LoginRequiredMixin and PermissionRequiredMixin, already inherit from object, Python now cannot determine what class to look methods up on first.
You don't need to inherit from object here.
class OwnerCourseMixin(LoginRequiredMixin, PermissionRequiredMixin):
model = Course
fields = ['subject', 'title', 'slug', 'overview']
success_url = reverse_lazy('manage_course_list')
That should work.
I am doing django project 2.1.4 and getting the below errors, i searched and it seems that i fix errors one by one , but i managed to solve some.
However these i could find any clue.
Error after runserver or migrate.
(myenv) C:\Users\Users\Desktop\blog_project\mysite>python manage.py runserver
Performing system checks...
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001EC9271A0D0>
Traceback (most recent call last):
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\utils\autoreload.py", line 225,
in wrapper
fn(*args, **kwargs)
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\core\management\commands\runserv
er.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 3
79, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 3
66, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\core\checks\registry.py", line 7
1, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\core\checks\urls.py", line 13, i
n check_url_config
return check_resolver(resolver)
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\core\checks\urls.py", line 23, i
n check_resolver
return check_method()
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\urls\resolvers.py", line 396, in
check
for pattern in self.url_patterns:
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\utils\functional.py", line 37, i
n __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\urls\resolvers.py", line 533, in
url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\utils\functional.py", line 37, i
n __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\urls\resolvers.py", line 526, in
urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Users\Anaconda3\envs\myenv\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Users\Desktop\blog_project\mysite\mysite\urls.py", line 22, in <module>
path('', include('blog.urls')),
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\urls\conf.py", line 34, in inclu
de
urlconf_module = import_module(urlconf_module)
File "C:\Users\Users\Anaconda3\envs\myenv\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Users\Desktop\blog_project\mysite\blog\urls.py", line 2, in <module>
from .import views
File "C:\Users\Users\Desktop\blog_project\mysite\blog\views.py", line 4, in <module>
from blog.forms import PostForm,CommentForm
File "C:\Users\Users\Desktop\blog_project\mysite\blog\forms.py", line 15, in <module>
class CommentForm(forms.ModelForm):
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\forms\models.py", line 243, in _
_new__
"needs updating." % name
django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute
or the 'exclude' attribute is prohibited; form CommentForm needs updating.
urlconf_module = import_module(urlconf_module)
File "C:\Users\Users\Anaconda3\envs\myenv\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\Users\Desktop\blog_project\mysite\blog\urls.py", line 2, in <module>
from .import views
File "C:\Users\Users\Desktop\blog_project\mysite\blog\views.py", line 4, in <module>
from blog.forms import PostForm,CommentForm
File "C:\Users\Users\Desktop\blog_project\mysite\blog\forms.py", line 15, in <module>
class CommentForm(forms.ModelForm):
File "C:\Users\Users\Anaconda3\envs\myenv\lib\site-packages\django\forms\models.py", line 243, in _
_new__
"needs updating." % name
django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute
or the 'exclude' attribute is prohibited; form CommentForm needs updating.
here i am just adding separately.
File "C:\Users\Users\Desktop\blog_project\mysite\mysite\urls.py", line 22, in <module>
path('', include('blog.urls')),
'
path('', include('blog.urls')),
'
File "C:\Users\Users\Desktop\blog_project\mysite\blog\urls.py", line 2, in <module>
from .import views
'
from .import views
'
File "C:\Users\Users\Desktop\blog_project\mysite\blog\views.py", line 4, in <module>
from blog.forms import PostForm,CommentForm
'
from blog.forms import PostForm,CommentForm
'
File "C:\Users\Users\Desktop\blog_project\mysite\blog\forms.py", line 15, in <module>
class CommentForm(forms.ModelForm):
'
class CommentForm(forms.ModelForm):
'
How to fix this errors?
UPDATE: CommentForm below
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fileds = ('author','text',)
widgets = {
'author':forms.TextInput(attrs={'class':'textinputclass'}),
'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea'})
}
As can be seen from your CommentForm, you've spelt fields as fileds. Correct that to fix the issue:
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('author','text',) # Use correct spelling
widgets = {
'author':forms.TextInput(attrs={'class':'textinputclass'}),
'text':forms.Textarea(attrs={'class':'editable medium-editor-textarea'})
}
You need to add 'fields' or 'exclude' attribute to your ModelForm.
# example model:
class Comments(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
comment = models.TextField()
# forms:
class CommentForm(forms.ModelForm):
class Meta(object):
model = Comments
exclude = ['first_name', ]
# or:
fields = ['comments', ]
Trying to build a full text search view in Django, but getting this error message when I try to run the server:
No module named 'django.contrib.postgres.search
I did just switch my db from sqlite to postgres, so not sure if there is some sort of error that happened in that move
here is my full stack trace
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x06B2D1E0>
Traceback (most recent call last):
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 115, in populate
app_config.ready()
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\debug_toolbar\apps.py", line 15, in ready
dt_settings.patch_all()
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\debug_toolbar\settings.py", line 243, in patch_all
patch_root_urlconf()
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\debug_toolbar\settings.py", line 231, in patch_root_urlconf
reverse('djdt:render_panel')
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py", line 568, in reverse
app_list = resolver.app_dict[ns]
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py", line 360, in app_dict
self._populate()
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py", line 293, in _populate
for pattern in reversed(self.url_patterns):
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\utils\functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\Users\crstu\Desktop\JSPROJ\dealmazing\dealmazing\urls.py", line 29, in <module>
url(r"^deals/", include("deals.urls", app_name="deals", namespace="deals")),
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\conf\urls\__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 655, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed
File "C:\Users\crstu\Desktop\JSPROJ\dealmazing\deals\urls.py", line 3, in <module>
from .views import *
File "C:\Users\crstu\Desktop\JSPROJ\dealmazing\deals\views.py", line 2, in <module>
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
I've triple checked how i'm importing the module in my views file here but appears ok:
from django.shortcuts import render, redirect
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from django.contrib import messages
from django.http import Http404
from django.contrib.auth.decorators import login_required
from django.views.generic import ListView
from accounts.models import User
from .models import *
import datetime
class DealListView(ListView):
model = Deal
context_object_name = 'deal_list'
queryset = Deal.objects.all()
template_name = 'deal_list.html'
class DealSearchListView(ListView):
"""
Display a Deal List page filtered by search query
"""
model = Deal
paginate_by = 10
def get_queryset(self):
qs = Deal.objects.all()
keywords = self.request.GET.get('q')
if keywords:
query = SearchQuery(keywords)
title_vector = SearchVector('title', weight='A')
content_vector = SearchVector('description', weight='B')
vectors = title_vector + content_vector
qs = qs.annotate(search=vectors).filter(search=query)
qs = qs.annotate(rank=SearchRank(vectors, query)).order_by('-rank')
return qs
and my urls:
from django.conf.urls import url, include
from django.contrib import admin
from .views import *
from dealmazing.views import *
from django.conf import settings
app_name = "deals"
urlpatterns = [
url(r'^$', DealListView.as_view(), name='deals'),
url(r'^(?P<slug>[\w-]+)/$', deal_by_detail, name='deal_detail'),
url(r'^category/(?P<category>\w+)/$', deals_by_category, name='category'),
url(r'^search/(?P<qs>\w+)/$', DealSearchListView.as_vieW(), name='search_results'),