Opened 11 years ago

Closed 11 years ago

#21945 closed Uncategorized (invalid)

Overriding field in a ModelForm makes it required

Reported by: Cody Scott Owned by: nobody
Component: Forms Version: 1.6
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I have overriden the due_date field below and it becomes required. If I set required=False then it is not required but I get a validation error that it doesn't match a DateTime. However using widgets in the class Meta: works.


# due_date is a required field
    class AssignmentForm(forms.ModelForm):
       due_date = forms.CharField(
           widget=forms.TextInput(
               attrs={'class': 'datepicker',
                   'data-date-format': 'yyyy-mm-dd',
                   'placeholder': 'YYYY-MM-DD'
                   }))
     
       class Meta:
           model = Assignment
           fields = ['name', 'due_date']
     
     
    #due_date is not required
    class AssignmentForm(forms.ModelForm):
     
       class Meta:
           model = Assignment
           fields = ['name', 'due_date']
           widgets = {
               'due_date': forms.TextInput(
                   attrs={
                       'class': 'datepicker',
                       'data-date-format': 'yyyy-mm-dd',
                       'placeholder': 'YYYY-MM-DD'
                   }
               ),}
     
     
    #models
    from django.db import models
     
    class Assignment(models.Model):
       name = models.CharField(max_length=200)
       due_date = models.DateTimeField(null=True, blank=True)
     
       class Meta:
           ordering = ['due_date']
     
       def __unicode__(self):
           return self.name

Change History (1)

comment:1 by loic84, 11 years ago

Resolution: invalid
Status: newclosed

Hi @Siecje, this is the expected behavior as described in https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-fields:

Fields defined declaratively are left as-is [...] (and) do not draw their attributes like max_length or required from the corresponding model. If you want to maintain the behavior specified in the model, you must set the relevant arguments explicitly when declaring the form field.

If you only intend to provide a custom widget, you may use the Meta.widgets attribute rather than redefining the field.

Note: See TracTickets for help on using tickets.
Back to Top