亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果空值傳遞給Django中的表單字段,如何驗證表單?

如果空值傳遞給Django中的表單字段,如何驗證表單?

jeck貓 2022-06-07 19:56:40
下面是表格:通過為某些表單字段發送空值來努力驗證表單。姓名和電話是必填字段。當用戶鍵入并單擊提交時,應將所有值連接起來并保存在文件中。表格.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()應該將清理后的數據作為字典返回,而不是連接字符串;連接應該在其他地方完成。


查看完整回答
反對 回復 2022-06-07
  • 1 回答
  • 0 關注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號