Related
I found this trick, which might be a hack, to set default values when the field is a foreign key to another database:
class House(models.Model):
name = models.CharField(max_length=100, unique=True)
address = models.CharField(max_length=300, null=True, blank=True)
def __str__(self):
return name
#classmethod
def get_default(cls):
return cls.objects.filter(address="5360 Wallaby Lane").first().pk
class Meta:
ordering = ["name"]
When constructing another class that references this field, we can set a default as follows:
class Neighborhood(models.Model):
favourite_house = models.ForeignKey("civilization.House", on_delete=models.PROTECT, default=House.get_default())
name = models.CharField(max_length=100, unique=True)
#classmethod
def get_default(cls):
return cls.objects.filter(name="Upper Snootington").first().pk
This works fine. As long as this function referencing a second layer isn't called by another default field for a table, Django doesn't complain. Once I tie this in as a default to another model, however:
class City(models.Model):
favourite_neighborhood = models.ForeignKey("civilization.Neighborhood", on_delete=models.PROTECT, default=Neighborhood.get_default())
Django throws exceptions "django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.". It seems this is pretty specific to that second layer of default retrieval. The best I can surmise is that Django is trying to interact with the models while it builds the models with that second layer referencing another model.
Something tells me this is a hack and there's a better way...
Error Stack Trace:
Traceback (most recent call last):
2022-10-04T19:47:25.097693165Z File "/usr/local/lib/python3.9/threading.py", line 973, in _bootstrap_inner
2022-10-04T19:47:25.097697202Z self.run()
2022-10-04T19:47:25.097700239Z File "/usr/local/lib/python3.9/threading.py", line 910, in run
2022-10-04T19:47:25.097724934Z self._target(*self._args, **self._kwargs)
2022-10-04T19:47:25.097732858Z File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper
2022-10-04T19:47:25.097736509Z fn(*args, **kwargs)
2022-10-04T19:47:25.097739522Z File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run
2022-10-04T19:47:25.097742666Z autoreload.raise_last_exception()
2022-10-04T19:47:25.097745656Z File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception
2022-10-04T19:47:25.097748771Z raise _exception[1]
2022-10-04T19:47:25.097751654Z File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute
2022-10-04T19:47:25.097754680Z autoreload.check_errors(django.setup)()
2022-10-04T19:47:25.097757640Z File "/usr/local/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper
2022-10-04T19:47:25.097760614Z fn(*args, **kwargs)
2022-10-04T19:47:25.097763440Z File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup
2022-10-04T19:47:25.097766409Z apps.populate(settings.INSTALLED_APPS)
2022-10-04T19:47:25.097769265Z File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 114, in populate
2022-10-04T19:47:25.097772386Z app_config.import_models()
2022-10-04T19:47:25.097775245Z File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 301, in import_models
2022-10-04T19:47:25.097814770Z self.models_module = import_module(models_module_name)
2022-10-04T19:47:25.097822684Z File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-10-04T19:47:25.097827905Z return _bootstrap._gcd_import(name[level:], package, level)
2022-10-04T19:47:25.097833111Z File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-10-04T19:47:25.101634487Z File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-10-04T19:47:25.103934434Z File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
2022-10-04T19:47:25.105839169Z File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
2022-10-04T19:47:25.107814611Z File "<frozen importlib._bootstrap_external>", line 850, in exec_module
2022-10-04T19:47:25.109409635Z File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
2022-10-04T19:47:25.111132100Z File "/code/civilization/models.py", line 102, in <module>
2022-10-04T19:47:25.112666303Z class Neighborhood(models.Model):
2022-10-04T19:47:25.112769078Z File "/code/civilization/models.py", line 105, in City
2022-10-04T19:47:25.114428690Z on_delete=models.PROTECT, default= get_default_neighborhood())
2022-10-04T19:47:25.114479112Z File "/code/civilization/models.py", line 37, in get_default_neighborhood
2022-10-04T19:47:25.115610331Z return Neighborhood.get_default()
2022-10-04T19:47:25.115733686Z File "/code/civilization/models.py", line 29, in get_default
2022-10-04T19:47:25.116830129Z return cls.objects.filter(address="5360 Wallaby Lane").first().pk
2022-10-04T19:47:25.116868823Z File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 674, in first
2022-10-04T19:47:25.119852074Z for obj in (self if self.ordered else self.order_by('pk'))[:1]:
2022-10-04T19:47:25.119907893Z File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 280, in __iter__
2022-10-04T19:47:25.119917143Z self._fetch_all()
2022-10-04T19:47:25.119920693Z File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all
2022-10-04T19:47:25.119923803Z self._result_cache = list(self._iterable_class(self))
2022-10-04T19:47:25.119926782Z File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__
2022-10-04T19:47:25.119931046Z results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
2022-10-04T19:47:25.119935039Z File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1162, in execute_sql
2022-10-04T19:47:25.119938474Z sql, params = self.as_sql()
2022-10-04T19:47:25.119941476Z File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 513, in as_sql
2022-10-04T19:47:25.119957520Z extra_select, order_by, group_by = self.pre_sql_setup()
2022-10-04T19:47:25.119960883Z File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 56, in pre_sql_setup
2022-10-04T19:47:25.119963826Z order_by = self.get_order_by()
2022-10-04T19:47:25.119966609Z File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 356, in get_order_by
2022-10-04T19:47:25.119969517Z order_by.extend(self.find_ordering_name(
2022-10-04T19:47:25.119972298Z File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 740, in find_ordering_name
2022-10-04T19:47:25.119975219Z field, targets, alias, joins, path, opts, transform_function = self._setup_joins(pieces, opts, alias)
2022-10-04T19:47:25.119978235Z File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 780, in _setup_joins
2022-10-04T19:47:25.119981145Z field, targets, opts, joins, path, transform_function = self.query.setup_joins(pieces, opts, alias)
2022-10-04T19:47:25.119984116Z File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1648, in setup_joins
2022-10-04T19:47:25.120132662Z path, final_field, targets, rest = self.names_to_path(
2022-10-04T19:47:25.120632399Z File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/query.py", line 1539, in names_to_path
2022-10-04T19:47:25.121907397Z if field.is_relation and not field.related_model:
2022-10-04T19:47:25.122421805Z File "/usr/local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__
2022-10-04T19:47:25.123109833Z res = instance.__dict__[self.name] = self.func(instance)
2022-10-04T19:47:25.123140347Z File "/usr/local/lib/python3.9/site-packages/django/db/models/fields/related.py", line 95, in related_model
2022-10-04T19:47:25.123568285Z apps.check_models_ready()
2022-10-04T19:47:25.123651924Z File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 141, in check_models_ready
2022-10-04T19:47:25.124090201Z raise AppRegistryNotReady("Models aren't loaded yet.")
2022-10-04T19:47:25.124122833Z django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
I am trying to make migrations by running the following command:
python manage.py makemigrations
But, I am getting the below error:
django.db.utils.ProgrammingError: (1146, "Table 'password_management.accounts_workspace' doesn't exist")
I am using MySQL Database named as password_management.
Earlier my Django app was working fine with all the user migrations and stuff. When I made this new Model Workspace, I am getting the above mentioned error.
Full Error Details:
Traceback (most recent call last):
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute
return self.cursor.execute(query, args)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\MySQLdb\cursors.py", line 206, in execute
res = self._query(query)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\MySQLdb\cursors.py", line 319, in _query
db.query(q)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\MySQLdb\connections.py", line 254, in query
_mysql.connection.query(self, query)
MySQLdb._exceptions.ProgrammingError: (1146, "Table 'password_management.accounts_workspace' doesn't exist")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\manage.py", line 22, in <module>
main()
File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line
utility.execute()
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\base.py", line 455, in execute
self.check()
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\management\base.py", line 487, in check
all_issues = checks.run_checks(
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\core\checks\urls.py", line 61, in _load_all_namespaces
url_patterns = getattr(resolver, "url_patterns", [])
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\utils\functional.py", line 49, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\urls\resolvers.py", line 696, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\utils\functional.py", line 49, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\urls\resolvers.py", line 689, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\inviteandresetpass\urls.py", line 21, in <module>
path("accounts/", include("apps.accounts.urls")), # URLs of Login/Registration System
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\urls\conf.py", line 38, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\apps\accounts\urls.py", line 4, in <module>
from .views import (
File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\apps\accounts\views.py", line 16, in <module>
from .forms import (
File "D:\Projects\meistery\projects\pricing_password_management_poc\inviteandresetpass\apps\accounts\forms.py", line 14, in <module>
for i in range(len(workspaces)):
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\models\query.py", line 302, in __len__
self._fetch_all()
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\models\query.py", line 1507, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\models\query.py", line 57, in __iter__
results = compiler.execute_sql(
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\models\sql\compiler.py", line 1361, in execute_sql
cursor.execute(sql, params)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\utils.py", line 103, in execute
return super().execute(sql, params)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\utils.py", line 67, in execute
return self._execute_with_wrappers(
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
with self.db.wrap_database_errors:
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\django\db\backends\mysql\base.py", line 75, in execute
return self.cursor.execute(query, args)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\MySQLdb\cursors.py", line 206, in execute
res = self._query(query)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\MySQLdb\cursors.py", line 319, in _query
db.query(q)
File "D:\Projects\meistery\venvs\inviteandresetpass\lib\site-packages\MySQLdb\connections.py", line 254, in query
_mysql.connection.query(self, query)
django.db.utils.ProgrammingError: (1146, "Table 'password_management.accounts_workspace' doesn't exist")
My Workspace model is below:
class Workspace(models.Model):
name = models.CharField(max_length=254)
name_slug = models.SlugField(editable=False)
admin = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self) -> str:
"""
Returns a string to as an instance name
"""
return (self.name)
def save(self, *args, **kwargs):
if self.name:
try:
group = Group.objects.get(name=self.name)
group.delete()
except Exception as ex:
print(ex)
permissions = Permission.objects.all
for p in permissions:
if p.name.endswith(self.name):
p.delete()
super(Workspace, self).save(*args, **kwargs)
self.name_slug = slugify(self.name)
workspace_group = Group.objects.create(
name="manage-" + self.name_slug
)
content_type = ContentType.objects.get_for_model(Workspace)
permissions = []
permissions.append(
Permission.objects.create(
codename='can_remove_from_workspace_%s' % self.name_slug,
name='Can Remove User From Workspace %s' % self.name,
content_type=content_type,
)
)
permissions.append(
Permission.objects.create(
codename='can_add_to_workspace_%s' % self.name_slug,
name='Can Add User To Workspace %s' % self.name,
content_type=content_type,
)
)
permissions.append(
Permission.objects.create(
codename='can_view_from_workspace_%s' % self.name_slug,
name='Can View User From Workspace %s' % self.name,
content_type=content_type,
)
)
workspace_group.permissions.set(permissions)
super(Workspace, self).save(*args, **kwargs)
def make_admin(self, user):
user.add_workspace(self)
self.admin = user
self.save()
def remove_admin(self):
self.admin = None
self.save()
def invite_workspace_user(self, user, invite_form_data):
workspace = invite_form_data["workspace"]
invitation = Invitation.objects.create(
created_by = user,
invitee_email = invite_form_data["invitee_email"],
invitee_first_name = invite_form_data["invitee_first_name"],
invitee_last_name = invite_form_data["invitee_last_name"]
)
invitation.send_invite_user_email(workspace)
def get_by_name(self, name):
try:
return self.objects.get(name=name)
except:
return None
In admins.py I have:
from .models import Workspace
admin.site.register(Workspace)
In forms.py I have:
from .models import Workspace
WORKSPACES_CHOICES = []
workspaces = Workspace.objects.all()
for i in range(len(workspaces)):
WORKSPACES_CHOICES.append(tuple((str(i + 1), workspaces[i].name)))
WORKSPACES_CHOICES = tuple(WORKSPACES_CHOICES)
class InviteUserByAdminForm(forms.ModelForm):
workspaces = forms.MultipleChoiceField(
widget=forms.CheckboxSelectMultiple,
choices=WORKSPACES_CHOICES
)
class Meta:
model = Invitation
fields = (
"invitee_first_name",
"invitee_last_name",
"sent_to",
"workspaces",
)
I have already tried all the solutions mentioned in this thread at stackoverflow. But, none of them worked for me.
Anyone can tell me what's wrong?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I already know that this is going to be a trashy question, as per the SO question guidelines, but I have to keep details down to a minimum. I have a traceback, but I don't know why its throwing an error.
Traceback:
Exception in thread django-main-thread:
Traceback (most recent call last):
File "...USER...\threading.py", line 954, in _bootstrap_inner
self.run()
File "...USER...\threading.py", line 892, in run
self._target(*self._args, **self._kwargs)
File "...USER...\site-packages\django\utils\autoreload.py", line 64, in wrapper
fn(*args, **kwargs)
File "...USER...\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
self.check(display_num_errors=True)
File "...USER...\site-packages\django\core\management\base.py", line 419, in check
all_issues = checks.run_checks(
File "...USER...\site-packages\django\core\checks\registry.py", line 76, in run_checks
new_errors = check(app_configs=app_configs, databases=databases)
File "...USER...\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "...USER...\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "...USER...\site-packages\django\urls\resolvers.py", line 412, in check
for pattern in self.url_patterns:
File "...USER...\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "...USER...\site-packages\django\urls\resolvers.py", line 598, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "...USER...\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "...USER...\site-packages\django\urls\resolvers.py", line 591, in urlconf_module
return import_module(self.urlconf_name)
File "...USER...\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 855, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "...USER...\urls.py", line 20, in <module>
path('django_app/', include('django_app.urls')),
File "...USER...\site-packages\django\urls\conf.py", line 34, in include
urlconf_module = import_module(urlconf_module)
File "...USER...\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 855, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "...USER...\urls.py", line 2, in <module>
from . import views
File "...USER...\views.py", line 185
if t > 0:
^
SyntaxError: invalid syntax
The "syntax error" is being thrown inside of a class that I made inside of my views.py file...
A general, crude idea of the code is:
import os
import sys
import numpy
some other imports
class my_constructor:
def __init__(self):
some stuff
def func(self):
some logic
(t, b, l, r) = self.removed_space
(w, h, th) = self.dimensions
if l > 0 or r > 0:
ppi_w = 0
if t > 0 or b > 0:
ppi_h = 0
if t > 0: #this is line 185 from the last line in the traceback
t = round(t * ppi_h)
if len(array) > 2:
t_a = 0
else:
t_a = 0
ar = 0
m = 0
if b > 0:
b = 0
if len(array) > 2:
b_a = 0
else:
b_a = 0
ar = 0
m = 0
I know a true answer for this likely isn't a reasonable request, but I am desperate and just asking for general ideas as to why this error might actually be occuring. I am using notepad++, so spacing is consistent. I know the syntax for the if statement is right... and apart from that, its got me beat.
if t > 0:
There's nothing wrong with that line. Check the previous line of code for imbalanced parentheses.
I want to add one of my models to the admin panel, but this error falls:
> Traceback (most recent call last): File
> "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\threading.py",
> line 932, in _bootstrap_inner
> self.run() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\threading.py",
> line 870, in run
> self._target(*self._args, **self._kwargs) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py",
> line 53, in wrapper
> fn(*args, **kwargs) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py",
> line 109, in inner_run
> autoreload.raise_last_exception() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py",
> line 76, in raise_last_exception
> raise _exception[1] File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py",
> line 357, in execute
> autoreload.check_errors(django.setup)() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py",
> line 53, in wrapper
> fn(*args, **kwargs) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py",
> line 24, in setup
> apps.populate(settings.INSTALLED_APPS) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py",
> line 122, in populate
> app_config.ready() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\apps.py",
> line 24, in ready
> self.module.autodiscover() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\__init__.py",
> line 26, in autodiscover
> autodiscover_modules('admin', register_to=site) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\module_loading.py",
> line 47, in autodiscover_modules
> import_module('%s.%s' % (app_config.name, module_to_search)) File
> "C:\Users\smirn\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:\Users\smirn\OneDrive\Desktop\SYZYGY\Coding\Python\Django\Megan\Fridge\admin.py",
> line 13, in <module>
> admin.site.register([Product, Fridge, ProductObject]) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\sites.py",
> line 104, in register
> if model._meta.abstract: AttributeError: type object 'ProductObject' has no attribute '_meta'
models.py:
from django.db import models as m
from django.conf import settings
import datetime
def mounth():
now = datetime.datetime.now()
return now + datetime.timedelta(days=20)
class Product(m.Model):
product_name = m.CharField(max_length=200)
product_calories = m.PositiveIntegerField(blank=True)
def __str__(self):
return self.product_name
class Fridge(m.Model):
OPTIONS = (
("1", "BASIC"),
("2", "PRO"),
("3", "KING"),
)
fridge_owner = m.ForeignKey(settings.AUTH_USER_MODEL, on_delete=m.CASCADE)
fridge_mode = m.CharField(max_length=5, choices=OPTIONS)
class Recipe(m.Model):
recipe_name = m.CharField(max_length=200)
recipe_products = m.ManyToManyField(Product)
recipe_description = m.TextField()
def __str__(self):
return self.recipe_name
class ProductObject(): # Не знаю как сделать правильно. Вдруг это можно реализовать по другому
product_obj_fridge = m.ForeignKey(Fridge, on_delete=m.CASCADE)
product_obj_product = m.ManyToManyField(Product)
product_shelf_life = m.DateField(default=mounth())
product_count = m.PositiveIntegerField(default=1)
class Meta:
ordering = ('product_shelf_life', )
admin.py:
from django.contrib import admin
from .models import Product, Fridge, Recipe, ProductObject
from tinymce.widgets import TinyMCE
from django.db import models
# Register your models here.
class RecipeAdmin(admin.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': TinyMCE}
}
admin.site.register([Product, Fridge, ProductObject])
admin.site.register(Recipe, RecipeAdmin)
If I remove the ProductObject in the registration in the admin panel, then there will be no error, but I do not understand this error at all. It seems that everything should be correct, but for some reason not
Please, help me!
In model ProductObject you are missing m.Model in the definition.
Without this the Meta field can not be constructed.
I can not locate this error.
Error is genereted after I added one field in disease that is contact and taggable manager in models
If that is correct than is this error is generated due to Id field that I gave manually
Help to me get out of this!!
personal(myapp)/urls.py
urlpatterns = [
url(r'^.*doctorsu/$', views.doctorsu.as_view(), name = 'doctorsu'),
url(r'^.*disease/$', views.AddDisease.as_view(), name = 'AddDisease'),
]
mysite/urls.py
urlpatterns = [
url(r'^$',include('personal.urls')),
url(r'^taggit/',include('taggit_selectize.urls')),
]
models.py
class DoctorSignup(models.Model):
contact_regex = RegexValidator(regex=r'^[789]\d{9}$',message="Phone number must be start with 7,8 or 9")
doid = models.AutoField(verbose_name='Doctor Id',primary_key=True,default=0)
email = models.CharField(max_length=50)
contact = models.CharField(validators=[contact_regex])
class TaggedSymptoms(TaggedItemBase):
content_object = models.ForeignKey("Disease")
class TaggedMedicine(TaggedItemBase):
content_object = models.ForeignKey("Disease")
class Disease(models.Model):
did = models.AutoField(verbose_name='Disease Id', primary_key=True,default=0)
dName = models.CharField(max_length=20)
dtype = models.CharField(max_length=10)
symptoms = TaggableManager(through=TaggedSymptoms)
symptoms.rel.related_name = "+"
medi = TaggableManager(through=TaggedMedicine)
medi.rel.related_name = "+"
views.py
class doctorsu(TemplateView):
template_name = 'personal/doctorsu.html'
def get(self, request):
dsform = DoctorSignupForm()
data = DoctorSignup.objects.all()
args = {'dsform': dsform,'data': data}
return render(request,self.template_name,args)
def post(self, request):
dsform = DoctorSignupForm(request.POST)
if dsform.is_valid():
dsform.save()
cd = dsform.cleaned_data
args = {'dsform': dsform , 'cd': cd}
return render(request,self.template_name,args)
return render(request, 'personal/doctorsu.html')
class AddDisease(TemplateView):
template_name = 'personal/disease.html'
def get(self, request):
dform = DiseaseForm()
ddata = Disease.objects.all()
args = {'dform': dform,'ddata': ddata}
return render(request,self.template_name,args)
def post(self, request):
dform = DiseaseForm(request.POST)
if dform.is_valid():
dform.save()
cd = dform.cleaned_data
args = {'dform': dform , 'cd': cd}
return render(request,self.template_name,args)
forms.py
class DoctorSignupForm(forms.ModelForm):
dname = forms.CharField()
email = forms.EmailField()
contact = forms.RegexField(regex=r'^[789]\d{9}$',error_messages="Enter valid phone no.")
class Meta:
model = DoctorSignup
fields = "__all__"
class DiseaseForm(ModelForm):
dName = forms.CharField(help_text="Enter disease")
symptoms = TagField(help_text="Enter symptoms separated by comma")
medicine = TagField()
class Meta:
model = Disease
fields = "__all__"
Traceback
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line
utility.execute()
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 327, in execute
self.check()
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver
return check_method()
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py", line 254, in check
for pattern in self.url_patterns:
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "E:\IT\project\program\20-8-17\mysite\mysite\urls.py", line 7, in <module>
url(r'^$',include('personal.urls')),
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\conf\urls\__init__.py", line 50, in include
urlconf_module = import_module(urlconf_module)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 986, in _gcd_import
File "<frozen importlib._bootstrap>", line 969, in _find_and_load
File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 665, in exec_module
File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
File "E:\IT\project\program\20-8-17\mysite\personal\urls.py", line 2, in <module>
from . import views
File "E:\IT\project\program\20-8-17\mysite\personal\views.py", line 3, in <module>
from personal.forms import *
File "E:\IT\project\program\20-8-17\mysite\personal\forms.py", line 50, in <module>
class DoctorSignupForm(forms.ModelForm):
File "E:\IT\project\program\20-8-17\mysite\personal\forms.py", line 90, in DoctorSignupForm
contact = forms.RegexField(regex=r'^[789]\d{9}$',error_messages="Enter valid phone no.")
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\fields.py", line 517, in __init__
super(RegexField, self).__init__(max_length, min_length, *args, **kwargs)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\fields.py", line 228, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "C:\Users\Charmi Shah\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\forms\fields.py", line 122, in __init__
messages.update(error_messages or {})
ValueError: dictionary update sequence element #0 has length 1; 2 is required
error_messages should be a dict, not a string.
See the docs.