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

thedeepfield picture thedeepfield · Feb 17, 2012 · Viewed 31.1k times · Source

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={''}),}  

Answer

Alasdair picture Alasdair · Feb 17, 2012

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',)