Opened 13 years ago

Closed 13 years ago

#6625 closed (invalid)

Overriding the default field types in a ModelForm doesn't maintain core field arguments

Reported by: stp2007 <stp2007@…> Owned by: nobody
Component: Forms Version: master
Severity: Keywords: ModelForm
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


Using ModelForm to generate a form class for cWilt. When overriding the default field type (for age in this example) field arguments 'verbose_name', 'help_text' and 'default' defined in the original model do not seem to be maintained and do not display correctly in the form. For example, help_text doesn't display at all and the label displayed is "Age" not "Age - VName"

# **************************
class cWilt(Model):
    summary = models.CharField(max_length=60, core=True, help_text = 'Summary: help text defined in Model', verbose_name  = "Summary - VName", )
    p_notes = models.TextField(blank=True, help_text='Notes: help text defined in Model', verbose_name  = "Notes - VName",)
    title = models.CharField(max_length=3, choices=returnTitleChoices(), help_text = 'Title: help text defined in Model', verbose_name  = "Title - VName",)
    age = models.IntegerField(max_length=3, help_text = 'Must be a non-zero value', verbose_name  = "Age - VName",)

# **************************
class cWiltForm(ModelForm):
    age = IntegerFieldNonZero()
    class Meta:
        model = cWilt
        fields = ('summary', 'p_notes', 'title', 'age')

# **************************
class IntegerFieldNonZero(fields.IntegerField):
    default_error_messages = {
        'zero': _(u'Value cannot be zero'),
    def clean(self, value):
        value = super(IntegerFieldNonZero, self).clean(value)
        if value == 0:
            raise ValidationError(self.error_messages['zero'])
        return value

Change History (4)

comment:1 Changed 13 years ago by Brian Rosner

According to the ModelForm docs this is intended behavior when you override the field coming from the model. You must explicitly re-define those values in the form.

comment:2 Changed 13 years ago by Brian Rosner

Resolution: invalid
Status: newclosed

comment:3 Changed 13 years ago by stp2007 <stp2007@…>

Resolution: invalid
Status: closedreopened

Understood. However 'verbose_name', 'default' and 'help_text' are valid arguments for a django.db.models field used to define the class model. These same three arguments are NOT valid for django.newforms.fields used to modify the initial class model with ModelForm. Looking into it I cannot find a way to define these three arguments within a form field and therefore this seems to be something missing with ModelForm.

comment:4 Changed 13 years ago by James Bennett

Resolution: invalid
Status: reopenedclosed

You can define them on a form field. This is the intended behavior. Don't reopen this ticket.

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