如果空值传递给Django中的表单字段,如何验证表单?
Posted
技术标签:
【中文标题】如果空值传递给Django中的表单字段,如何验证表单?【英文标题】:How to validate form if empty values passed to form fields in Django? 【发布时间】:2020-01-27 01:39:28 【问题描述】:下面是表格:
努力通过为某些表单字段发送空值来验证表单。
姓名和电话是必填字段。当用户输入并单击提交时,所有值应连接并保存在文件中。
forms.py
from django import forms
class ReviewForm1(forms.Form):
PRECAUTIONS_CHOICES = (
('no', 'No'),
('yes', 'Yes')
)
UNIT1_CHOICES = (
('Very Satisfied', 'Very Satisfied'),
('Satisfied', 'Satisfied'),
('neutral', 'neutral'),
('Unsatisfied', 'Unsatisfied'),
('Very Unsatisfied', 'Very Unsatisfied'),
)
name = forms.CharField(required=True, widget=forms.TextInput(attrs='required': 'true'))
phone = forms.CharField(required=False)
email = forms.EmailField(required=True, widget=forms.TextInput(attrs='required': 'true'))
precautions = forms.ChoiceField(required=True, choices= PRECAUTIONS_CHOICES, widget=forms.Select())
unit1_ambience = forms.ChoiceField(required=True, choices= UNIT1_CHOICES, widget=forms.Select())
review = forms.CharField(required=False, widget=forms.Textarea())
def clean(self):
name = self.cleaned_data.get('name')
phone = self.cleaned_data.get('phone')
review = self.cleaned_data.get('review')
email = self.cleaned_data.get('email')
precautions = self.cleaned_data.get('precautions')
unit1_ambience = self.cleaned_data.get('unit1_ambience')
expected_string = ''
options = [name,phone,review,email,precautions,unit1_ambience]
for option in options:
if not option:
continue
else:
expected_string = expected_string + option + '\n'
# concat all with review and then return string
return expected_string
views.py sn-p
@require_POST
@csrf_protect
def revfile_save(request):
"""
This page processes and saves review file.
"""
form = ReviewForm1(request.POST)
if form.is_valid():
review = form.cleaned_data
reviewfile_name = "/root/sjfacweb/" + remote.sjfacweb()
#content writes to timestamped filename
remote.write_reviewfile(reviewfile_name,False,review)
以下是点击保存时出现的错误:
分配前引用的局部变量“review”
我认为 form.is_valid() 返回 false,如何解决这个问题?
谢谢
【问题讨论】:
【参考方案1】:这与“空字段”没有任何关系。该视图的其余部分应位于 is_valid
块内,并且您应该执行其他操作 - 即使用无效表单重新呈现模板 - 当表单无效时。
form = ReviewForm1(request.POST)
if form.is_valid():
review = form.cleaned_data
reviewfile_name = "/root/sjfacweb/" + remote.sjfacweb()
#content writes to timestamped filename
remote.write_reviewfile(reviewfile_name,False,review)
return redirect('somewhere')
else:
return render(request, 'template.html', 'form': form)
请注意,clean()
应该将清理后的数据作为字典返回,而不是串联字符串;连接应该在其他地方完成。
【讨论】:
以上是关于如果空值传递给Django中的表单字段,如何验证表单?的主要内容,如果未能解决你的问题,请参考以下文章
如何动态地将 id 传递给 Bootstrap 验证器规则的 url:远程用于相同的表单输入字段?
Django 表单字段验证 - 如何判断操作是插入还是更新?