Django Official Tutorial Part 1 index out of bound error - django

I started learning Django recently and am having a strange problem with the tutorial. Everything was going fine until I started playing with the interactive shell and then I got an error whenever I tried to call all the objects in one of the tables.
I am using Django 1.1, Python 2.5 on MacOs X.
For those unfamiliar with the tutorial you are making a website to manage Polls. You have the following code in the model:
from django.db import models
import datetime
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_today(self):
return self.pub_date.date() == datetime.date.today()
was_published_today.short_description = 'Published today?'
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice
After creating the model you add a poll item and then add some choices to it.
Everything was fine until I tried to see all the objects in the choices table or tried to see all the choices in a particular poll. Then I got an error. Heres an example series of commands in the interactive shell. Please note that the count of the choices is correct (I have experimented a bit after running into the error so the count is a bit high.)
>>> from mysite.polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: What's up>, <Poll: Yups>]
>>> Choice.objects.count()
10
>>> Choice.objects.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Python/2.5/site-packages/django/db/models/query.py", line 68, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/Library/Python/2.5/site-packages/django/db/models/query.py", line 83, in __len__
self._result_cache.extend(list(self._iter))
File "/Library/Python/2.5/site-packages/django/db/models/query.py", line 238, in iterator
for row in self.query.results_iter():
File "/Library/Python/2.5/site-packages/django/db/models/sql/query.py", line 287, in results_iter
for rows in self.execute_sql(MULTI):
File "/Library/Python/2.5/site-packages/django/db/models/sql/query.py", line 2369, in execute_sql
cursor.execute(sql, params)
File "/Library/Python/2.5/site-packages/django/db/backends/util.py", line 19, in execute
return self.cursor.execute(sql, params)
File "/Library/Python/2.5/site-packages/django/db/backends/sqlite3/base.py", line 193, in execute
return Database.Cursor.execute(self, query, params)
File "/Library/Python/2.5/site-packages/django/db/backends/util.py", line 82, in typecast_timestamp
seconds = times[2]
IndexError: list index out of range
The Django tutorial(part 1) can be found here
Thanks!

The problem seemed to be that the database was not synchronized with the models. Resetting the database worked fine. Thanks to Alasdair for the suggestion.

It looks like the problem is that was_published_today() is comparing a datetime to a date. Try changing it to:
return self.pub_date.date() == datetime.date.today()

Since the problem seems to be in the code that interprets strings as timestamps, I'd be interested to see the actual data in the db. It looks like there's a timestamp in there that isn't in the proper form. Not sure how it got there without seeing it, but I bet there's a clue there.

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.

InheritanceManager bug when access parent-class elements (Django 2.0)

I'm currently trying to have a object oriented schema in Django 2.0 (Python 3.6.3) with a parent class Program and some children classes Snippet and Software. I saw that the model_utils module contains some tools to handle the polymorphism, and tried to replicate the tutorial (http://django-model-utils.readthedocs.io/en/latest/managers.html), here is what it gives in my case:
models.py
from django.db import models
from model_utils.managers import InheritanceManager
class Program(models.Model):
name = models.CharField(max_length=100)
objects = InheritanceManager()
class Snippet(Program):
code = models.TextField()
class Software(Program):
repoLink = models.URLField()
Django shell
>>> from coding.models import Program
>>> programs = Program.objects.select_subclasses()
>>> programs
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "...\py3django\lib\site-packages\django\db\models\query.py", line 248, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "...\py3django\lib\site-packages\django\db\models\query.py", line 292, in __getitem__
qs = self._chain()
File "...\py3django\lib\site-packages\django\db\models\query.py", line 1156, in _chain
obj = self._clone()
File "...\py3django\lib\site-packages\model_utils\managers.py", line 100, in _clone
return super(InheritanceQuerySetMixin, self)._clone(**kwargs)
TypeError: _clone() got an unexpected keyword argument 'subclasses'
I don't understand this error and how to fix it, and even don't know if it is a fail in my design or a bad use of the InheritanceManager. So what can be the origin of this error message?
According to the docs, django-model-utils only supports Django 1.8 to 1.10.

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

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"
)

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

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.