views:

64

answers:

1

Hello, 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
+1  A: 

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)
Dominic Rodger
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
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
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
@Daniel Roseman - thanks! Knew you'd find this eventually!
Dominic Rodger