zjm1126
zjm1126

Reputation: 35672

Defining a model class in Django shell fails

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 "<console>", line 1, in <module>
  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

What can I do?

Upvotes: 27

Views: 8654

Answers (3)

Zaky German
Zaky German

Reputation: 14334

I ran into this problem using Eclipse, Django and PyDev. I needed to have the application (instead of some .py file for example) selected in the PyDev Package Explorer (left panel) before clicking Run for everything to work properly.

Upvotes: 0

Bryan Wolfford
Bryan Wolfford

Reputation: 2182

That other answer definitely works for the interactive prompt, however, I don't think that the intention of the first block of code was intended to actually be run. Immediately following that code in the models documentation, you are expected to put the next codes into your models.py file created during the previous tutorial... I guess that's why they subtly labeled that section "Quick Example." What a headache for me too!

Upvotes: 0

Chris Morgan
Chris Morgan

Reputation: 90752

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

Upvotes: 45

Related Questions