我正在尝试对request.user对象使用验证来限制django管理站点内特定用户的某些行的更新。我得到的印象是我需要覆盖ModelAdmin change_view方法以将请求对象传递给表单。我已经查看了django.contrib.admin.options
中的change_view方法,但作为django的新手,我无法理解change_view方法中需要进行这些修改的位置。任何正确方向的指针都会很棒。
class IssuesAdmin(admin.ModelAdmin):
def change_view(self, request, object_id, extra_context=None):
#modify lines to pass request to form
form = IssuesAdminForm
class IssuesAdminForm(forms.ModelForm):
class Meta:
model = Issues
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(IssuesAdminForm, self).__init__(*args, **kwargs)
def clean_product(self):
if self.request.user.name=='someone'
return self.cleaned_data["product"]
else:
raise forms.ValidationError("Nope!")
答案 0 :(得分:1)
class IssuesAdmin(admin.ModelAdmin):
def change_view(self, request, object_id, extra_context=None): #remember to edit also add_view()... etc
self.form.request = request
form = IssuesAdminForm
class IssuesAdminForm(forms.ModelForm):
class Meta:
model = Issues
def __init__(self, *args, **kwargs):
self.request = # do what you need ;)
super(IssuesAdminForm, self).__init__(*args, **kwargs)
def clean_product(self):
if self.request.user.name=='someone'
return self.cleaned_data["product"]
else:
raise forms.ValidationError("Nope!")