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
Adding (and adjusting) Daniel Roseman's answer from another question:
and in your view:
There is a way to achieve this without creating additional admin views: use a form metaclass in
get_form()
: