gpt4 book ai didi

python-3.x - Django 表单验证检查不起作用

转载 作者:行者123 更新时间:2023-12-05 04:28:00 25 4
gpt4 key购买 nike

我在我的 Django 表单中给出了这个验证规则,所以当该字段为空时,它会出现验证错误,但验证时间到了,我的意思是什么时候没有或没有我每次都收到验证错误,我如何解决这个问题。模型.py

class Check(models.Model):
use_for_car = models.BooleanField(default=False)

表格.py

class CheckForm(forms.ModelForm):
translated_names = TranslationField()

def clean(self):
cleaned_data = super(CheckForm, self).clean()
use_for_car = self.cleaned_data.get("use_for_car")

if use_for_car is None:
raise ValidationError("Use For Car NEED TO BE FILLED ")
return use_for_registrations

class Meta:
fields = "__all__"
model = models.Check

最佳答案

情况已经如此,因为您没有指定 blank=True [Django-doc] ,这意味着表单字段是必需的,所以这意味着对于表单字段,required=True [Django-doc] , 而对于 BooleanField form field [Django-doc] ,这意味着:

Since all Field subclasses have required=True by default, the validation condition here is important. If you want to include a boolean in your form that can be either True or False (e.g. a checked or unchecked checkbox), you must remember to pass in required=False when creating the BooleanField.

因此您可以简单地让 Django 完成工作:

class CheckForm(forms.ModelForm):
translated_names = TranslationField()

# no clean override

class Meta:
model = models.Check
fields = '__all__'

关于python-3.x - Django 表单验证检查不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72706800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com