How to clear form data depending on registered user in django admin panel?

I looked at a few questions that looked similar, but none of them discussed the issue from the perspective of the admin panel.

I need to check if the user has permission to leave the field empty. I wanted to use request.user, but I do not know how to pass the request from EntryAdmin to ModelForm. I wanted to do something like this:

class EntryAdminForm(ModelForm): class Meta: model = Entry def clean_category(self): if not self.request.user.has_perm('blog.can_leave_empty_category') and not bool(self.category): raise ValidationError(u'You need to choose a Category!') else: return self.cleaned_data['category'] 
+4
source share
1 answer

You can override ModelAdmin.get_form by adding the request as an attribute of the newly created form class (it must be thread safe).

Something like that:

 class EntryAdmin(admin.ModelAdmin): form = EntryAdminForm def get_form(self, request, *args, **kwargs): form = super(EntryAdmin, self).get_form(request, *args, **kwargs) form.request = request return form 

Then the code in your question should work.

+2
source

Source: https://habr.com/ru/post/1306764/


All Articles