I've model which represents settings in my system and I use it from another part of my application so that import has 3 levels WORKING CODE <- Module <- Model
Model Variables
from django.db import models
class Variables(models.Model):
key = models.CharField(max_length = 20, verbose_name = 'Variable')
value = models.CharField(max_length = 1024)
class Meta:
app_label = 'core'
def __unicode__(self):
return '%s: %s' % (self.key, self.value,)
Here is the code I'm using it from
Module variables.py
from core.models.storage import Variables
def get_var(name):
return Variables.objects.get(key = name)
Module config.py
var = get_var('some_key')
When I use this stuff from django shell everything works well but when I call get_var function I've ImportError exception
storage.py
from django.db import models
class Variables(models.Model):
key = models.CharField(max_length = 20, verbose_name = 'Variable')
value = models.CharField(max_length = 1024)
class Meta:
app_label = 'core'
def __unicode__(self):
return '%s: %s' % (self.key, self.value,)
File "monitor_cli.py", line 19, in
print worker.get_provider()
File "/home/sultan/Project/monitor/app/worker.py", line 14, in get_provider
print Variables.objects.get(pk=1)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 132, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 341, in get
clone = self.filter(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 550, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 568, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1172, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1060, in add_filter
negate=negate, process_extras=process_extras)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1226, in setup_joins
field, model, direct, m2m = opts.get_field_by_name(name)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 307, in get_field_by_name
cache = self.init_name_map()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 337, in init_name_map
for f, model in self.get_all_related_m2m_objects_with_model():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 414, in get_all_related_m2m_objects_with_model
cache = self._fill_related_many_to_many_cache()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/options.py", line 428, in _fill_related_many_to_many_cache
for klass in get_models():
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 167, in get_models
self._populate()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/loading.py", line 76, in load_app
app_module = import_module(app_name)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
ImportError: No module named c
Get rid of the models directory, and put all your models in a models.py file, unless you have a VERY good reason not to. Change your imports to from core.models import Variable (rename your Variables class to Variable - django models should be named as the singular not the plural).
The problem probably has to do with the fact that your models live in namespaces other than models; ie. models.storage. The django infrastructure expects certain things to be in certain places. If you're going to put models in separate namespaces like you're doing, you should be importing them from the __init__.py file within the models module. Don't do this, again, unless you have a very good reason.
Finally, when asking questions of this nature, you should provide a lot more information. You should show the code of all of the relevant files. You should provide detail on what you've done that deviates from the convention of django (in this case, a models directory rather than a models.py file). You should also show relevant settings from settings.py, in this case, your INSTALLED_APPS setting. You should also tell us what version of django and python you are using; this is sometimes relevant. More information upfront is much better than less information.
Related
I'm using Django allauth as my user account framework for my django site. The docs show there is an ACCOUNT_USERNAME_MIN_LENGTH however there is no ACCOUNT_USERNAME_MAX_LENGTH for some reason.
Is there any way to create a max length for username?
Here's my custom allauth signup form - maybe I can do something here?:
class AllauthSignupForm(forms.Form):
captcha = ReCaptchaField(
public_key=config("RECAPTCHA_PUBLIC_KEY"),
private_key=config("RECAPTCHA_PRIVATE_KEY"),
)
class Meta:
model = User
def signup(self, request, user):
""" Required, or else it throws deprecation warnings """
pass
Edit: Trying to subclass SignupView
draft1/forms.py
class AllauthSignupForm(SignupForm):
def __init__(self, *args, **kwargs):
super(AllauthSignupForm, self).__init__(*args, **kwargs)
self.fields['username']['validators'] += MaxLengthValidator(150,
"Username should be less than 150 character long")
captcha = ReCaptchaField(
public_key=config("RECAPTCHA_PUBLIC_KEY"),
private_key=config("RECAPTCHA_PRIVATE_KEY"),
)
class Meta:
model = User
def signup(self, request, user):
""" Required, or else it throws deprecation warnings """
pass
draft1/views.py
from allauth.account.views import SignupView
class MySignupView(SignupView):
form_class = AllauthSignupForm
allauth/account/urls.py
url(r"^signup/$", MySignupView.as_view(), name="account_signup"),
draft1/settings.py
ACCOUNT_SIGNUP_FORM_CLASS = 'draft1.forms.AllauthSignupForm'
The above code returns this error:
Traceback (most recent call last):
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/utils/autoreload.py", line 228, in wrapper
fn(*args, **kwargs)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
self.check(display_num_errors=True)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/base.py", line 359, in check
include_deployment_checks=include_deployment_checks,
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/management/base.py", line 346, in _run_checks
return checks.run_checks(**kwargs)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/checks/urls.py", line 16, in check_url_config
return check_resolver(resolver)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/core/checks/urls.py", line 26, in check_resolver
return check_method()
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/urls/resolvers.py", line 254, in check
for pattern in self.url_patterns:
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/urls/resolvers.py", line 405, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
return import_module(self.urlconf_name)
File "/Users/zorgan/Desktop/postr1/lib/python3.5/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 "/Users/zorgan/Desktop/vorsso/venvor/draft1/urls.py", line 6, in <module>
from . import views
File "/Users/zorgan/Desktop/vorsso/venvor/draft1/views.py", line 11, in <module>
from .forms import UserSettingsForm
File "/Users/zorgan/Desktop/vorsso/venvor/draft1/forms.py", line 8, in <module>
from allauth.account.forms import SignupForm
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/allauth/account/forms.py", line 228, in <module>
class BaseSignupForm(_base_signup_form_class()):
File "/Users/zorgan/Desktop/postr1/lib/python3.5/site-packages/allauth/account/forms.py", line 216, in _base_signup_form_class
fc_classname))
django.core.exceptions.ImproperlyConfigured: Module "draft1.forms" does not define a "AllauthSignupForm" class
This can be quickly done by extending DefaultAccountAdapter class and overriding the clean_username method. You need to also reference the clean_username once again after our custom validation to complete other inbuilt validations.
It can be done as follows.
from allauth.account.adapter import DefaultAccountAdapter
from django.forms import ValidationError
class UsernameMaxAdapter(DefaultAccountAdapter):
def clean_username(self, username):
if len(username) > 'Your Max Size':
raise ValidationError('Please enter a username value less than the current one')
return DefaultAccountAdapter.clean_username(self,username) # For other default validations.
Finally, point to the subclass in your settings.py
ACCOUNT_ADAPTER = 'YourProject.adapter.UsernameMaxAdapter'
Reference: https://github.com/pennersr/django-allauth/blob/8fbbf8c1d32832d72de5ed1c7fd77600af57ea6f/allauth/account/adapter.py#L244
You should use a max length validator like below. More documentation about validators here.
from django.core.validators import MaxLengthValidator
from allauth.account.forms import SignupForm
class AllauthSignupForm(SignupForm):
def __init__(self, *args, **kwargs):
self.fields['username']['validators'] += MaxLengthValidator(150, "Username should be less than 150 character long")
Not sure if this is the best way but it works.
After extending the SignupForm, Completely changed the username field with a new one that has the max_length parameter.
from django import forms
from django.utils.translation import ugettext_lazy as _
from allauth.account.forms import SignupForm
class AllauthSignupForm(SignupForm):
username = forms.CharField(label=_("Username"),
min_length=5,
max_length=20, # Change this
widget=forms.TextInput(
attrs={'placeholder':
_('Username'),
'autofocus': 'autofocus'}))
I would like to explain why there is no ACCOUNT_USERNAME_MAX_LENGTH. If you open source code you will see that max_length validator comes from username model field https://github.com/pennersr/django-allauth/blob/330bf899dd77046fd0510221f3c12e69eb2bc64d/allauth/account/forms.py#L277
username_field.max_length = get_username_max_length()
Where get_username_max_length is function that actually pulls max_length value from User model https://github.com/pennersr/django-allauth/blob/8fbbf8c1d32832d72de5ed1c7fd77600af57ea6f/allauth/utils.py#L64
def get_username_max_length():
from .account.app_settings import USER_MODEL_USERNAME_FIELD
if USER_MODEL_USERNAME_FIELD is not None:
User = get_user_model()
max_length = User._meta.get_field(USER_MODEL_USERNAME_FIELD).max_length
else:
max_length = 0
return max_length
First approach: So you could change max_length value directly on your User's model username field if you have it swapped.
I don't think overriding form fields or __init__ method will actually work the it suggested by other answers, because assign of max_length happens in subclass of ACCOUNT_SIGNUP_FORM_CLASS https://github.com/pennersr/django-allauth/blob/330bf899dd77046fd0510221f3c12e69eb2bc64d/allauth/account/forms.py#L259
class BaseSignupForm(_base_signup_form_class()):
where _base_signup_form_class is function that gets your ACCOUNT_SIGNUP_FORM_CLASS
Second approach: is to subclass SignupView and override it's SignupForm read Override signup view django-allauth and How to customize user profile when using django-allauth
In that SignupForm you could actually do what #MehdiB or #PeterSobhi suggested.
ImproperlyConfigured issue occurs because of https://github.com/pennersr/django-allauth/issues/1792
So you be sure that these forms are defined in different python modules as per https://github.com/pennersr/django-allauth/issues/1749#issuecomment-304628013
# base/forms.py
# this is form that your ACCOUNT_SIGNUP_FORM_CLASS is points to
class BaseSignupForm(forms.Form):
captcha = ReCaptchaField(
public_key=config("RECAPTCHA_PUBLIC_KEY"),
private_key=config("RECAPTCHA_PRIVATE_KEY"),
)
class Meta:
model = User
def signup(self, request, user):
""" Required, or else it throws deprecation warnings """
pass
# data1/forms.py
# this is your signup form
from django.core.validators import MaxLengthValidator
from allauth.account.forms import SignupForm
class MySignupForm(SignupForm):
def __init__(self, *args, **kwargs):
super(MySignupForm, self).__init__(*args, **kwargs)
self.fields['username']['validators'] += MaxLengthValidator(150, "Username should be less than 150 character long")
# views.py
from allauth.account.views import SignupView
class MySignupView(SignupView):
form_class = MySignupForm
# urls.py
url(r"^signup/$", MySignupView.as_view(), name="account_signup"),
Try importing with the full name like in your forms :
from allauth.accouts import forms as AllauthForms
class AllauthSignupForm(AllauthForms.SignupForm):
....
i didn't test this and sorry i posted this with my phone i will reformat the answer soon
UPDATE:
This is probably a better representation of my question:
Using loadtestdata, how do you populate the auth.User database? I just want to populate the database with bogus users, and simulations that are linked to those bogus users.
I have looked at all relevant resources but I'm unable to make any headway.
Situation:
I am building a simulation model using Django and am looking to store simulation data as well as sets of parameter data. Many sets of simulation data should be linked to each user, and many sets of parameter data can be linked to each simulation. Thus, I have tried to model this under 'models.py' of my Django app.
from django.db import models
from django.conf import settings
# Create your models here.
class Simulation(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, )
date = models.DateTimeField()
# Each simulation has only one graph
# Graphing parameters
hill_num = models.CharField(max_length=3)
div_type = models.CharField(max_length=10)
s3_url = models.CharField(max_length=256)
def __str__(self):
return str(self.sim_id)
class Parameter(models.Model):
# Each simulation can have many sets of simulation parameters
simulation = models.ForeignKey('Simulation', on_delete=models.CASCADE)
lsp = models.PositiveIntegerField()
plots = models.PositiveIntegerField()
pioneer = models.BooleanField()
neutral = models.BooleanField()
# for pioneers
p_max = models.PositiveIntegerField()
p_num = models.PositiveIntegerField()
p_start = models.PositiveIntegerField()
# for non-pioneers
np_max = models.PositiveIntegerField()
np_num = models.PositiveIntegerField()
np_start = models.PositiveIntegerField()
def __str__(self):
return str(self.param_id)
./manage.py makemigrations works but when I try to populate the database with python manage.py loadtestdata auth.User:10 divexplorer.Simulation:40 divexplorer.Parameter:300, it throws this error:
auth.User(pk=72): JshtkqSzw3
auth.User(pk=73): QwPfxJc_KS1k5sgH5BN98J
auth.User(pk=74): fuEhnZ
auth.User(pk=75): a
auth.User(pk=76): XjVXXLYGz3MJSfmZ54wGxXo
auth.User(pk=77): fhOWIp
auth.User(pk=78): 5tkEhKOjX2UUbFe
auth.User(pk=79): JgG4Y4PqkcapNJJOlFW1LOQ
auth.User(pk=80): fhRmfQHNim4zM8hGPzpYdkwaHI7
auth.User(pk=81): cEPQtyByKdUs8Gw58DrfNtpsCRB_
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/utils/decorators.py", line 185, in inner
return func(*args, **kwargs)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/autofixture/management/commands/loadtestdata.py", line 225, in handle
autofixture.create(model, count, **kwargs)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/autofixture/__init__.py", line 136, in create
return autofixture.create(count, **create_kwargs)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/autofixture/base.py", line 554, in create
instance = self.create_one(commit=commit, **kwargs)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/autofixture/base.py", line 519, in create_one
instance.save()
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/db/models/base.py", line 807, in save
force_update=force_update, update_fields=update_fields)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/db/models/base.py", line 837, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/db/models/base.py", line 923, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/db/models/base.py", line 962, in _do_insert
using=using, raw=raw)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/db/models/query.py", line 1076, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1099, in execute_sql
cursor.execute(sql, params)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/db/backends/utils.py", line 80, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Users/evanma/anaconda/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "user_id" of relation "divexplorer_simulation" does not exist
LINE 1: INSERT INTO "divexplorer_simulation" ("user_id", "date", "hi...
I have spent hours trying to work through this error but to no avail. Any ideas?
I have tried renaming the argument db_column in the ForeignKey function, applying default values, but none of them work. Would appreciate some input thank you very much!
I believe you need to specify if related models should also be created with random values.
Please check the docs: http://django-autofixture.readthedocs.io/en/latest/loadtestdata.html
Where it is stated:
There are a few command line options available. Mainly to control the behavior of related fields. If foreingkey or many to many fields should be populated with existing data or if the related models are also generated on the fly. Please have a look at the help page of the command for more information:
django-admin.py help loadtestdata
Unfortunately I can't check a running instance of Django know in order to point you to the exact option and it's value but checking the docs I would say that you have to use this option from loadtestdata:
...
make_option('--generate-fk', action='store', dest='generate_fk', default=None,
help=u'Do not use already existing instances for ForeignKey relations. ' +
'Create new instances instead. You can specify a comma sperated list of ' +
'field names or ALL to indicate that all foreignkeys should be generated ' +
'automatically.'),
...
based on my model:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
Base = declarative_base()
class Session(Base):
__tablename__ = 'sessions'
id = Column(Integer, primary_key=True)
token = Column(String(200))
user_id = Column(Integer, ForeignKey('app_users.id'))
user = relationship('model.user.User', back_populates='sessions')
I want to instantiate a new session through:
session = Session(token='test-token-123')
But i get:
AttributeError: mapper
The full stacktrace:
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.5/site-packages/falcon/api.py", line 227, in __call__
responder(req, resp, **params)
File "./app_user/register.py", line 13, in on_post
session = Session(token='test-token-123')
File "<string>", line 2, in __init__
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/instrumentation.py", line 347, in _new_state_if_none
state = self._state_constructor(instance, self)
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/util/langhelpers.py", line 764, in __get__
obj.__dict__[self.__name__] = result = self.fget(obj)
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/instrumentation.py", line 177, in _state_constructor
self.dispatch.first_init(self, self.class_)
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/event/attr.py", line 256, in __call__
fn(*args, **kw)
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/mapper.py", line 2976, in _event_on_first_init
configure_mappers()
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/mapper.py", line 2872, in configure_mappers
mapper._post_configure_properties()
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/mapper.py", line 1765, in _post_configure_properties
prop.init()
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/interfaces.py", line 184, in init
self.do_init()
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/relationships.py", line 1653, in do_init
self._process_dependent_arguments()
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/relationships.py", line 1710, in _process_dependent_arguments
self.target = self.mapper.mapped_table
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/util/langhelpers.py", line 850, in __getattr__
return self._fallback_getattr(key)
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/util/langhelpers.py", line 828, in _fallback_getattr
raise AttributeError(key)
I have no idea where this error is coming from and i can not really debug it.. anybody could help me with this issue?
Thanks and Greetings!
Looking at the traceback you can see these lines:
...
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/relationships.py", line 1653, in do_init
self._process_dependent_arguments()
File "/home/ubuntu/.local/lib/python3.5/site-packages/sqlalchemy/orm/relationships.py", line 1710, in _process_dependent_arguments
self.target = self.mapper.mapped_table
...
which narrow your problem down quite a bit. The relationship
user = relationship('model.user.User', back_populates='sessions')
uses a Python evaluable string as the argument, the use of which is further explained in "Configuring Relationships":
Relationships to other classes are done in the usual way, with the added feature that the class specified to relationship() may be a string name. The “class registry” associated with Base is used at mapper compilation time to resolve the name into the actual class object, which is expected to have been defined once the mapper configuration is used
If you've not imported models.user module anywhere before you try to instantiate a Session object for the first time, then the name resolving fails because the class User has not been created yet and does not exist in the registry. In other words for the name resolving to work, all classes must have been defined, which means that their bodies must have been executed.
And if you actually have imported the models.user module, check your other models and that their related model classes have been defined. Using your models for the first time triggers mapper compilation/configuration, so the source of the error could be other models as well.
If I try to run a test via PyCharm, I get this exception
...bin/python /usr/local/pycharm-4.5.1/helpers/pycharm/utrunner.py ...src/foo/foo/tests/FooEditTest.py::FooEditTest::test_issue_add true
Testing started at 15:59 ...
Traceback (most recent call last):
File "/usr/local/pycharm-4.5.1/helpers/pycharm/utrunner.py", line 139, in <module>
module = loadSource(a[0])
File "/usr/local/pycharm-4.5.1/helpers/pycharm/utrunner.py", line 41, in loadSource
module = imp.load_source(moduleName, fileName)
File "...src/foo/foo/tests/FooEditTest.py", line 45, in <module>
from foo.views.issue.forward import forward
File "...src/foo/foo/views/issue/forward.py", line 29, in <module>
class ForwardForm(forms.Form):
File "...src/foo/foo/views/issue/forward.py", line 36, in ForwardForm
group=forms.ModelChoiceField(Group.objects.exclude(groupconfig__no_issue=True).extra(
File "...python2.7/site-packages/django/db/models/manager.py", line 92, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "...python2.7/site-packages/django/db/models/query.py", line 698, in exclude
return self._filter_or_exclude(True, *args, **kwargs)
File "...python2.7/site-packages/django/db/models/query.py", line 707, in _filter_or_exclude
clone.query.add_q(~Q(*args, **kwargs))
File "...python2.7/site-packages/django/db/models/sql/query.py", line 1331, in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
File "...python2.7/site-packages/django/db/models/sql/query.py", line 1358, in _add_q
current_negated=current_negated, connector=connector)
File "...python2.7/site-packages/django/db/models/sql/query.py", line 1182, in build_filter
lookups, parts, reffed_aggregate = self.solve_lookup_type(arg)
File "...python2.7/site-packages/django/db/models/sql/query.py", line 1120, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "...python2.7/site-packages/django/db/models/sql/query.py", line 1383, in names_to_path
field, model, direct, m2m = opts.get_field_by_name(name)
File "...python2.7/site-packages/django/db/models/options.py", line 416, in get_field_by_name
cache = self.init_name_map()
File "...python2.7/site-packages/django/db/models/options.py", line 445, in init_name_map
for f, model in self.get_all_related_m2m_objects_with_model():
File "...python2.7/site-packages/django/db/models/options.py", line 563, in get_all_related_m2m_objects_with_model
cache = self._fill_related_many_to_many_cache()
File "...python2.7/site-packages/django/db/models/options.py", line 577, in _fill_related_many_to_many_cache
for klass in self.apps.get_models():
File "...python2.7/site-packages/django/utils/lru_cache.py", line 101, in wrapper
result = user_function(*args, **kwds)
File "...python2.7/site-packages/django/apps/registry.py", line 168, in get_models
self.check_models_ready()
File "...python2.7/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.
Process finished with exit code 1
I use group=forms.ModelChoiceField(Group.objects.exclude(...))
This line gets executed during importing. The call to django.setup() was not done before.
I have no clue how to solve this:
Should I call django.setup()? But where to insert this line?
Avoid using MyModel.objects.filter(...) during import time? This would need a big refactoring, since we have several ModelChoiceFields.
You're currently running the tests using the PyCharm's Python unit test runner pycharm-4.5.1/helpers/pycharm/utrunner.py.
This test runner is great for low-level unit tests (subclassed from unittest.TestCase) that don't touch Django features like the ORM, but
if the tests rely on Django-specific things like the database, then your TestCases probably need to be subclassed from django.test.testcases.TestCase and you'll need to go through PyCharm's Django test manager django_test_manage.py, which takes care of setting up the test database, initialising the model registry, and so on.
Run > Edit Configurations > Add New Configuration (+ button) > Django Tests
Set the target to foo.foo.tests.FooEditTest and make sure to put DJANGO_SETTINGS_MODULE=... in the environment variables if it doesn't find your settings.
I faced the same problem while running test cases and solved it by adding this to test file at the beginning with import statements
import os
import sys
from django.core.handlers.wsgi import WSGIHandler
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
application = WSGIHandler()
Please show your exact code (especially the extra() clause). Calling filter() or exclude() at import time is not bad because querysets are lazy but you could evaluate the queryset here that caused the exception.
Do not evaluate querysets during import time because import statements are executed only once: e.g., if a new group is created, it won't be available as a choice for you ModelChoiceField.
A bit hard to say without seeing your code, but I had a similar issue once. For me it was related to a module that was being imported by my models and that also contained an import of my models.
ModelA --- imports --> service -- imports --> ModelA
I solved this by moving the import in my service to the method that needed the import. So instead of putting it at the top of the service module, I limited the scope of the import to the method that needed this import, thus avoiding importing the models whilst initializing the service module. Fwew, I wish I could draw it for you :)
Here is what I have done so far,
1) I installed Django, and started a project using:
django-admin.py startproject helloworld
2) I downloaded django non-rel, djangotoolbox and django-mongodb-engine
I installed these using
sudo python setup.py install
3) Added djangotoolbox to INSTALLED_APPS, and added django_mongodb_engine as database back end engine.
4) I have a sample model like this:
from django.db import models
from djangotoolbox import *
class Post(models.Model):
title = models.CharField()
text = models.TextField()
tags = ListField()
comments = ListField()
5) Started python repl using: python manage.py shell
6) And did this:
from hello.models import Post
post = Post.objects.create(
... title='Hello MongoDB!',
... text='Just wanted to drop a note from Django. Cya!',
... tags=['mongodb', 'django']
... )
I got this error, I don't know how to fix this
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 149, in create
return self.get_query_set().create(**kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 416, in create
obj.save(force_insert=True, using=self.db)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 546, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/base.py", line 650, in save_base
result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 215, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 1675, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 237, in get_compiler
return connection.ops.compiler(self.compiler)(self, connection, using)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/__init__.py", line 703, in compiler
self._cache = import_module(self.compiler_module)
File "/usr/local/lib/python2.6/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/home/Desktop/helloworld/django_mongodb_engine/compiler.py", line 18, in <module>
from djangotoolbox.db.basecompiler import (
File "/usr/local/lib/python2.6/dist-packages/djangotoolbox-1.4.0-py2.6.egg/djangotoolbox/db/basecompiler.py", line 9, in <module>
from django.db.models.sql.constants import LOOKUP_SEP, MULTI, SINGLE
ImportError: cannot import name LOOKUP_SEP
What am i doing wrong here? how do i fix it?
LOOKUP_SEP was here in Django 1.4, but has been removed in 1.5, so my guess is you are using an olfer version of djangotoolbox.
You probably need to update your packages, try to follow the instructions here: http://django-mongodb-engine.readthedocs.org/en/latest/topics/setup.html