Django modelform不是必填字段

eni9jsuy  于 2022-12-14  发布在  Go
关注(0)|答案(7)|浏览(309)

我有这样一张表格:

class My_Form(ModelForm):
    class Meta:
        model = My_Class
        fields = ('first_name', 'last_name' , 'address')

如何将地址字段设置为可选?

nzk0hqpo

nzk0hqpo1#

class My_Form(forms.ModelForm):
    class Meta:
        model = My_Class
        fields = ('first_name', 'last_name' , 'address')

    def __init__(self, *args, **kwargs):
        super(My_Form, self).__init__(*args, **kwargs)
        self.fields['address'].required = False
xienkqul

xienkqul2#

你的模型大概是这样的:

class My_Class(models.Model):

    address = models.CharField()

Django版本〈1.8的表单:

class My_Form(ModelForm):

    address = forms.CharField(required=False)

    class Meta:
        model = My_Class
        fields = ('first_name', 'last_name' , 'address')

Django版本〉1.8的表单:

class My_Form(ModelForm):

    address = forms.CharField(blank=True)

    class Meta:
        model = My_Class
        fields = ('first_name', 'last_name' , 'address')
c0vxltue

c0vxltue3#

field = models.CharField(max_length=9, default='', blank=True)

只需在model字段中添加blank=True,在使用modelforms时就不需要它了。
如果模型字段具有blank=True,则在表单字段上将required设置为False。否则,将设置为required=True
资料来源https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#field-types
[编辑]:将django文档链接从3.1更改为4.1

pnwntuvh

pnwntuvh4#

你必须加上:

address = forms.CharField(required=False)
nkcskrwz

nkcskrwz5#

解决方案:同时使用blank=Truenull=True

my_field = models.PositiveIntegerField(blank=True, null=True)

说明:
如果使用null=True

my_field = models.PositiveIntegerField(null=True)

那么my_field是必需的,在表单中它旁边有*,并且您不能提交空值。
如果使用blank=True

my_field = models.PositiveIntegerField(blank=True)

my_field不是必需的,表单中它旁边不会有*,您无法提交值。但它将获得不允许的空字段。
注意:标记为非必需和允许空字段是两件不同的事情。
专业提示:阅读错误比阅读文档更仔细。

yws3nbqq

yws3nbqq6#

@Atma回答的评论中的Anentropic的解决方案对我很有效,我认为这也是最好的一个。
他的评论:
null=True, blank=True将导致ModelForm字段变为required=False
我只是在我的UserProfile类中的ManyToMany字段上设置了它,它工作得非常完美。
我的UserProfile类现在看起来如下所示(注意friends字段):

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    friends = models.ManyToManyField('self', null=True, blank=True)

我还认为这是最漂亮的解决方案,因为你做同样的事情,把nullblankTrue,无论你有一个简单的char字段或像我一样,ManyToMany字段。

hk8txs48

hk8txs487#

以上答案正确;不过,请注意,在ManyToManyField上设置null=True在数据库级别上没有影响,并且在迁移时会引发以下警告:
(fields.W340) null has no effect on ManyToManyField.
另一个thread解释了这个问题的一个很好的答案。

相关问题