Django modelform NOT required field

后端 未结 7 1133
一整个雨季
一整个雨季 2021-01-30 01:54

I have a form like this:

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


        
相关标签:
7条回答
  • 2021-01-30 02:46

    @Anentropic's solution from the comment on @Atma's answer worked for me. And I think it's the best one too.

    His comment:

    null=True, blank=True will cause the ModelForm field to be required=False

    I just set it on my ManyToMany field in my UserProfile class and it worked flawlessly.

    My UserProfile class now looks like this (notice the friends field):

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

    I also think that this is the most beautiful solution since you do the same thing, put null and blank to True, weather you have a simple char field or, like I have, ManyToMany field.

    Again, thanks alot @Anentropic. :)

    P.S. I wrote this as a post since I couldn't comment (I have less than 50 reputation) but also because I think his comment needs more exposure.

    P.P.S. If this answer helped you, please do upwote his comment.

    Cheers :)

    0 讨论(0)
提交回复
热议问题