I have problems with circularity in my two files. Model import function to run when create object and this function import model to check if code in unique.
How use model in function and function in model without problem with circularity? I checked questions simillar to my problem but i still don't know to fix this issue.
models.py
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from .middleware.current_user import get_current_user
from shortener.utils import create_shortcode
from django.conf import settings
CODE_MAX_LENGTH = getattr(settings, 'CODE_MAX_LENGTH', 16)
class Shortener(models.Model):
url = models.URLField()
code = models.CharField(unique=True, blank=True, max_length=CODE_MAX_LENGTH)
author = models.ForeignKey(User, blank=True, null=True) # Allow anonymous
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
def save(self, *args, **kwargs):
if not self.pk:
self.author = get_current_user()
if self.code in [None, ""]:
self.code = create_shortcode()
elif self.code.find(' ') != -1:
self.code = self.code.replace(' ', '_')
if self.url not in ["http", "https"]:
self.url = "http://{0}".format(self.url)
super(Shortener, self).save(*args, **kwargs)
def __str__(self):
return self.url
def __unicode__(self):
return self.url
def get_short_url(self):
return reverse("redirect", kwargs={'code': self.code})
Utils.py
import random
import string
from django.conf import settings
from shortener.models import Shortener
SIZE = getattr(settings, 'CODE_GENERATOR_MAX_SIZE', 12)
def code_generator(size=SIZE):
return ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(size))
def create_shortcode():
code = code_generator()
if Shortener.objects.filter(code=code).exists():
create_shortcode()
return code
Traceback:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x037EAB28>
Traceback (most recent call last):
File "C:\Users\loc\shortener\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\loc\shortener\lib\site-packages\django\core\management\commands\runserver.py", line 113, in inner_run
autoreload.raise_last_exception()
File "C:\Users\loc\shortener\lib\site-packages\django\utils\autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "C:\Users\loc\shortener\lib\site-packages\django\utils\six.py", line 685, in reraise
raise value.with_traceback(tb)
File "C:\Users\loc\shortener\lib\site-packages\django\utils\autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "C:\Users\loc\shortener\lib\site-packages\django\__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\loc\shortener\lib\site-packages\django\apps\registry.py", line 108, in populate
app_config.import_models(all_models)
File "C:\Users\loc\shortener\lib\site-packages\django\apps\config.py", line 199, in import_models
self.models_module = import_module(models_module_name)
File "E:\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 "C:\Users\loc\PycharmProjects\DjangoURLShortener\shortener\models.py", line 4, in <module>
from shortener.utils import create_shortcode
File "C:\Users\loc\PycharmProjects\DjangoURLShortener\shortener\utils.py", line 4, in <module>
from shortener.models import Shortener
ImportError: cannot import name 'Shortener'
Short answer: Move the create_shortcode implementation into the models.py module, it's just 3 lines of code to generate codes in there and you avoid the circular imports. Do the filters inside the model and Shortener.save method with self.objects.filter(...).
Longer answer: The uuid module and the uuid.uuid4 function is better (than writing a possibly buggy implementation yourself) for generating unique codes. You are, at the moment, generating 12-character or 12-byte random codes, and the UUID module can generate 16-byte codes for you out of the box. If you want enable user-definable or overridable codes but wish to generate very unique codes automatically:
code = models.CharField(unique=True, max_length=16, default=uuid.uuid4)
Related
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 3 years ago.
Improve this question
Creating forms from models
i'm new to django and try to models form but unfortunate get some bizarre error even i twice check my code as well i checked django documentation but not figure out my issue...
i visit this django documentation but not figure out yet!!! quite confusing!
https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/
AppFive/forms.py
from django import forms
from AppFive.models import User
from django.forms import ModelForm
class NewUserForm(ModelForm):
class Meta:
model = User
fields = '__all__ ' # <-- Mistake over here - This Line. SOLVED!
AppFive/models.py
from django.db import models
# Create your models here.
class User(models.Model):
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
email = models.EmailField(max_length=264,unique=True)
AppFive/views.py
from django.shortcuts import render
# from django.http import HttpResponse
# from AppFive.models import User
# Create your views hereself.
from AppFive.forms import NewUserForm
def index(request):
return render(request,'AppFive/index.html')
def users(request):
form = NewUserForm()
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print('ERROR : F O R M I N V A L I D')
return render(request,'AppFive/users.html',{'form':form})
Traceback (most recent call last):
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\threading.py", line 926, in _bootstrap_inner
self.run()
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
all_namespaces = _load_all_namespaces(resolver)
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
url_patterns = getattr(resolver, 'url_patterns', [])
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\utils\functional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\urls\resolvers.py", line 572, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\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\Khan\Desktop\Python Bootcamp\PB2\ProFive\ProFive\urls.py", line 18, in <module>
from AppFive import views
File "C:\Users\Khan\Desktop\Python Bootcamp\PB2\ProFive\AppFive\views.py", line 5, in <module>
from AppFive.forms import NewUserForm
File "C:\Users\Khan\Desktop\Python Bootcamp\PB2\ProFive\AppFive\forms.py", line 5, in <module>
class NewUserForm(ModelForm):
File "C:\Users\Khan\Miniconda3\envs\MyDjangoEnv\lib\site-packages\django\forms\models.py", line 235, in __new__
raise TypeError(msg)
TypeError: NewUserForm.Meta.fields cannot be a string. Did you mean to type: ('__all__ ',)?
python 3.7.4
django (2, 2, 3, 'final', 0)
fields = '__all__ '
It has an extra space in the string. Remove it!
As mentioned by caot, you need to provide the code for correct answer. Anyway, let me make a guess.
When you try to generate a form out of a model, you need to specify the model as well as the fields in it (that you are interested in displaying / capturing).
The fields should be assigned a list consisting (strictly) of field names, each as a string. If you intend to include all fields, 'all' as a string (yes, string; not a list) can be specified.
I guess, either you made a mistake in specifying all or you included the fields as a string (fields = 'pub_date' or fields = 'pub_date, headline')
If my answer does not solve your issue, please show the full code.
Cheers
I am creating a blog app from the book django 2 by example by antonio mele.
I am on the sub topic creating model managers.
However, as soon as i edit my models.py file, the power shell window that hosts the local server displays this error:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03B61300>
Traceback (most recent call last):
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inne
r_run
autoreload.raise_last_exception()
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception
raise _exception[1]
File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\__init__.py", line 337, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\public\django\my_env\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\public\django\my_env\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\public\django\my_env\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\public\django\my_env\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\public\django\mysite\blog\models.py", line 1, in <module>
class PublishedManager(models.Manager):
NameError: name 'models' is not defined
This is the code on the models.py file
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset()\
.filter(status='published')
class Post(models.Model):
# ...
objects = models.Manager() # The default manager.
published = PublishedManager() # Our custom manager
#TDK im not sure what youmean by 'includes' but this is the the admin.py file
from django.contrib import admin
from .models import Post
#admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'author', 'publish',
'status')
list_filter = ('status', 'created', 'publish', 'author')
search_fields = ('title', 'body')
prepopulated_fields = {'slug': ('title',)}
raw_id_fields = ('author',)
date_hierarchy = 'publish'
ordering = ('status', 'publish')
# Tony and Jonah, i added the code from django.db import models
and i get this error message too
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x030233D8>
Traceback (most recent call last):
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inne
r_run
self.check(display_num_errors=True)
File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\base.py", line 425, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'title', which is not a callable,
an attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[1]' refers to 'slug', which is not a callable, a
n attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'author', which is not a callable,
an attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[3]' refers to 'publish', which is not a callable
, an attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
<class 'blog.admin.PostAdmin'>: (admin.E108) The value of 'list_display[4]' refers to 'status', which is not a callable,
an attribute of 'PostAdmin', or an attribute or method on 'blog.Post'.
System check identified 5 issues (0 silenced).
Am really i was sharing the wrong models.py file.
# Daniel This complete code in the file:
from django.db import models
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset()\
.filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
unique_for_date='publish')
author = models.ForeignKey(User,
on_delete=models.CASCADE,
related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
default='draft')
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
# ...
objects = models.Manager() # The default manager.
published = PublishedManager() # Our custom manager
and this is the error message i am getting now
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x036C1420>
Traceback (most recent call last):
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inne
r_run
autoreload.raise_last_exception()
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception
raise _exception[1]
File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\__init__.py", line 337, in execute
autoreload.check_errors(django.setup)()
File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "C:\Users\public\django\my_env\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\public\django\my_env\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\public\django\my_env\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\public\django\my_env\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\public\django\mysite\blog\models.py", line 9, in <module>
class Post(models.Model):
File "C:\Users\public\django\mysite\blog\models.py", line 17, in Post
author = models.ForeignKey(User,
NameError: name 'User' is not defined
As i alluded to in my comment, you’ve probably forgotten to include
from django.db import models
Now that error has gone it looks like you also need
from django.contrib.auth.models import User
I'm guessing you haven't imported the models code:
from django.db import models
I am trying to use the CsvModel module from django-adaptors. However, when i use from adaptor.model import CsvModel and makemigrations, below errors occured.
Can anyone advise the reason why? my code in the model is as follows:
from django.db import models
from adaptor.model import CsvModel
from adaptor.fields import CharField, DecimalField
class User(models.Model):
user_name = models.CharField(max_length = 50, null=True, unique=True)
def __str__(self):
return self.user_name
class Profile(models.Model):
rubbish = models.DecimalField(max_digits= 1000, decimal_places=3, null=True)
user = models.CharField(max_length = 50, unique = True, null=True)
hobby = models.CharField(max_length = 50, null=True)
job = models.CharField(max_length = 60, null=True)
class Trial(CsvModel):
rubbish = DecimalField()
user = CharField()
hobby = CharField()
class Meta:
dbmodel = Profile
delimiter = ','
has_header = True
Error message is as follows:
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
django.setup()
File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
app_config.import_models()
File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/Cellar/python/3.6.4_3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/pangkachun/Desktop/smallpro2/small_pro/small/models.py", line 2, in <module>
from adaptor.model import CsvModel
File "/usr/local/lib/python3.6/site-packages/adaptor/model.py", line 269
except ValueError, e:
^ . `
You are using python3.6 but the library looks like it is made for python2.5-
For Python 3 it should be
except ValueError as e:
source
You may have to find a different csv plugin like django-csvimport and possibly change your strategy accordingly
I'm currently trying to build a blog using Django. I've been facing this error for a few hours now. I'm not quite sure if this has anything to do with the directories but the error occurs when I try to register my model in the admin.py file.
from django.contrib import admin
from .models import Post
# Register models
admin.site.register(Post)
The directories look as follows:
blog
models
Post
Category
admin.py
settings
static
templates
Trace:
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7ffb589a67b8>
Traceback (most recent call last):
File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run
autoreload.raise_last_exception()
File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception
raise _exception[1]
File "/usr/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute
autoreload.check_errors(django.setup)()
File "/usr/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper
fn(*args, **kwargs)
File "/usr/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/lib/python3.6/site-packages/django/apps/registry.py", line 120, in populate
app_config.ready()
File "/usr/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 23, in ready
self.module.autodiscover()
File "/usr/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/usr/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/hallak/Projects/hallak.io/hallak_blog/admin.py", line 5, in <module>
admin.site.register(Post)
File "/usr/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 102, in register
for model in model_or_iterable:
TypeError: 'module' object is not iterable
Post:
from django.db import models
from django.utils import timezone
class Post(models.Model):
# Auto-generated ID
id = models.AutoField(primary_key=True)
# Title
title = models.CharField(max_length=100)
# Slug
slug = models.SlugField(max_length=100)
# Content
body = models.TextField()
# Timestamps
created_on = models.DateField(auto_now_add=True)
published_on = models.DateTimeField(blank=True, null=True)
# Category
category = models.ForeignKey('.Category', on_delete=models.DO_NOTHING)
# Author
author = models.ForeignKey('auth.User', on_delete=models.DO_NOTHING)
# Publish post
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
Category:
from django.db import models
class Category(models.Model):
# Auto-generated ID
id = models.AutoField(primary_key=True)
# Title
title = models.CharField(max_length=100)
# Slug
slug = models.SlugField(max_length=100)
# Timestamps
created_on = models.DateField(auto_now_add=True)
The error is happening here: https://github.com/django/django/blob/master/django/contrib/admin/sites.py#L100-L101
Whenever I comment the register line everything works fine.
Instead of writing "from .models import Post" you should write "from .models.Post import Post".
First "Post" is a modulename (file name), second one is a class name.
i' ve Django 1.9.2 with python 3.4.2 in a virtualenvironment.
I' ve many applications, and the 2 related are common and shop.
common/models.py contains:
from django.apps import apps
class Document(CLDate):
user = models.ForeignKey(User)
assessmentorder = models.ForeignKey(apps.get_model('shop', 'AssessmentOrder'), blank=True, null=True)
shop/models.py contains:
from common.models import ServiceModel
class AssessmentOrder(CLDate):
"""AssessmentOrder model"""
order = models.ForeignKey(Order)
comment = models.TextField()
.
This is a circular import, and i read many strategy to resolve it (including apps.get_model), but none of them seem to work for me. I also tried
apps.get_model('shop.AssessmentOrder')
, but the same. The complete error message is the following:
File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run
autoreload.raise_last_exception()
File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/importlib/__init__.py", line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
File "<frozen importlib._bootstrap>", line 1129, in _exec
File "<frozen importlib._bootstrap>", line 1471, in exec_module
File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
File "/home/hidden/git/sccdb/sccdb/common/models.py", line 25, in <module>
class Document(CLDate):
File "/home/hidden/git/sccdb/sccdb/common/models.py", line 28, in Document
assessmentorder = models.ForeignKey(apps.get_model('shop.AssessmentOrder'), blank=True, null=True)
File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/apps/registry.py", line 194, in get_model
self.check_models_ready()
File "/home/hidden/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/apps/registry.py", line 131, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Is it somehow related to my django version or python3, or what am i doing wrong?
Instead of doing using get_model function in foreign key declaration, you can simply put the model name as string and it'll still work:
assessmentorder = models.ForeignKey('shop.AssessmentOrder', blank=True, null=True)
This should resolve the issue
Don't include models, just put a path to them. As it described in docs
from django.conf import settings
class Document(CLDate):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
assessmentorder = models.ForeignKey('shop.AssessmentOrder', blank=True, null=True)
And
class AssessmentOrder(CLDate):
"""AssessmentOrder model"""
order = models.ForeignKey('yourapp.Order')
comment = models.TextField()