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, so that i can customize the form in its __init__
method?
I think saving the current request in a thread local would be a possibility but this would be my last resort think I'm thinking it is a bad design approach....
views:
307answers:
3Not a super-useful answer, but Chapter 11 of Pro Django details a non-threadlocals way of doing it.
Slightly more useful answer - Google Books has almost all of the chapter - bar the last bits, but you may well be able to work it out from there.
It's worth buying the book if you have the opportunity too.
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
Just in case anyone is monitoring this forum, here is a solution i've posted to my own question which i believe is cleaner and easier to understand: