Django: how to hide/overwrite default label with ModelForm?
Asked Answered
C

6

14

i have the following, but why does this not hide the label for book comment? I get the error 'textfield' is not defined:

from django.db import models
from django.forms import ModelForm, Textarea

class Booklog(models.Model):
    Author = models.ForeignKey(Author)
    Book_comment = models.TextField()
    Bookcomment_date = models.DateTimeField(auto_now=True)

class BooklogForm(ModelForm):
    #book_comment = TextField(label='')

    class Meta:
        model = Booklog
        exclude = ('Author')
        widgets = {'book_entry': Textarea(attrs={'cols': 45, 'rows': 5}, label={''}),}  
Carmelinacarmelita answered 17/2, 2012 at 17:18 Comment(5)
maybe not hide, but change the label to nothing?Carmelinacarmelita
Have you imported forms.TextField?Goldsmith
I did not, I only have from django.forms import ModelForm, Textarea. when I try to add ", TextField" i get an import error...Carmelinacarmelita
Oops. There isn't a forms.TextField. Use a forms.CharField with a Textarea widget.Goldsmith
this is driving me nuts, what is the correct syntax? does anyone know how to simply replace the default label??Carmelinacarmelita
G
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',)
Goldsmith answered 17/2, 2012 at 19:32 Comment(0)
H
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

Hammy answered 31/12, 2013 at 18:21 Comment(0)
R
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'
Retrogression answered 10/12, 2015 at 15:38 Comment(0)
R
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'),
    }
Raber answered 20/4, 2019 at 20:30 Comment(0)
F
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.)

Freelance answered 17/2, 2012 at 17:20 Comment(3)
I believe that Django's documentation recommends tuples because since the exclude values would not change, there is no point of having a list (which is mutable). List are bigger than tuples because of that mutable property. a = ('a',), b = ['a'] then use the __ sizeof __ method and check the size ;-)Massenet
i just want the label to be blank, im following the docs exactly and im able to override the default label...Carmelinacarmelita
@markuz: I assume that's the case, but I still think it's wrong, as tuples aren't just immutable lists.Freelance
H
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.

Holofernes answered 17/2, 2012 at 17:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.