views:

307

answers:

3

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

A: 

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

stevejalim
You could make this a super-useful answer if you included some details of how.
Dominic Rodger
well can you give me some hints, can not wait till i get a book...
lazerscience
Google Books has (almost all) of the chapter - see answer above
stevejalim
+1  A: 

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
lazerscience
A: 

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:

http://stackoverflow.com/questions/2991365/how-to-auto-insert-the-current-user-when-creating-an-object-in-django-admin/2992150#2992150

FurtiveFelon
Well if you read my question carefully again, you'll see it's about something else,namely customizing a form according to the displayed user, not about saving the user in the database at all...
lazerscience