django referencing models before syncdb - python

I have an actions.py file which defines custom actions for the admin page for one of my models. It uses an intermediary page (like the default delete action) and hence has a corresponding form which is also declared in the same file.
For some reason, I had drop by database (development) and now when I try to run syncdb, it gives me the following error:
Traceback (most recent call last):
File "/home/vinayak/pyCharm/helpers/pycharm/django_manage.py", line 23, in <module>
run_module(manage_file, None, '__main__', True)
File "/usr/lib/python2.7/runpy.py", line 176, in run_module
fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 82, in _run_module_code
mod_name, mod_fname, mod_loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/home/vinayak/zenatix/customuser/manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 284, in execute
self.validate()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 310, in validate
num_errors = get_validation_errors(s, app)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/validation.py", line 34, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 196, in get_app_errors
self._populate()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 75, in _populate
self.load_app(app_name, True)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 99, in load_app
models = import_module('%s.models' % app_name)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/usr/local/lib/python2.7/dist-packages/debug_toolbar/models.py", line 63, in <module>
patch_root_urlconf()
File "/usr/local/lib/python2.7/dist-packages/debug_toolbar/models.py", line 51, in patch_root_urlconf
reverse('djdt:render_panel')
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 480, in reverse
app_list = resolver.app_dict[ns]
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 310, in app_dict
self._populate()
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 262, in _populate
for pattern in reversed(self.url_patterns):
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 346, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 341, in urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/home/vinayak/zenatix/customuser/customuser/urls.py", line 6, in <module>
admin.autodiscover()
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/__init__.py", line 29, in autodiscover
import_module('%s.admin' % app)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 40, in import_module
__import__(name)
File "/home/vinayak/zenatix/customuser/iiitd/admin.py", line 3, in <module>
from actions import grant_read_permission
File "/home/vinayak/zenatix/customuser/iiitd/actions.py", line 13, in <module>
class SelectUserForm(forms.Form):
File "/home/vinayak/zenatix/customuser/iiitd/actions.py", line 16, in SelectUserForm
clientObj = ClientInfo.objects.all()[:1].get()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 301, in get
num = len(clone)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 77, in __len__
self._fetch_all()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 854, in _fetch_all
self._result_cache = list(self.iterator())
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 220, in iterator
for row in compiler.results_iter():
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 710, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 781, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 69, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 99, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 53, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "iiitd_clientinfo" does not exist
LINE 1: ...ientinfo"."id", "iiitd_clientinfo"."corp_id" FROM "iiitd_cli...
iiitd is the name of one of my apps. The reason this is happening is because actions.py imports the iiitd_clientinfo model - but that doesn't exist yet, obviously. Currently, I make it work by excluding/commenting out my actions.py file. Surely, there has to be a work around?
I have tried the following:
south migration before syncdb - same error.
sorted out the INSTALLED_APPS order to ensure that they are in a topological order- same error
Used this in my actions.py:
try:
clientObj = ClientInfo.objects.all()[:1].get()
except ClientInfo.DoesNotExist:
clientObj = None
EDIT:
Relevent part of actions.py:
from django import forms, template
from django.contrib import admin
from django.contrib.admin import helpers
from django.shortcuts import render_to_response
from django.utils.encoding import force_unicode
from guardian.shortcuts import assign_perm
from django.utils.translation import ugettext as _
from models import ClientInfo
from customauth.models import ZenatixUser
class SelectUserForm(forms.Form):
_selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
try:
clientObj = ClientInfo.objects.all()[:1].get()
except ClientInfo.DoesNotExist:
clientObj = None
if clientObj:
client = clientObj.corp
client_name = client.shortName
client_id = client.cID
userList = ZenatixUser.objects.filter(corp__cID=client_id)
user = forms.ModelMultipleChoiceField(userList, label=client_name + ' users ')
def grant_read_permission(modeladmin, request, queryset):
Fix
class SelectUserForm(forms.Form):
_selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
def __init__(self, initial, *args, **kwargs):
super(SelectUserForm, self).__init__(*args, **kwargs)
try:
clientObj = ClientInfo.objects.all()[:1].get()
client = clientObj.corp
client_name = client.shortName
client_id = client.cID
userList = ZenatixUser.objects.filter(corp__cID=client_id)
#user = forms.ModelMultipleChoiceField(userList, label=client_name + ' users ')
self.fields['user'] = forms.ModelMultipleChoiceField(userList, label=client_name + ' users ')
self._selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
except ClientInfo.DoesNotExist:
raise Exception('Please add a client info object to the client')

It's mostly a wild guess until you post the source for your actions.py module, but from the traceback I assume line 16 is at the top level of your SelectUserForm class body. If so, this statement will be executed each time the module is imported, which is a BadThing for many reasons. You just discovered one of these reasons, congrats. Another one is that this will be executed once per process, and only once per process, which leads to to strange bugs as soon as you're in production (stale state, incoherent state from one process to another, etc).
The cure here is to move this statement within a method of your form.

Related

ProgrammingError: relation 'blah blah' does not exist, trying to run the specific migration and get error

I am getting an error:
$ python manage.py migrate swsite 0023_hitcounter.py
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
utility.execute()
File "/usr/lib64/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 398, in execute
self.check()
File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 426, in check
include_deployment_checks=include_deployment_checks,
File "/usr/lib64/python2.7/site-packages/django/core/checks/registry.py", line 75, in run_checks
new_errors = check(app_configs=app_configs)
File "/usr/lib64/python2.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "/usr/lib64/python2.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver
for pattern in resolver.url_patterns:
File "/usr/lib64/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/lib64/python2.7/site-packages/django/core/urlresolvers.py", line 417, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/lib64/python2.7/site-packages/django/utils/functional.py", line 33, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/lib64/python2.7/site-packages/django/core/urlresolvers.py", line 410, in urlconf_module
return import_module(self.urlconf_name)
File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/var/www/swlab-website/mysite/urls.py", line 25, in <module>
url(r'^swsite/', include('swsite.urls')),
File "/usr/lib64/python2.7/site-packages/django/conf/urls/__init__.py", line 52, in include
urlconf_module = import_module(urlconf_module)
File "/usr/lib64/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/var/www/swlab-website/swsite/urls.py", line 2, in <module>
from . import views
File "/var/www/swlab-website/swsite/views.py", line 27, in <module>
class IndexView(generic.ListView):
File "/var/www/swlab-website/swsite/views.py", line 31, in IndexView
newhit = HitCounter.objects.create()
File "/usr/lib64/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/django/db/models/query.py", line 401, in create
obj.save(force_insert=True, using=self.db)
File "/usr/lib64/python2.7/site-packages/django/db/models/base.py", line 708, in save
force_update=force_update, update_fields=update_fields)
File "/usr/lib64/python2.7/site-packages/django/db/models/base.py", line 736, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/usr/lib64/python2.7/site-packages/django/db/models/base.py", line 820, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/usr/lib64/python2.7/site-packages/django/db/models/base.py", line 859, in _do_insert
using=using, raw=raw)
File "/usr/lib64/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/django/db/models/query.py", line 1039, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/lib64/python2.7/site-packages/django/db/models/sql/compiler.py", line 1060, in execute_sql
cursor.execute(sql, params)
File "/usr/lib64/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/lib64/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/usr/lib64/python2.7/site-packages/django/db/utils.py", line 95, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/lib64/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "swsite_hitcounter" does not exist
LINE 1: INSERT INTO "swsite_hitcounter" ("date", "template_location"...
This is confusing to me as it is specifically trying to build the swsite_hitcounter table as in the following migration I am trying to fun:
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2017-07-05 15:56
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('swsite', '0022_auto_20170307_1343'),
]
operations = [
migrations.CreateModel(
name='HitCounter',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateTimeField(auto_now=True)),
('template_location', models.TextField()),
],
),
]
Is something maybe out of sink? This is me trying to run this migration on my production box, it ran fine (of course) on my development box. Might of been cause I ran a specific migration? :
python manage.py migrate swsite 0023_hitcounter.py
Though running:
python manage.py showmigrations
Gives me same error? I am guessing my migrations are out of sync but not being able to show migrations, I don't know how to show the ones that didn't get into this update (on production from gilab)
The traceback is showing you that the error is occuring in IndexView. You are trying to create objects in the database when the view loads.
class IndexView(TemplateView):
newhit = HitCounter.objects.create() # remove this line
...
Accessing the database when the views load like this is a bad idea, so you should probably remove the line. In production, it gives you the error because it is trying to create the object in the database before you have applied the migration that creates the table.

