在我的项目中,我有一个forms.py,其中包含以下字段:
fullName = forms.CharField(min_length=3, max_length=255, widget=forms.TextInput(attrs={'placeholder': 'Full Name', 'class': 'fullNameField'}))
在我的views.py中,我检查该字段是否不包含空格:
if not ' ' in form.cleaned_data.get('fullName'):
context ['fullNameError'] = "Please enter a valid full name"
[当我提交表单并添加一个空格时,不应该调用the context ['fullNameError']
。
有人知道为什么吗?谢谢。
首先,您想做的是:
if ' ' not in form.cleaned_data.get('fullName'):
# stuff goes here
现在,要使它更干净。表单验证必须在表单内部进行。检查this part of the documentation。
这是您的表单看起来应该很丑:
class MyForm(forms.Form):
# define fields here
def clean_fullName(self):
full_name = self.cleaned_data['fullName']
if ' ' not in full_name:
raise forms.ValidationError("Cannot contain spaces")
return full_name
这样,错误将附加到表单字段,并且您的代码已正确解耦。