Opened 12 years ago
Closed 12 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
Note:
See TracTickets
for help on using tickets.
Hi @Siecje, this is the expected behavior as described in https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-fields:
If you only intend to provide a custom widget, you may use the
Meta.widgetsattribute rather than redefining the field.