Django: How to get current user in admin forms

后端 未结 6 1712
花落未央
花落未央 2020-11-30 00:31

In Django\'s ModelAdmin I need to display forms customized according to the permissions an user has. Is there a way of getting the current user object into the form class, s

6条回答
  •  感动是毒
    2020-11-30 01:03

    I think I found a solution that works for me: To create a ModelForm Django uses the admin's formfield_for_db_field-method as a callback.
    So I have overwritten this method in my admin and pass the current user object as an attribute with every field (which is probably not the most efficient but appears cleaner to me than using threadlocals:

        def formfield_for_dbfield(self, db_field, **kwargs):
            field = super(MyAdmin, self).formfield_for_dbfield(db_field, **kwargs)
            field.user = kwargs.get('request', None).user
            return field
    

    Now I can access the current user object in the forms __init__ with something like:

        current_user=self.fields['fieldname'].user
    

提交回复
热议问题