[Fixed]-Django: how to hide/overwrite default label with ModelForm?

18👍

To expand on my comment above, there isn’t a TextField for forms. That’s what your TextField error is telling you. There’s no point worrying about the label until you have a valid form field.

The solution is to use forms.CharField instead, with a Textarea widget. You could use the model form widgets option, but it’s simpler to set the widget when defining the field.

Once you have a valid field, you already know how to set a blank label: just use the label=” in your field definition.

# I prefer to importing django.forms
# but import the fields etc individually
# if you prefer 
from django import forms

class BooklogForm(forms.ModelForm):
    book_comment = forms.CharField(widget=forms.Textarea, label='')

    class Meta: 
        model = Booklog
        exclude = ('Author',)

10👍

If you’re using Django 1.6+ a number of new overrides were added to the meta class of ModelForm, including labels and field_classes.

See: https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#overriding-the-default-fields

9👍

To override just the label you can do

def __init__(self, *args, **kwargs): 
    super(ModelForm, self).__init__(*args, **kwargs)
    self.fields['my_field_name'].label = 'My New Title'

3👍

Found an easy solution below:
https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#overriding-the-default-fields

Basically just add labels dictionary and type the new label you want in your forms meta class.

class AuthorForm(ModelForm):
class Meta:
    model = Author
    fields = ('name', 'title', 'birth_date')
    labels = {
        'name': _('Writer'),
    }

1👍

The exclude attribute takes an iterable (usually a list or tuple). But ('book') is not a tuple; you need to append a comma to make it a tuple, due to a quirk of Python’s syntax: exclude = ('book',).

For this reason, I usually just use lists: exclude = ['book']. (Semantically, it makes more sense to use lists here anyway; I’m not sure why Django’s documentation encourages the use of tuples instead.)

👤mipadi

0👍

First off, you put the field in the Meta class. It needs to go on the actual ModelForm. Second, that won’t have the desired result anyways. It will simply print an empty label element in the HTML.

If you want to remove the label completely, either manually check for the field and don’t show the label:

{% for field in form %}
    {% if field.name != 'book_comment' %}
    {{ field.label }}
    {% endif %}
    {{ field }}
{% endfor %}

Or use JavaScript to remove it.

Leave a comment