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....
相关问题
- Django __str__ returned non-string (type NoneType)
- Django & Amazon SES SMTP. Cannot send email
- Django check user group permissions
- Django restrict pages to certain users
- UnicodeEncodeError with attach_file on EmailMessag
相关文章
- Profiling Django with PyCharm
- Why doesn't Django enforce my unique_together
- MultiValueDictKeyError in Django admin
- Django/Heroku: FATAL: too many connections for rol
- Django is sooo slow? errno 32 broken pipe? dcramer
- Django: Replacement for the default ManyToMany Wid
- Upgrading transaction.commit_manually() to Django
- UnicodeEncodeError when saving ImageField containi
Joshmaker's answer doesn't work for me on Django 1.7. Here is what I had to do for Django 1.7:
For more details on this method, please see this relevant Django documentation
stumbled upon same thing and this was first google result on my page.Dint helped, bit more googling and worked!!
Here is how it works for me (django 1.7+) :
Another way you can solve this issue is by using Django currying which is a bit cleaner than just attaching the request object to the form model.
This has the added benefit making your init method on your form a bit more clear as others will understand that it's being passed as a kwarg and not just randomly attached attribute to the class object before initialization.
Here is what i did recently for a Blog:
I can now access the current user in my
forms.ModelForm
by accessingself.current_user
EDIT: This is an old answer, and looking at it recently I realized the
get_form
method should be amended to be:(Note the addition of
*args
)I think I found a solution that works for me: To create a
ModelForm
Django uses the admin'sformfield_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:
Now I can access the current user object in the forms
__init__
with something like:This use case is documented at ModelAdmin.get_form
If you just need to save a field, then you could just override ModelAdmin.save_model