Django AttributeError: 'str' object has no attribute '_default_manager' - django

The following error seems to occur randomly on my live server (i.e. through apache mod_wsgi) but never in development (i.e. localhost python manage.py runserver).
Note this happens infrequently and is not something that can be reproduced easily or each time a specific url is accessed.
I have seen various answers posted both here on SO and on google but there does not seem to be any definitive reason as to why this error occurs. Maybe this is because the error is fairly generic but the most common answer seems to be due to circular import errors. Another answer I've seen is that model FK field references have not been the correct case (e.g. applabel.model instead of applabel.Model) but all my model FK fields are correct.
The cause of the error seems to point to one of my admin.py files. This file did originally import custom form classes from a forms.py file. Both the admin.py file and forms.py file imported the same models from a models.py file. Therefore I moved the form classes to the admin.py file in case there was a circular reference occurring here but I still occasionally get these errors.
Could anyone shed any light as to why this error occurs and why so randomly? I always ensure the relevant services are restarted after a code update.
Traceback is:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 101, in get_response
request.path_info)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 250, in resolve
for pattern in self.url_patterns:
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 279, in _get_url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 274, in _get_urlconf_module
self._urlconf_module = import_module(self.urlconf_name)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/myproject/urls.py", line 6, in <module>
admin.autodiscover()
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
import_module('%s.admin' % app)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/myproject/myapps/app/admin.py", line 61, in <module>
class CardAdminForm(forms.ModelForm):
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 205, in __new__
opts.exclude, opts.widgets, formfield_callback)
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py", line 159, in fields_for_model
formfield = f.formfield(**kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 913, in formfield
'queryset': self.rel.to._default_manager.using(db).complex_filter(self.rel.limit_choices_to),
AttributeError: 'str' object has no attribute '_default_manager'
Packages and versions
Warning: cannot find svn location for pymssql==2.0.0b1-dev-20111019
Warning: cannot find svn location for distribute==0.6.24dev-r0
Django==1.3.3
GnuPGInterface==0.3.2
Landscape-Client==12.05
PAM==0.4.2
PIL==1.1.7
Twisted-Core==11.1.0
apt-xapian-index==0.44
argparse==1.2.1
chardet==2.0.1
command-not-found==0.2.44
## FIXME: could not find svn URL in dependency_links for this package: distribute==0.6.24dev-r0
django-debug-toolbar==0.9.4
django-rosetta==0.6.8
httplib2==0.7.2
iotop==0.4.4
keyring==0.7.1
language-selector==0.1
launchpadlib==1.9.12
lazr.restfulclient==0.12.0
lazr.uri==1.0.3
mercurial==2.0.2
oauth==1.0.1
psycopg2==2.4.5
pyOpenSSL==0.12
pycrypto==2.4.1
## FIXME: could not find svn URL in dependency_links for this package:pymssql==2.0.0b1-dev-20111019
pyserial==2.5
python-apt==0.8.3ubuntu7
python-debian==0.1.21ubuntu1
reportlab==2.5
simplejson==2.3.2
ufw==0.31.1-1
wadllib==1.3.0
wsgiref==0.1.2
xlwt==0.7.4
zope.interface==3.6.1
Database: Postgresql 9.1.5
CardAdmin and CardAdminForm:
class CardAdmin(admin.ModelAdmin):
form = CardAdminForm
raw_id_fields = ('cust', 'acc', 'vehicle', 'driver')
list_display = ('id', 'pan', 'name', 'expiry', 'created', 'modified')
list_filter = ('status', )
search_fields = ['id', 'pan']
admin.site.register(Card, CardAdmin)
class CardAdminForm(forms.ModelForm):
"""
A Form for Cards (Admin console)
"""
def __init__(self, *args, **kwargs):
super(CardAdminForm, self).__init__(*args, **kwargs)
self.fields['cust'].required = True
self.fields['acc'].required = True
self.fields['name'].required = True
self.fields['code'].widget = forms.PasswordInput()
self.fields['code'].max_length = 6
class Meta:
model = Card
fields = (
'cust',
'name',
'acc',
'no',
'code',
'type',
'status',
'address_1',
'address_2',
'zip',
'city',
'country',
'phone_no',
'expiry',
'vehicle',
'driver'
)
def save(self, commit=True):
# Save some additional data.
form_instance = super(CardAdminForm, self).save(commit=False)
cleaned_data = self.cleaned_data
form_instance.pan = '%s%s%s'\
% (
cleaned_data['acc'].iso.number,
cleaned_data['acc'].number,
cleaned_data['no']
)
if commit:
form_instance.save()
return form_instance

Quick note for people still finding this old issue: This case can also be caused by a ForeignKey/ManyToMany/OnetoOne that uses a string as reference that is invalid (eg: not correctly pointing to a model).
I was updating/refactoring a project and ran into this. Turned out it was just a typo.
Kinda weird django doesn't notify clearly it cannot resolve the string, could be because other apps confused it.

_default_manager is the attribute on a model that holds the (surprise, surprise) default manager for that model. Django uses this all over the place, especially in the admin, to return querysets for ModelAdmins.
So the error is telling you that somewhere, you've passed a string where a model class or instance was expected. It tries to call _default_manager on the string, and fails, obviously.
However, since the error comes in Django code, in particular when referencing self.rel.to on an instance, I can only assume that you or some third-party whose code you are utilizing has made some pretty integral and monumental changes to something. This is not how the stock code should behave.

The solution to my problem seems to have been resolved by looking at the following links:
Getting the “str” has no property “_default_manager” on a Django app just on startup
and:
Django Ticket 10405 Comment 11
Technically Chris Pratt's answer is absolutely correct and a very good explanation but nowhere in my code could I find an instance that would be causing this error.
The error occurred randomly but the source of this error was mostly being triggered by a server monitoring system requesting the base url (/) for my website (i.e. full HTTP page request). I can only assume the monitoring system uses something like the wget command to make this check so I used this command to test the base url for my website.
Occasionally this command would return a 200 OK response but on most occasions this would return a 500 Internal Server Error response, even though I could access the website fine from a browser. It seems also that a 500 Internal Server Error response would always occur immediately after restarting Apache.
I'm still a bit puzzled as to the exact cause and randomness of this error, discussions I've seen point to a possible bug in the Django framework but this doesn't happen in other websites using the same set up I have implemented here. Reading through the comments in the 2nd link above, it seems to be that a similar code layout has been used as that in my question above (only happens in production using Apache/mod_wsgi, ModelForms used for admin section, using quoted FK references in models).
As mentioned in the above links the solution is to insert:
from django.db.models.loading import cache as model_cache
if not model_cache.loaded:
model_cache.get_models()
before:
admin.autodiscover()
in the base urls.py file.
Hope this helps others that may stumble upon this weird issue. I've had no errors since making the above code addition.

I ran in to this error message because I did not correctly specify the model in the meta class of a factory
class FooBarFactory(factory.django.DjangoModelFactory):
class Meta:
model = 'foobar' # <-- must be 'myapp.foobar'

File "/home/lb/.local/lib/python3.6/site-packages/django/db/models/fields/related.py", line 1673, in formfield
'queryset': self.remote_field.model._default_manager.using(using),
AttributeError: 'str' object has no attribute '_default_manager'
In my module there was an incorrect code with a String:
Error:
tags = models.ManyToManyField('Tag', blank=True)
Correct:
tags = models.ManyToManyField(Tag, blank=True)
I have not created the class Tag

I got a similar error when I did:
from people.models import Quote
quote = models.ManyToManyField(
"Quote",
blank=True,
verbose_name=_("Quotes"),
help_text=_("Select quotes"),
default=None,
related_name="people_quotes"
)
But when I removed the quotes around the referenced model "Quote", the error went away.
from people.models import Quote
quote = models.ManyToManyField(
Quote,
blank=True,
verbose_name=_("Quotes"),
help_text=_("Select quotes"),
default=None,
related_name="people_quotes"
)

Related

Is there a workaround for Django's `ModelDoesNotExist` error in a situation like this?

So I get a ModelDoesNotExist error when I run manage.py runserver because in a file in my directory, I make a query to a table which has not been populated yet.
def __init__(self):
self.spotify_object = SocialToken.objects.get(account__provider="spotify")
The above is a class instantiated to perform some sort of authentication and the SocialToken table gets populated only after I login. Now, I was wondering if there was a way to escape the error by triggering this part of the code only after I login? I only use the class in an endpoint, and during that period, the table would have been populated but the fact that it is not populated before running the server is causing a DoesNotExist error. Is there a solution to this?
Traceback
File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\Sparison\views.py", line 4, in <module>
from .authentication import SparisonCacheHandler
File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\Sparison\authentication.py", line 43, in
<module>
cache_handler = SparisonCacheHandler() ,
File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\Sparison\authentication.py", line 25,
in __init__
self.spotify_object = SocialToken.objects.get(account__provider="spotify")
File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\venv\lib\site-
packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Kwaku Biney\Desktop\sparison-1\project\venv\lib\site-
packages\django\db\models\query.py", line 429, in get
raise self.model.DoesNotExist(
allauth.socialaccount.models.DoesNotExist: SocialToken matching query does not exist.
In my views.py, I import the class which has the query and the error comes up.
There are two ways to avoid the DoesNotExist Error.
A) Use .filter() instead of .get()
Filtering leads to an empty queryset when the search comes up empty.
def __init__(self):
self.spotify_object = SocialToken.objects.filter(account__provider="spotify")
B) Use get_object_or_404() instead of .get()
This is a built-in function by django:
Calls get() on a given model manager, but it raises Http404 instead of the model’s DoesNotExist exception.
Django Documentation
def __init__(self):
self.spotify_object = SocialToken.objects.get_object_or_404(account__provider="spotify")
Hope I could help you. Have a nice day.

Getting Django error (models.E028). for 6 different models after moving from the Desktop folder to the var/www folder on Ubuntu Server

I recently moved my django project files from a laptop to a web server. After moving the files I ran the django dev server to test things and everything was fine. After moving the project files once to the var/www folder I attempted again to see if everything still worked before finishing the process of launching the project.
I am now getting a django error (models.E028) and don't know how to solve it.
I have looked through the models.py folder where these models are and everything appears the same as before. Also the second model that the error message lists is not in my models.py file at all, for example in teh first line it lists "auth.Group". I am unable to locate this model at all.
Also I have yet to destroy the copies of the project on the laptop so I tried to launch it there and it works with no errors.
Unfortunately the Django docs don't give further explanation of the error, or where to start looking for the cause.
I'm sure the error has to do with moving the files from one location to another on the server, but I can't think of why it would affect the models. They have to be in the folder they are located in now, so moving them back isn't a solution. I moved the folder with the following command:
sudo mv file/I/needed/to/move /var/www/
Here is the full error I am getting when I attempt to launch the dev server from django using the runserver command:
Watching for file changes with StatReloader
Performing system checks...
Exception in thread django-main-thread:
Traceback (most recent call last):
File "/usr/lib/python3.6/threading.py", line 916, in
_bootstrap_inner
self.run()
File "/usr/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/home/cpcadmin/.local/lib/python3.6/site-
packages/django/utils/autoreload.py", line 54, in wrapper
fn(*args, **kwargs)
File "/home/cpcadmin/.local/lib/python3.6/site-
packages/django/core/management/commands/runserver.py", line 117, in
inner_run
self.check(display_num_errors=True)
File "/home/cpcadmin/.local/lib/python3.6/site-
packages/django/core/management/base.py", line 436, in check
raise SystemCheckError(msg)
django.core.management.base.SystemCheckError: SystemCheckError:
System check identified some issues:
ERRORS:
auth_group: (models.E028) db_table 'auth_group' is used by multiple
models: Final.AuthGroup, auth.Group.
auth_permission: (models.E028) db_table 'auth_permission' is used by
multiple models: Final.AuthPermission, auth.Permission.
auth_user: (models.E028) db_table 'auth_user' is used by multiple
models: Final.AuthUser, auth.User.
django_admin_log: (models.E028) db_table 'django_admin_log' is used
by multiple models: Final.DjangoAdminLog, admin.LogEntry.
django_content_type: (models.E028) db_table 'django_content_type' is
used by multiple models: Final.DjangoContentType,
contenttypes.ContentType.
django_session: (models.E028) db_table 'django_session' is used by
multiple models: Final.DjangoSession, sessions.Session.
System check identified 6 issues (0 silenced).
I don't have a lot of experience with django beyond a couple small sites and have never encountered this particular error. Any help is greatly appreciated as I'm at a loss. Thanks in advance!
Change manage variable to False for DjangoContentType class in your application's model.py
For Example
class DjangoContentType(models.Model)
app_label = models.CharField(max_length=100)
model = models.CharField(max_length=100)
class Meta:
**managed = False**
db_table = 'django_content_type'
unique_together = (('app_label', 'model'),)

