Model's verbose_name not getting used as field label when specifying a field type in ModelForm

544 views
Skip to first unread message

Michael Corey

unread,
Feb 1, 2019, 10:08:48 PM2/1/19
to Django users
I'm having trouble getting the verbose_name attribute of a model field to show up when rendering a ModelForm. instead, the label uses the pretty version of the field name, not the verbose_name. This occurs any time I specify a field type, and works properly (shows the verbose_name) if I don't specify a field type.

Version 1: This works (i.e. it shows the verbose name as the label)...
```
# models.py

class Pitch(models.Model):
    dummy = models.CharField(verbose_name="not a real field just so I can exclude something for this bug report")
    who = models.TextField(max_length=3000, verbose_name="In a few lines, tell us what your story is about and what question your story is trying to answer.")


# forms.py
class PitchForm(forms.ModelForm):
    class Meta:
        model = Pitch
        excludes = ['dummy']

# pitchform.html

 {% for field in form %}
      {{ field.label }}
      <div class="fieldWrapper">
          {{ field.errors }}
          {{ field.label_tag }} {{ field }}
          {% if field.help_text %}
          <p class="help">{{ field.help_text|safe }}</p>
          {% endif %}
      </div>
      {% endif %}
 {% endfor %}

```

Version 2: This does not work (shows a prettified version of the field name, not the verbose_name). The only difference is specifying a CharField in forms.py
```
# models.py

class Pitch(models.Model):
    dummy = models.CharField(verbose_name="not a real field just so I can exclude something for this bug report")
    who = models.TextField(max_length=3000, verbose_name="In a few lines, tell us what your story is about and what question your story is trying to answer.")


# forms.py
class PitchForm(forms.ModelForm):
    who = forms.CharField(widget=forms.Textarea)
   
    class Meta:
        model = Pitch
        excludes = ['dummy']

# pitchform.html

 {% for field in form %}
      {{ field.label }}
      <div class="fieldWrapper">
          {{ field.errors }}
          {{ field.label_tag }} {{ field }}
          {% if field.help_text %}
          <p class="help">{{ field.help_text|safe }}</p>
          {% endif %}
      </div>
      {% endif %}
 {% endfor %}

```

Am I doing it wrong?

Thanks

Tim Graham

unread,
Feb 1, 2019, 10:17:23 PM2/1/19
to Django users
When you add a form field like that, it removes inheritance of field attributes like verbose_name from the model.

Instead, you could override Form.__init__() and set the widget similar to what's described at https://docs.djangoproject.com/en/stable/ref/forms/widgets/ "Or if the field isn’t declared directly on the form..."

I think it would be: self.fields['who'].widget = forms.Textarea()

Michael Corey

unread,
Feb 1, 2019, 10:32:53 PM2/1/19
to Django users
Yup, that works! Thank you!
Reply all
Reply to author
Forward
0 new messages