我总是使用以下代码来验证表单,以防止空白表单提交。它始终在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)
谢谢
由于您是在模型中blank=True
和时指定这些字段,null=True
因此请更改这些属性
class Device(models.Model):
category = models.CharField(max_length=50, blank=False, null=False)
或者默认情况下,如果您未指定这些blank
和null
属性,则默认情况下它将为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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句