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