Django syncdb exception after updating to 1.4

So I was developing an app in Django and needed a function from the 1.4 version so I decided to update.
But then a weird error appeared when I wanted to do syncdb
I am using the new manage.py and as You can see it makes some of the tables but then fails :
./manage.py syncdb
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
Traceback (most recent call last):
File "./manage.py", line 9, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/core/management/base.py", line 371, in handle
return self.handle_noargs(**options)
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/core/management/commands/syncdb.py", line 91, in handle_noargs
sql, references = connection.creation.sql_create_model(model, self.style, seen_models)
File "/usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/db/backends/creation.py", line 44, in sql_create_model
col_type = f.db_type(connection=self.connection)
TypeError: db_type() got an unexpected keyword argument 'connection'
I had the same issue, the definition for my custom field was missing the connection parameter.
from django.db import models
class BigIntegerField(models.IntegerField):
def db_type(self, connection):
return "bigint"
Although already old, answered and accepted question but I am adding my understanding I have added it because I am not using customized type and it is a Django Evolution error (but not syncdb)evolve --hint --execute. I think it may be helpful for someone in future. .
I am average in Python and new to Django. I also encounter same issue when I added some new features to my existing project. To add new feature I had to add some new fields of models.CharField() type,as follows.
included_domains = models.CharField(
"set of comma(,) seprated list of domains in target emails",
default="",
max_length=it_len.EMAIL_LEN*5)
excluded_domains = models.CharField(
"set of comma(,) seprated list of domains NOT in target emails",
default="",
max_length=it_len.EMAIL_LEN*5)
The Django version I am using is 1.3.1:
$ python -c "import django; print django.get_version()"
1.3.1 <--------# version
$python manage.py syncdb
Project signature has changed - an evolution is required
Django Evolution: Django Evolution is an extension to Django that allows you to track changes in your models over time, and to update the database to reflect those changes.
$ python manage.py evolve --hint
#----- Evolution for messagingframework
from django_evolution.mutations import AddField
from django.db import models
MUTATIONS = [
AddField('MessageConfiguration', 'excluded_domains', models.CharField, initial=u'', max_length=300),
AddField('MessageConfiguration', 'included_domains', models.CharField, initial=u'', max_length=300)
]
#----------------------
Trial evolution successful.
Run './manage.py evolve --hint --execute' to apply evolution.
The trial was susses and when I tried to apply changes in DB
$ python manage.py evolve --hint --execute
Traceback (most recent call last):
File "manage.py", line 25, in <module>
execute_manager(settings)
File "/var/www/sites/www.taxspanner.com/django/core/management/__init__.py", line 362, in execute_manager
utility.execute()
File "/var/www/sites/www.taxspanner.com/django/core/management/__init__.py", line 303, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/var/www/sites/www.taxspanner.com/django/core/management/base.py", line 195, in run_from_argv
self.execute(*args, **options.__dict__)
File "/var/www/sites/www.taxspanner.com/django/core/management/base.py", line 222, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django_evolution-0.6.9.dev_r225-py2.7.egg/django_evolution/management/commands/evolve.py", line 60, in handle
self.evolve(*app_labels, **options)
File "/usr/local/lib/python2.7/dist-packages/django_evolution-0.6.9.dev_r225-py2.7.egg/django_evolution/management/commands/evolve.py", line 140, in evolve
database))
File "/usr/local/lib/python2.7/dist-packages/django_evolution-0.6.9.dev_r225-py2.7.egg/django_evolution/mutations.py", line 426, in mutate
return self.add_column(app_label, proj_sig, database)
File "/usr/local/lib/python2.7/dist-packages/django_evolution-0.6.9.dev_r225-py2.7.egg/django_evolution/mutations.py", line 438, in add_column
sql_statements = evolver.add_column(model, field, self.initial)
File "/usr/local/lib/python2.7/dist-packages/django_evolution-0.6.9.dev_r225-py2.7.egg/django_evolution/db/common.py", line 142, in add_column
f.db_type(connection=self.connection), # <=== here f is field class object
TypeError: db_type() got an unexpected keyword argument 'connection'
To understand this exception I check that this exception is something similar to:
>>> def f(a):
... print a
...
>>> f('b', b='a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() got an unexpected keyword argument 'b'
>>>
So the function signature has been changed.
Because I have not added any new customized or enum fields but only two similar fields that was already in model and char type field is supported by most of database (I am ussing PostgreSQL) even I was getting this error!
Then I read from #: Russell Keith-Magee-4 Reply.
What you've hit here is the end of the deprecation cycle for code that
doesn't support multiple databases.
In Django 1.2, we introduced multiple database support; in order to
support this, the prototype for get_db_preb_lookup() and
get_db_prep_value() was changed.
For backwards compatibility, we added a shim that would transparently
'fix' these methods if they hadn't already been fixed by the
developer.
In Django 1.2, the usage of these shims raised a
PendingDeprecationWarning. In Django 1.3, they raised a
DeprecationWarning.
Under Django 1.4, the shim code was been removed -- so any code that
wasn't updated will now raise errors like the one you describe.
But I am not getting any DeprecationWarning warning assuming because of newer version of Django Evolution.
But from above quote I could understand that to support multiple databases function signature is added and an extra argument connection is needed. I also check the db_type() signature in my installation of Django as follows:
/django$ grep --exclude-dir=".svn" -n 'def db_type(' * -R
contrib/localflavor/us/models.py:8: def db_type(self):
contrib/localflavor/us/models.py:24: def db_type(self):
:
:
Ialso refer of Django documentation
Field.db_type(self, connection):
Returns the database column data type for the Field, taking into account the connection
object, and the settings associated with it.
And Then I could understand that to resolve this issue I have to inherited models.filed class and overwrite def db_type() function. And because I am using PostgreSQL in which to create 300 chars type field I need to return 'char(300)'. In my models.py I added:
class CharMaxlengthN(models.Field):
def db_type(self, connection):
return 'char(%d)' % self.max_length # because I am using postgresql
If you encounter similar problem please check your underline DB's manual that which type of column you need to create and return a string.
And changed the definition of new fields (that I need to add) read comments:
included_domains = CharMaxlengthN( # <--Notice change
"set of comma(,) seprated list of domains in target emails",
default="",
max_length=it_len.EMAIL_LEN*5)
excluded_domains = CharMaxlengthN( # <-- Notice change
"set of comma(,) seprated list of domains NOT in target emails",
default="",
max_length=it_len.EMAIL_LEN*5)
Then I executed same command that was failing previously:
t$ python manage.py evolve --hint --execute
You have requested a database evolution. This will alter tables
and data currently in the None database, and may result in
IRREVERSABLE DATA LOSS. Evolutions should be *thoroughly* reviewed
prior to execution.
Are you sure you want to execute the evolutions?
Type 'yes' to continue, or 'no' to cancel: yes
Evolution successful.
I also check my DB and tested my new added features It is now working perfectly, and no DB problem.
If you wants to create ENUM field read Specifying a mySQL ENUM in a Django model.
Edit: I realized instead of sub classing models.Field I should have inherit more specific subclass that is models.CharField.
Similarly I need to create Decimal DB fields so I added following class in model:
class DecimalField(models.DecimalField):
def db_type(self, connection):
d = {
'max_digits': self.max_digits,
'decimal_places': self.decimal_places,
}
return 'numeric(%(max_digits)s, %(decimal_places)s)' % d

Django database query: How to get object by id?

Django automatically creates an id field as primary key.
Now I need to get the object by this id.
object = Class.objects.filter()
How to write this filter?
If you want to get an object, using get() is more straightforward:
obj = Class.objects.get(pk=this_object_id)
I got here for the same problem, but for a different reason:
Class.objects.get(id=1)
This code was raising an ImportError exception. What was confusing me was that the code below executed fine and returned a result set as expected:
Class.objects.all()
Tail of the traceback for the get() method:
File "django/db/models/loading.py", line 197, in get_models
self._populate()
File "django/db/models/loading.py", line 72, in _populate
self.load_app(app_name, True)
File "django/db/models/loading.py", line 94, in load_app
app_module = import_module(app_name)
File "django/utils/importlib.py", line 35, in import_module
__import__(name)
ImportError: No module named myapp
Reading the code inside Django's loading.py, I came to the conclusion that my settings.py had a bad path to my app which contains my Class model definition. All I had to do was correct the path to the app and the get() method executed fine.
Here is my settings.py with the corrected path:
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
# ...
'mywebproject.myapp',
)
All the confusion was caused because I am using Django's ORM as a standalone, so the namespace had to reflect that.
You can also use get_object_or_404 django shortcut. It raises a 404 error if object is not found.
You can use:
objects_all=Class.objects.filter(filter_condition="")
This will return a query set even if it gets one object.
If you need exactly one object use:
obj=Class.objects.get(conditon="")
You can also do:
obj = ClassModel.get_by_id(object_id)
This works, but there may I'm not sure if it's supported in Django 2.
In case you don't have some id, e.g., mysite.com/something/9182301, you can use get_object_or_404 importing by from django.shortcuts import get_object_or_404.
Use example:
def myFunc(request, my_pk):
my_var = get_object_or_404(CLASS_NAME, pk=my_pk)

