I am overriding the save_model method of my ModelAdmin so I can set some additional fields on the model. However, I keep getting a DoesNotExist exception. I stepped through the code with a debugger and I’m a bit confused.
The model has this field:
created_by = models.ForeignKey(User, db_column='created_by', related_name='%(class)s_creator')
In the save_model method when I look at the attributes of the obj parameter, I see this:
Name:
created_by
Value:
str: Traceback (most recent call last):
File "/home/vicki/.eclipse/org.eclipse.platform_3.7.0_155965261/plugins/org.python.pydev.debug_2.3.0.2011121518/pysrc/pydevd_resolver.py", line 182, in _getPyDictionary
attr = getattr(var, n)
File "/usr/lib/pymodules/python2.7/django/db/models/fields/related.py", line 301, in __get__
raise self.field.rel.to.DoesNotExist
DoesNotExist
Name:
created_by_id
Value:
NoneType: None
Where did ‘created_by_id’ come from, and why does ‘created_by’ not exist?
Is there a particular reason why you have used
db_column='created_by'? Are you dealing with a legacy database? Normally, you would let Django handle the name of the db column. By default, Django will append_idto the field name to create the db column name. This is explained in the Django Foreign Key docs.On your model instance you can access:
You can’t access
obj.created_byin your method because you haven’t assigned a user to it yet. Thecreated_by_idvalue isNone, and trying to fetch aUserwith primary keyNonenaturally raises aDoesNotExistexception.Your
save_modelmethod should look something like this: