views:

64

answers:

1

I've looked at several questions here that looked similar, but none of them discussed the problem from the perspective of admin panel.

I need to check if user has permission to leave a field empty. I wanted to use request.user but I don't knot how to pass 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']
+1  A: 

You could override the ModelAdmin.get_form, by adding the request as an attribute of the newly created form class (should be thread-safe).

Something along these lines:

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.

Clément