Unknown column cms_page.path upgrading django-cms to 3.1

I'm currently trying to upgrade an existing django-cms site from 3.0.16 to 3.1.4 with django 1.7.11
I followed the instructions given in http://docs.django-cms.org/en/latest/upgrade/3.1.html but when I get to python manage.py migrate
I get the following error:
django.db.utils.OperationalError: (1054, "Unknown column 'cms_page.path' in 'field list'")
Any hints on how I can debug this? Thanks!
Update:
Here is the full traceback:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/path/to/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/path/to/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/path/to/venv/local/lib/python2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/path/to/venv/local/lib/python2.7/site-packages/django/apps/registry.py", line 115, in populate
app_config.ready()
File "/path/to/venv/local/lib/python2.7/site-packages/debug_toolbar/apps.py", line 15, in ready
dt_settings.patch_all()
File "/path/to/venv/local/lib/python2.7/site-packages/debug_toolbar/settings.py", line 228, in patch_all
patch_root_urlconf()
File "/path/to/venv/local/lib/python2.7/site-packages/debug_toolbar/settings.py", line 216, in patch_root_urlconf
reverse('djdt:render_panel')
File "/path/to/venv/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 522, in reverse
app_list = resolver.app_dict[ns]
File "/path/to/venv/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 329, in app_dict
self._populate()
File "/path/to/venv/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 269, in _populate
for pattern in reversed(self.url_patterns):
File "/path/to/venv/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 372, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/path/to/venv/local/lib/python2.7/site-packages/django/core/urlresolvers.py", line 366, in urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/path/to/project/project/urls.py", line 14, in <module>
url(r'^admin/', include(admin.site.urls)),
File "/path/to/venv/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 262, in urls
return self.get_urls(), self.app_name, self.name
File "/path/to/venv/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 246, in get_urls
url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls))
File "/path/to/venv/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 598, in urls
return self.get_urls()
File "/path/to/venv/local/lib/python2.7/site-packages/cms/admin/placeholderadmin.py", line 138, in get_urls
from cms.urls import SLUG_REGEXP
File "/path/to/venv/local/lib/python2.7/site-packages/cms/urls.py", line 20, in <module>
urlpatterns = get_app_patterns()
File "/path/to/venv/local/lib/python2.7/site-packages/cms/appresolver.py", line 215, in get_app_patterns
for title in title_qs.exclude(page__application_urls=None).exclude(page__application_urls='').order_by('-page__path').select_related():
File "/path/to/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 141, in __iter__
self._fetch_all()
File "/path/to/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 966, in _fetch_all
self._result_cache = list(self.iterator())
File "/path/to/venv/local/lib/python2.7/site-packages/django/db/models/query.py", line 265, in iterator
for row in compiler.results_iter():
File "/path/to/venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 701, in results_iter
for rows in self.execute_sql(MULTI):
File "/path/to/venv/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 787, in execute_sql
cursor.execute(sql, params)
File "/path/to/venv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 81, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/path/to/venv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/path/to/venv/local/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/path/to/venv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 65, in execute
return self.cursor.execute(sql, params)
File "/path/to/venv/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 129, in execute
return self.cursor.execute(query, args)
File "/path/to/venv/local/lib/python2.7/site-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/path/to/venv/local/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
django.db.utils.OperationalError: (1054, "Unknown column 'cms_page.path' in 'field list'")
I'm not sure why this worked, but the traceback indicated that there was some problem in my projects urls.py
I commented out all of the url rules in this file, migrated the cms app, then uncommented my url rules. That seems to solve the migration problem.

Issues migrating project from django 1.5 to django 1.8

