我正在尝试控制管理员项目条目,其中非超级用户帐户无法保存日期属性超过2天的ChannelStatus模型输入。我需要让用户,以便我可以检查请求是否是一个reqular或超级用户,但无法实现这一点。
我已经尝试过“request.user.is_superuser”,“user.is_superuser”,“self.user.is_superuser”和“self.request.user.is_superuser”,但似乎都没有。
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
答案 0 :(得分:1)
从another question添加(并调整)Daniel Roseman的答案:
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)
答案 1 :(得分:0)
有一种方法可以在不创建其他管理员视图的情况下实现此目的:get_form()
中的 use a form metaclass:
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