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={''}),}
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.
In __init__ method set your field label as empty. This will remove label text.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
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.
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',)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With