How do I get syncdb db_table and app_label to play nicely together

I've got a model that looks something like this:
class HeiselFoo(models.Model):
title = models.CharField(max_length=250)
class Meta:
""" Meta """
app_label = "Foos"
db_table = u"medley_heiselfoo_heiselfoo"
And whenever I run my test suite, I get an error because Django isn't creating the tables for that model.
It appears to be an interaction between app_label and db_table -- as the test suite runs normally if db_table is set, but app_label isn't.
Here's a link to the full source code: http://github.com/cmheisel/heiselfoo
Here's the traceback from the test suite:
E
======================================================================
ERROR: test_truth (heiselfoo.tests.HeiselFooTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/chris/Code/heiselfoo/ve/lib/python2.6/site-packages/heiselfoo/tests.py", line 10, in test_truth
f.save()
File "/Users/chris/Code/heiselfoo/ve/lib/python2.6/site-packages/django/db/models/base.py", line 434, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/Users/chris/Code/heiselfoo/ve/lib/python2.6/site-packages/django/db/models/base.py", line 527, in save_base
result = manager._insert(values, return_id=update_pk, using=using)
File "/Users/chris/Code/heiselfoo/ve/lib/python2.6/site-packages/django/db/models/manager.py", line 195, in _insert
return insert_query(self.model, values, **kwargs)
File "/Users/chris/Code/heiselfoo/ve/lib/python2.6/site-packages/django/db/models/query.py", line 1479, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/chris/Code/heiselfoo/ve/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 783, in execute_sql
cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/Users/chris/Code/heiselfoo/ve/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 727, in execute_sql
cursor.execute(sql, params)
File "/Users/chris/Code/heiselfoo/ve/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py", line 200, in execute
return Database.Cursor.execute(self, query, params)
DatabaseError: no such table: medley_heiselfoo_heiselfoo
----------------------------------------------------------------------
Ran 1 test in 0.004s
FAILED (errors=1)
Creating test database 'default'...
No fixtures found.
medley_heiselfoo_heiselfoo
Destroying test database 'default'...
Ok, I'm a moron. You need to have an app in INSTALLED_APPS that matches your app_label or your tables won't get created.
You need to have an app in INSTALLED_APPS that matches your app_label or your tables won't get created.
In my case it doesn't work - when I change app name in INSTALLED_APPS on app_label wchich matches models Meta setting, but is different than app folder name, manage.py syncdb raise: "Error: No module named ...". I still have no idea how to sync models with database in case of using app_label and db_table in model Meta.
Caveat: this is not a direct answer to your question.
From looking at your code in github I find that you have defined the model inside models.py. And yet you have defined app_label inside your model's Meta. Is there a reason for doing this?
Django's documentation says that app_label is meant to be used
If a model exists outside of the standard models.py (for instance, if the app’s models are in submodules of myapp.models), the model must define which app it is part of:
Given that, I don't see any reason to define an app_label in your case. Hence my question. Perhaps you are better off without defining the app_label after all.