Django modelform NOT required field

后端 未结 7 1132
一整个雨季
一整个雨季 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:31

    The above answers are correct; nevertheless due note that setting null=True on a ManyToManyField has no effect at the database level and will raise the following warning when migrating:

    (fields.W340) null has no effect on ManyToManyField.

    A good answer to this is explained in this other thread.

    0 讨论(0)
  • 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.
    
    0 讨论(0)
  • 2021-01-30 02:33
    field = models.CharField(max_length=9, default='', blank=True)
    

    Just add blank=True in your model field and it won't be required when you're using modelforms.

    source: https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/#field-types

    0 讨论(0)
  • 2021-01-30 02:36

    Guess your model is like this:

    class My_Class(models.Model):
    
        address = models.CharField()
    

    Your form for Django version < 1.8:

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

    Your form for Django version > 1.8:

    class My_Form(ModelForm):
    
        address = forms.CharField(blank=True)
    
        class Meta:
            model = My_Class
            fields = ('first_name', 'last_name' , 'address')
    
    0 讨论(0)
  • 2021-01-30 02:36
    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
    
    0 讨论(0)
  • 2021-01-30 02:44

    You would have to add:

    address = forms.CharField(required=False)
    
    0 讨论(0)
提交回复
热议问题