验证空白Django表单字段不起作用

时间:2020-05-26 10:26:57

标签: django django-forms

我始终使用以下代码来验证表单,以防止提交空白表单。它始终可以在Django 1.8中使用,但由于某些原因在Django 2.2中无法使用。

这是表格

class CreateForm(forms.ModelForm):
    class Meta:
        model = Device
        fields = ['category', 'item_name', 'quantity']

    def clean_category(self):
        category = self.cleaned_data.get('category')
        if category == '':
            raise forms.ValidationError('This field is required')
        return category


    def clean_item_name(self):
        item_name = self.cleaned_data.get('item_name')
        if item_name == '':
            raise forms.ValidationError('This field is required')
        return item_name

这是模特

class Device(models.Model):
    category = models.CharField(max_length=50, blank=True, null=True)
    item_name = models.CharField(max_length=50, blank=True, null=True)
    quantity = models.IntegerField(default='0', blank=False, null=True)

谢谢

2 个答案:

答案 0 :(得分:1)

我认为问题是您没有None来回检查,但是。我认为您的目标是自己做太多工作。您只需指定字段为required=True [Django-doc],即可:

默认情况下,每个Field类都假定该值是必需的,因此,如果您传递一个空值– None或空字符串("" –然后{ {1}}将引发clean()异常。

因此我们可以使用以下命令填写必填字段:

ValidationError

也就是说,指定blank=True [Django-doc]相当“奇怪”,因为这实际上意味着模型形式中不需要该字段。 class CreateForm(forms.ModelForm): category = forms.CharField(required=True, max_length=50) item_name = forms.CharField(required=True, max_length=50) class Meta: model = Device fields = ['category', 'item_name', 'quantity']并不意味着允许使用空字符串,因为即使使用blank=True,您也可以在字段中存储空字符串。 blank=False将基于其“包装”的模型定义(大部分)验证,这意味着,如果您更好地定义模型,则将删除大量样板代码。因此,我建议消除ModelForm

答案 1 :(得分:1)

由于您在模型中将这些字段指定为blank=Truenull=True,因此请更改这些属性

class Device(models.Model):
    category = models.CharField(max_length=50, blank=False, null=False)

或者默认情况下,如果您未指定这些blanknull属性,则默认情况下它将为false,因此这也应该起作用

class Device(models.Model):
    category = models.CharField(max_length=50)

编辑基于评论: 就像Willem所说的那样,您需要检查None。可以这样做。

def clean_category(self):
    category = self.cleaned_data.get('category')
    if not category:
        raise forms.ValidationError('This field is required')
    return category