Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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={''}),}  
like image 409
thedeepfield Avatar asked Feb 17 '12 17:02

thedeepfield


People also ask

How do I hide a label in Django?

You could add a custom CSS class to the field, and in your CSS make that class invisible. I missed that the input was hidden so accessibility isn't a concern. It is just a control hidden input, I do not need the label, I am using this hidden input as a token.

How do I remove a form label in Django?

In __init__ method set your field label as empty. This will remove label text.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is the difference between form and ModelForm in Django?

The main difference between the two is that in forms that are created from forms. ModelForm , we have to declare which model will be used to create our form. In our Article Form above we have this line " model = models. Article " which basically means we are going to use Article model to create our form.


2 Answers

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',)
like image 168
Alasdair Avatar answered Sep 22 '22 01:09

Alasdair


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

like image 25
Alan Illing Avatar answered Sep 19 '22 01:09

Alan Illing