成功验证后,如何从视图中重新显示包含某些错误的表单?
示例:用户正确填写表单,但他的IP已被禁止,因此他应该看到正确的错误消息。我希望它显示为任何其他验证错误。
class MyView(CreateView):
form_class = MyForm
model = MyModel
def form_valid(self, form):
banned = is_ip_banned(self.request)
if banned:
# add error message 'You have been banned'
# redisplay a form with defined errors
return super(MyView, self).form_valid(form)
请注意,我无法覆盖form.is_valid()
,因为我需要request
变量。
答案 0 :(得分:1)
如果您在验证表单时需要请求,则只需将其传入。
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super(MyForm, self).__init__(*args, **kwargs)
def clean(self):
if is_ip_banned(self.request):
raise forms.ValidationError('You have been banned')
...
class MyView(forms.Form):
def get_form(self, form_class):
form_kwargs = self.get_form_kwargs()
form_kwargs['request'] = self.request
return form_class(**form_kwargs)