Django required field in model form

前端 未结 6 1517
栀梦
栀梦 2020-11-29 19:44

I have a form where a couple of fields are coming out as required when I don\'t want them too. Here is the form from models.py

class CircuitForm(ModelForm):
         


        
6条回答
  •  Happy的楠姐
    2020-11-29 20:28

    From the model field documentation,

    If you have a model as shown below,

    class Article(models.Model):
        headline = models.CharField(
            max_length=200,
            null=True,
            blank=True,
            help_text='Use puns liberally',
        )
        content = models.TextField()
    

    You can change the headline's form validation to required=True instead of blank=False as that of the model as defining the field as shown below.

    class ArticleForm(ModelForm):
        headline = MyFormField(
            max_length=200,
            required=False,
            help_text='Use puns liberally',
        )
    
        class Meta:
            model = Article
            fields = ['headline', 'content']
    

    So answering the question,

    class CircuitForm(ModelForm):
        begin = forms.DateTimeField(required=False)
        end = forms.DateTimeField(required=False)
            class Meta:
                model = Circuit
                exclude = ('lastPaged',)
    

    this makes begin and end to required=False

提交回复
热议问题