当覆盖表单清理方法时,您如何知道它在任何字段上的验证失败?例如在下面的表格中,如果我覆盖了干净的方法,我如何知道表格在任何字段上的验证是否失败?
class PersonForm(forms.Form):
title = Forms.CharField(max_length=100)
first_name = Forms.CharField(max_length=100)
surname = Forms.CharField(max_length=100)
password = Forms.CharField(max_length=100)
def clean(self, value):
cleaned_data = self.cleaned_data
IF THE FORM HAS FAILED VALIDATION:
self.data['password'] = 'abc'
raise forms.ValidationError("You have failed validation!")
ELSE:
return cleaned_data
由于
答案 0 :(得分:10)
您可以检查是否有任何错误添加到错误字典中:
def clean(self, value):
cleaned_data = self.cleaned_data
if self._errors:
self.data['password'] = 'abc'
raise forms.ValidationError("You have failed validation!")
else:
return cleaned_data
奖金!您可以检查特定字段的错误:
def clean(self, value):
cleaned_data = self.cleaned_data
if self._errors and 'title' in self._errors:
raise forms.ValidationError("You call that a title?!")
else:
return cleaned_data
答案 1 :(得分:4)
答案 2 :(得分:1)
虽然它的旧帖子,如果您想在同一表单/模型表格的多个字段上应用验证,请使用clean()
。此方法返回 cleaning_data 字典。
要向用户显示错误,您可以使用add_error(<fieldname>, "your message")
方法。这将在表单顶部显示错误以及字段名称。示例如下所示:
add_error()
会自动从 cleaning_data 词典中删除该字段,您无需手动删除该字段。此外,你不必导入任何东西来使用它。
def clean(self):
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
msg = 'passwords do not match'
self.add_error('password2', msg)
return self.cleaned_data
如果您只想在表单/模型的单个字段上进行验证,请使用clean_<fieldname>()
。此方法将使用 cleaning_data 字典中的值,然后您可以检查逻辑错误。检查逻辑后,始终返回值。
def clean_password(self):
password = self.cleaned_data['password']
if len(password)<6:
msg = 'password is too short'
self.add_error('password', msg)
return password
答案 3 :(得分:0)
以下是在clean()
中覆盖django.forms.Form
并在django-braces
中使用AnonymousRequiredMixin
要求只有匿名用户访问Loing页面的简单示例:
class LoginView(AnonymousRequiredMixin, FormView):
"""
Main Login. And Social Logins
"""
template_name = 'core/login.html'
form_class = LoginForm
success_url = reverse_lazy('blog:index')
def get_success_url(self):
try:
next = self.request.GET['next']
except KeyError:
next = self.success_url
return next
def form_valid(self, form):
cd = form.cleaned_data
user = auth.authenticate(username=cd['login_username'],
password=cd['login_password'])
if user:
auth.login(self.request, user)
messages.info(self.request, 'You are logged in.')
return super(LoginView, self).form_valid(form)