Django modelform NOT required field

后端 未结 7 1134
一整个雨季
一整个雨季 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 02:32

    Solution: use both blank=True, null=True.

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

    Explanation:

    if you use null=True

    `my_field = models.PositiveIntegerField(null=True)`
    

    then my_field is required, with * against it in form, you cant submit empty value.

    if you use blank=True

    `my_field = models.PositiveIntegerField(blank=True)`
    

    then my_field is not required, no * against it in form, you cant submit value. But will get null field not allowed.

    Note:

    1) marking as not required and 
    2) allowing null field are two different things.
    

    Pro Tip:

    Read the error more carefully than documentation.
    

提交回复
热议问题