Common Pitfalls - Data Models
If you encounter a strange error, make sure to run django-admin.py validate. That catches some common errors in model syntax.
Using module globals in models
The model module, being a Python module, can import modules or define globals. You might want to use those globals or imported modules in your models classes methods like this:
import md5
class Something(meta.Model):
def func(self, parm):
md5.new()
Warning
In Django 0.90 and Django 0.91, and in Django trunk up until the merge of the magic-removal branch, you may encounter problems with importing modules or defining global variables in a model file, because those versions of Django create dynamic model classes at runtime which do not get the global scope of the original model file. To work around this, give your model a 'module_constants' dictionary like so:
import md5
class Something(meta.Model):
class META:
module_constants = {
'md5': md5
}
def func(self, parm):
md5.new()
Or, simply import the modules needed in the function itself:
class Something(meta.Model):
...
def func(self):
import md5
md5.new(...)
This problem can also be avoided by using a more recent version of Django (i.e., any trunk version based on the magic-removal codebase).
Symptoms
You get tracebacks with NameErrors in your modules as if the global wasn't there.
ManyToManyField
Name likeness of helper classes and field classes
Warning
The field class is ManyToManyField, not ManyToMany. The latter is for internal use only.
Symptoms
A traceback that talks about __init__ getting 2 instead of 3 required positional parameters in the line of your model where the fields tuple is built.
ImageFields/FileFields
Providing an image field in without media configured
Warning
If you have an ImageField in your model, you need to configure media. See How do I use image and file fields? in the FAQ.
Symptoms
Data not being posted to the database with a refresh of the "add" screen.
If You Find get_X_list, get_X_count, etc. Not Getting Created
If you have a model class (for example Choices) that has a ForeignKey, the class that is the foreign key (for example Polls) gets methods like get_X_list, get_X_count (for example, Polls.get_choice_list, Polls.get_choice_count).
However, if you find those are not getting created, and you have a multi-file model, check to make sure that you have updated the __all__ variable in your model's __init__.py. It can be tough to remember to update that with the list of all your files in your model. If a particular model file isn't in __all__, those methods won't get created in your model objects.
