下面是表格:通过为某些表单字段发送空值来努力验证表单。姓名和电话是必填字段。当用户键入并单击提交时,应将所有值连接起来并保存在文件中。表格.pyfrom django import formsclass 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以下是单击保存时出现的错误:赋值前引用的局部变量“review”我认为 form.is_valid() 返回 false,如何解决这个问题?
1 回答
宝慕林4294392
TA贡献2021条经验 获得超8个赞
这与“空字段”没有任何关系。该视图的其余部分应该在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()应该将清理后的数据作为字典返回,而不是连接字符串;连接应该在其他地方完成。
添加回答
举报
0/150
提交
取消