你如何验证Django 1.7中的下拉列表?

时间:2014-11-15 08:06:33

标签: python django

我有一个Django表单,在创建验证时没有记录Dropdown值。而是验证读取值始终为null。这因此触发了验证:

This field cannot be null.

我可能做错了什么?我是Django框架的新手,所以任何帮助都会受到赞赏。这是我的forms.py文件:

from django import forms 
from reviews.models import Rating, Review

CHOICES = (
    (1,'One Star'),
    (2,'Two Star'),
    (3,'Three Star'),
    (4,'Four Star'),
    (5,'Five Star')
)

SERVICES = (
(0, 'Select a Service Name or Start typing'),
(85, 'Service1'),
(86, 'Service2'),
(88, 'Service3'),
(89, 'Service4'),
(90, 'Service5')
)

class ReviewForm(forms.ModelForm):
    serv_id = forms.ChoiceField(required=True, choices= SERVICES, widget=forms.Select(attrs={'class':'form-control'}))
    rating_value = forms.ChoiceField(required = True, choices = CHOICES,  widget=forms.RadioSelect(attrs={'class' : ''}))
    review_text = forms.CharField(required=True, widget=forms.Textarea(attrs={'class' : 'form-control', 'placeholder': 'Write Review', 'rows':5}))

    class Meta:
        model = Review
        fields = ('rating_value', 'review_text', 'serv_id',)

    def clean_serv_id(self):
        serv_id = self.cleaned_data['serv_id']
        if serv_id <= 0:
            raise forms.ValidationError("You need to select a Service.")

只要用户从下拉列表中选择一个选项(id整数值),它就可以工作。问题是当id = 0(用户没有选择服务)时,验证不会被触发:

2 个答案:

答案 0 :(得分:1)

您需要从clean_serv_id返回值。

def clean_serv_id(self):
    serv_id = self.cleaned_data['serv_id']
    if serv_id <= 0:
        raise forms.ValidationError("You need to select a Service.")
    else:
        return serv_id

答案 1 :(得分:0)

我之前要发布的很多..问题是我的验证中的比较运算符不正确 - 哦,我肯定需要返回serv_id,我只是在尝试调试之后将其从原始代码中删除某种原因..显然,我在我的小部件中用作值的数值0被解释为&#34; 0&#34;在ChoiceField中。

这是有效的验证。请注意,我还必须将比较运算符更改为&#34; ==&#34;:

def clean_serv_id(self):
        serv_id = self.cleaned_data['serv_id']
        if serv_id == "0":
            raise forms.ValidationError("You need to select a Service.")
        else:
            return serv_id