I have a model that has a user
field that needs to be auto-populated from the currently logged in user. I can get it working as specified here if the user
field is in a standard ModalAdmin, but if the model I'm working with is in an InlineModelAdmin
and being saved from the record of another model inside the Admin, it won't take.
views:
639answers:
5Does the other model save the user? In that case you could use the post_save
signal to add that information to the set of the inlined model.
Have you tried implementing custom validation in the admin as it is described in the documentation? Overriding the clean_user() function on the model form might do the trick for you.
Another, more involved option comes to mind. You could override the admin template that renders the change form. Overriding the change form would allow you to build a custom template tag that passes the logged in user to a ModelForm. You could then write a custom init function on the model form that sets the User automatically. This answer provides a good example on how to do that, as does the link on b-list you reference in the question.
Only the save_model
for the model you're editing is executed, instead you will need to use the post_save
signal to update inlined data.
(Not really a duplicate, but essentially the same question is being answered in http://stackoverflow.com/questions/2164539/do-inline-model-forms-emmit-post-save-signals-django)
I had a similar issue with a user field I was trying to populate in an inline model. In my case, the parent model also had the user field defined so I overrode save
on the child model as follows:
class inline_model:
parent = models.ForeignKey(parent_model)
modified_by = models.ForeignKey(User,editable=False)
def save(self,*args,**kwargs):
self.modified_by = self.parent.modified_by
super(inline_model,self).save(*args,**kwargs)
The user field was originally auto-populated on the parent model by overriding save_model in the ModelAdmin for the parent model and assigning
obj.modified_by = request.user
Keep in mind that if you also have a stand-alone admin page for the child model you will need some other mechanism to keep the parent and child modified_by fields in sync (e.g. you could override save_model
on the child ModelAdmin and update/save the modified_by field on the parent before calling save
on the child).
I haven't found a good way to handle this if the user is not in the parent model. I don't know how to retrieve request.user
using signals (e.g. post_save
), but maybe someone else can give more detail on this.