txt.si/blog

Setting default Usef FK in Django Admin to currently logged in user

Content on this page is probably outdated and represents my personal knowledge, feelings and understading of things at that time .

So, I always wanted to set the “author” fields of my Models to currently logged in user. But I also wanted to give the user a choice to change that, so most of the snippets out there were usless for me. So, with a bit of “inspirational” reading and thinking, I got an idea, why not to overload formfield_for_dbfield ( or extend that overload in my case ). Some trips to #django and failed trys and misunderstood docs later I came to the solution, it’s not exactly the nicest, but works well (for now). I’m basicly overloading get_form and storing the current user ( which I get from request, thats handed as a param to get_form ) and then use this information in formfield_for_dbfield.


def get_form(self, req, obj=None, **kwargs):
# save the currently logged in user for later
self.current_user = req.user
return super(PageAdmin, self).get_form(req, obj, **kwargs)

def formfield_for_dbfield(self, db_field, **kwargs):
"””
Hook for specifying the form Field instance for a given database Field
instance.
"””
if db_field.name == ‘author’:
kwargs[‘initial’] = int(self.current_user.id)
return db_field.formfield(**kwargs)

else:
return super(PageAdmin, self).formfield_for_dbfield(db_field, **kwargs)