I'm building a project with Django 1.5.1 and decided to migrate the project to Django 1.8.4, then I found out I cant initialize the project, I was able to detect and fix some errors, but It's been a couple of days now and I can't figure out the rest.
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 312, in execute
django.setup()
File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 86, in create
module = import_module(entry)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/jaime/djcode/spid/preventivos/__init__.py", line 38, in <module>
from preventivos.views import *
File "/home/jaime/djcode/spid/preventivos/views.py", line 4, in <module>
from preventivos.forms import *
File "/home/jaime/djcode/spid/preventivos/forms.py", line 122, in <module>
class UnidadesForm(forms.ModelForm):
File "/home/jaime/djcode/spid/preventivos/forms.py", line 124, in UnidadesForm
ciudad = forms.ModelChoiceField(widget=forms.Select(attrs={'size':'13', 'onchange':'this.form.action=this.form.submit()'}), choices= RefCiudades.objects.filter(provincia__contains = RefProvincia.objects.filter(descripcion__contains = "CHUBUT").values("id")) )
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 679, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 697, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1309, in add_q
clause, require_inner = self._add_q(where_part, self.used_aliases)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1337, in _add_q
allow_joins=allow_joins, split_subq=split_subq,
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1149, in build_filter
lookups, parts, reffed_expression = self.solve_lookup_type(arg)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1035, in solve_lookup_type
_, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1372, in names_to_path
if field.is_relation and not field.related_model:
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 60, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 110, in related_model
apps.check_models_ready()
File "/usr/local/lib/python2.7/dist-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.
The traceback is telling you that the problem is this line in your UnidadesForm model form.
ciudad = forms.ModelChoiceField(widget=forms.Select(attrs={'size':'13', 'onchange':'this.form.action=this.form.submit()'}), choices= RefCiudades.objects.filter(provincia__contains = RefProvincia.objects.filter(descripcion__contains = "CHUBUT").values("id")) )
As it's a model choice field, it would be better to use the queryset argument rather than choices.
ciudad = forms.ModelChoiceField(widget=forms.Select(attrs={'size':'13', 'onchange':'this.form.action=this.form.submit()'}), queryset= RefCiudades.objects.filter(provincia__contains = RefProvincia.objects.filter(descripcion__contains = "CHUBUT").values("id")) )
I think that might stop the error, but I'm not sure that your queryset makes sense. The filter argument provincia__contains should take a string, but RefProvincia(...).values("id") will return a values queryset.

dajaxice DajaxiceFinder fails collectstatic

I installed dajaxice into a django project. When i run the web using manage.py runserver, all went well. Now I try to deploy it with apache/wsgi. When I run manage.py collectstatic, error occur:
ImportError: cannot import name Bag
where Bag is one model within my app.
I tried
manage.py shell
then import Bag, i works well.
And I tried comment out DajaxiceFinder from settings.py, collectstatic finished normally.
Could any one help me out?
Thanks
The full stack of ImportError:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 222, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 255, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 385, in handle
return self.handle_noargs(**options)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 164, in handle_noargs
collected = self.collect()
File "/usr/local/lib/python2.7/dist-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect
handler(path, prefixed_path, storage)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 285, in copy_file
if not self.delete_file(path, prefixed_path, source_storage):
File "/usr/local/lib/python2.7/dist-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 224, in delete_file
source_last_modified = source_storage.modified_time(path)
File "/usr/local/lib/python2.7/dist-packages/django/core/files/storage.py", line 277, in modified_time
return datetime.fromtimestamp(os.path.getmtime(self.path(name)))
File "/usr/local/lib/python2.7/dist-packages/dajaxice/finders.py", line 55, in path
path = self.get_or_create_file(name)
File "/usr/local/lib/python2.7/dist-packages/dajaxice/finders.py", line 21, in get_or_create_file
data = getattr(self, self.files[path])()
File "/usr/local/lib/python2.7/dist-packages/dajaxice/finders.py", line 68, in dajaxice_core_js
dajaxice_autodiscover()
File "/usr/local/lib/python2.7/dist-packages/dajaxice/core/Dajaxice.py", line 135, in dajaxice_autodiscover
import_module("%s.ajax" % app)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/emini/project/emini/trunk/emini/repairment/ajax.py", line 4, in <module>
from emini.repairment.models import Bag
File "/home/emini/project/emini/trunk/emini/repairment/models.py", line 9, in <module>
class Bag(models.Model):
File "/home/emini/project/emini/trunk/emini/repairment/models.py", line 90, in Bag
shop_id = models.IntegerField(default=0, db_index=True, choices=DataConfig.get_valid_conf_as_choices_by_group(DataConfig.GROUP_NAME_SHOP), verbose_name="店铺")
File "/home/emini/project/emini/trunk/emini/sysconfig/models.py", line 62, in get_valid_conf_as_choices_by_group
data_configs = cls.objects.filter(group_name=group_name, enabled=True).order_by('-id')
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 155, in filter
return self.get_query_set().filter(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 669, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 687, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1271, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1139, in add_filter
process_extras=process_extras)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1325, in setup_joins
field, model, direct, m2m = opts.get_field_by_name(name)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py", line 351, in get_field_by_name
cache = self.init_name_map()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py", line 380, in init_name_map
for f, model in self.get_all_related_m2m_objects_with_model():
File "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py", line 469, in get_all_related_m2m_objects_with_model
cache = self._fill_related_many_to_many_cache()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py", line 483, in _fill_related_many_to_many_cache
for klass in get_models(only_installed=False):
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 197, in get_models
self._populate()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 75, in _populate
self.load_app(app_name)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 96, in load_app
models = import_module('.models', app_name)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/emini/project/emini/trunk/emini/express/models.py", line 6, in <module>
from emini.repairment.models import Bag
ImportError: cannot import name Bag
Enviroment:
Django==1.5.4
django-dajaxice==0.5.5
I try to delete the import Bag from express/models.py, then collectstatic successed.
Structure of my apps:
emini
express
models.py
repairment
models.py
in emini.express.models:
from emini.repairment.models import Bag
class Package(models.Model):
foo = models.CharField(max_length=20)
class BagPackageLink(models.Model):
bag = models.ForeignKey(Bag)
package = models.ForeignKey(Package)
class Meta:
unique_together = (("bag", "package"),)
in emini.repairment.models
class Bag(models.Model):
foo = models.CharField(max_length=20)
Am i messing up with 'overlap import'?
But why the runserver and shell can import Bag model?

