从管理员验证类获取用户 [英] getting the user from a admin validation class
问题描述
我正在尝试控制管理项目条目,其中非超级用户帐户无法保存具有超过2天的date属性的ChannelStatus模型输入。我需要得到用户,以便我可以检查请求是否是一个reqular或超级用户,但是无法实现这一点。
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.
我已经尝试过请求。 user.is_superuser,user.is_superuser,self.user.is_superuser和self.request.user.is_superuser,但似乎没有效果。
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
推荐答案
添加(和调整)Daniel Roseman的答案来自:
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
并且在您的视图中:
myform = ChannelStatusValidForm(request.POST, request=request)
这篇关于从管理员验证类获取用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!