Blog Job Engineering
Tuesday, January 03, 2012
 
when I use the Django shell, it shows an error; this is the error:

>>> from django.db import models
>>> class Poll(models.Model):
... question = models.CharField(max_length=200)
... pub_date = models.DateTimeField('date published')
...
Traceback (most recent call last):
File "", line 1, in
File "D:\Python25\lib\site-packages\django\db\models\base.py", line 51, in __new__
kwargs
= {"app_label": model_module.__name__.split('.')[-2]}
IndexError: list index out of range

Solution:

The model definition must come in an application - the error you're seeing there is that it tries to take the __name__ model_module - which should be something like project.appname.models for project\appname\models.py - and get the app name, appname. In the interactive console, the module's __name__ is '__main__' - so it fails.

To get around this, you'll need to specify the app_label yourself in the Meta class;

>>> from django.db import models
>>> class Poll(models.Model):
... question = models.CharField(max_length=200)
... pub_date = models.DateTimeField('date published')
... class Meta:
... app_label = 'test'

For explanation of why you can do that, look at that file mentioned in the traceback, D:\Python25\lib\site-packages\django\db\models\base.py:

    if getattr(meta, 'app_label', None) is None:
# Figure out the app_label by looking one level up.
# For 'django.contrib.sites.models', this would be 'sites'.
model_module
= sys.modules[new_class.__module__]
kwargs
= {"app_label": model_module.__name__.split('.')[-2]}
else:
kwargs
= {}

(Where meta is the Meta class, see just above in that file.)

source = http://stackoverflow.com/questions/4382032/defining-a-model-class-in-django-shell-fails

Labels:

 
Comments: Post a Comment
not another bull crap blog page

ARCHIVES
05/01/2003 - 06/01/2003 / 08/01/2003 - 09/01/2003 / 12/01/2004 - 01/01/2005 / 03/01/2005 - 04/01/2005 / 06/01/2005 - 07/01/2005 / 05/01/2006 - 06/01/2006 / 06/01/2006 - 07/01/2006 / 01/01/2009 - 02/01/2009 / 03/01/2009 - 04/01/2009 / 05/01/2010 - 06/01/2010 / 01/01/2012 - 02/01/2012 / 02/01/2012 - 03/01/2012 / 07/01/2012 - 08/01/2012 /


Powered by Blogger