Django syncdb error

I have django.contrib.auth in my installed apps and everything was was working about 10 minutes ago. I deleted the existed database because I had problems with south migrations. When I try to rebuild it I get an error.
Error: django.db.utils.DatabaseError: no such table: auth_user
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 219, in execute
self.validate()
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/usr/lib/python2.7/site-packages/django/core/management/validation.py", line 35, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/usr/lib/python2.7/site-packages/django/db/models/loading.py", line 146, in get_app_errors
self._populate()
File "/usr/lib/python2.7/site-packages/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/usr/lib/python2.7/site-packages/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/usr/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/bruk/workspace/hungryDroid/src/hungryDroid/Ingredient/models.py", line 22, in <module>
class Ingredient(models.Model):
File "/home/bruk/workspace/hungryDroid/src/hungryDroid/Ingredient/models.py", line 26, in Ingredient
FKowner = models.ForeignKey(User, default=User.objects.get(pk=1).id)
File "/usr/lib/python2.7/site-packages/django/db/models/manager.py", line 132, in get
return self.get_query_set().get(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 342, in get
num = len(clone)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 80, in __len__
self._result_cache = list(self.iterator())
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 271, in iterator
for row in compiler.results_iter():
File "/usr/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 677, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 732, in execute_sql
cursor.execute(sql, params)
File "/usr/lib/python2.7/site-packages/django/db/backends/util.py", line 15, in execute
return self.cursor.execute(sql, params)
File "/usr/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 200, in execute
return Database.Cursor.execute(self, query, params)
**django.db.utils.DatabaseError: no such table: auth_user**
The problem is that you are running a query against the User model
File "/home/bruk/workspace/hungryDroid/src/hungryDroid/Ingredient/models.py", line 26, in Ingredient
FKowner = models.ForeignKey(User, default=User.objects.get(pk=1).id)
In the syncdb process (during field declaration actually, so any time your module is imported, like during this validation process).
This will make sure that the auth_user query is executed before the auth_user table is created.
A safer way to get the functionality with the default user is to do
def get_default_user():
return User.objects.get(pk=1)
And then in your field declaration, do
FKowner = models.ForeignKey(User, default=get_default_user)
As per the model field reference default can be a callable. Note that you would have the same problem if you used get_default_user() in there - then it executes immediately, not on-demand.

Categories

Resources