2

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
Hellnar
  • 62,315
  • 79
  • 204
  • 279
  • That's because you don't have a `request` object. You'll need to give the form validation function a `RequestContext` object. – Dominic Rodger Sep 07 '09 at 09:22
  • I tried class ChannelStatusValidForm(forms.ModelForm,request): but it doesn't seem to work. – Hellnar Sep 07 '09 at 09:34
  • Yeah, I've tried googling, and I can't find, or work out how to send it in. I'm sure I've seen it done though. I'm sure someone will help you work it out soon! – Dominic Rodger Sep 07 '09 at 09:44
  • ts the matter of getting request object in form. Daniel has answered it here. http://stackoverflow.com/questions/1057252/django-how-do-i-access-the-request-object-or-any-other-variable-in-a-forms-clea/1057640#1057640 – simplyharsh Sep 07 '09 at 11:12
  • @harshh - great find. I knew I'd seen it somewhere, think that answer might have been here! – Dominic Rodger Sep 07 '09 at 11:23

2 Answers2

1

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)
Community
  • 1
  • 1
Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
  • great! I just couldn't get the last part, the view. For an admin model how can I add this view ? In other words in where will I be adding "myform = ChannelStatusValidForm(request.POST, request=request)" – Hellnar Sep 07 '09 at 12:10
  • Not sure - I can't see anything immediately in the docs for the admin site (http://docs.djangoproject.com/en/dev/ref/contrib/admin/), but you may have more luck spotting it than I did. – Dominic Rodger Sep 07 '09 at 12:40
  • 1
    You'll need to override the ModelAdmin's `add_view` and/or `change_view` methods. Look in `django.contrib.admin.options` for the existing versions. Unfortunately there'll be a fair amount of copy-and-pasted code to just change the lines where the form is instantiated, but that can't be helped at present. – Daniel Roseman Sep 07 '09 at 13:22
0

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
Community
  • 1
  • 1
Ivan Kharlamov
  • 1,889
  • 2
  • 24
  • 33