getting the user from a admin validation class

2019-07-23 23:48发布

I am trying to control admin item entry where non-super user accounts can't save a ChannelStatus model input that has a date attribute which is older than 2 days. I need to get the user so that I can check if the request is a reqular or a super user but couldn't achieve this.

I have already tried "request.user.is_superuser", "user.is_superuser", "self.user.is_superuser" and "self.request.user.is_superuser" but none seem to work.

class ChannelStatusValidForm(forms.ModelForm):
    class Meta:
            model = ChannelStatus
    def clean(self):
        cleaned_data = self.cleaned_data
        mydate = cleaned_data.get("date")
        today = date.today()
        if request.user.is_superuser:## here is the problem
            return cleaned_data
        elif (today - timedelta(days=2)) > mydate:
            raise forms.ValidationError("Invalid date, maximum 2 days allowed.")
        else:
            return cleaned_data

2条回答
别忘想泡老子
2楼-- · 2019-07-24 00:50

Adding (and adjusting) Daniel Roseman's answer from another question:

class ChannelStatusValidForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(MyForm, self).__init__(*args, **kwargs)


    def clean(self):
        cleaned_data = self.cleaned_data
        mydate = cleaned_data.get("date")
        today = date.today()
        if self.request.user.is_superuser:
            return cleaned_data
        elif (today - timedelta(days=2)) > mydate:
            raise forms.ValidationError("Invalid date, maximum 2 days allowed.")
        else:
            return cleaned_data

and in your view:

myform = ChannelStatusValidForm(request.POST, request=request)
查看更多
Bombasti
3楼-- · 2019-07-24 00:50

There is a way to achieve this without creating additional admin views: use a form metaclass in get_form():

class ChannelStatusValidForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None) # Now you can access request anywhere in your form methods by using self.request.            
        super(ChannelStatusValidForm, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = self.cleaned_data
        mydate = cleaned_data.get("date")
        today = date.today()
            request = self.request
        if request.user.is_superuser:
            return cleaned_data
        elif (today - timedelta(days=2)) > mydate:
            raise forms.ValidationError("Invalid date, maximum 2 days allowed.")
        else:
            return cleaned_data
    class Meta:
            model = ChannelStatus

class ChannelStatusAdmin(admin.ModelAdmin):
    form = ChannelStatusValidForm    
    def get_form(self, request, obj=None, **kwargs):
        AdminForm = super(ChannelStatusAdmin, self).get_form(request, obj, **kwargs)
        class ModelFormMetaClass(AdminForm):
            def __new__(cls, *args, **kwargs):
                kwargs['request'] = request
                return AdminForm(*args, **kwargs)
        return ModelFormMetaClass
查看更多
登录 后发表回答