Reputation: 527
I have created a model with some classes:
class Student(models.Model):
name = models.CharField(max_length=40)
last_name = models.CharFIeld(max_length=40)
(...)
and in the same models.py file at the bottom I've added a class corresponding to one of my models so i can create a form:
class StudentForm(ModelForm):
class Meta:
model = Student
How do I customize form fields created via ModelForm class ? I was reading django Documentation and I can't understand overriding the default types part. For example, in documentation they say this will work:
class ArticleForm(ModelForm):
pub_date = DateField(label='Publication date')
class Meta:
model = Article
but when i type my values it's not working. I can't define my label:
class StudentForm(ModelForm):
name = CharField(label='New label')
class Meta:
model = Student
Do i have to create a file like forms.py with identical fields as in Model class and then customize them ? Is it possible to change single field css attributes like width, height using only Model Forms ?
Upvotes: 4
Views: 6122
Reputation: 8036
In order to customize field in model form, you don't need to create it manually. Django model fields have special attributes:
verbose_name
(goes to label of the field)help_text
(by default rendered as additional description below the field)So, all you need is:
class Student(models.Model):
name = models.CharField(
max_length=40,
verbose_name="Student's Name",
help_text="Please tell me your name") # Optional
last_name = models.CharFIeld(max_length=40)
...
Then you don't need to do any customization in model form.
See: https://docs.djangoproject.com/en/dev/ref/models/fields/#verbose-name
Upvotes: 1
Reputation: 1224
Field for form use a difference library to create a from. You need to import django.forms
and use form.XXX
for specific Field
from django import forms
class StudentForm(ModelForm):
class Meta:
model = Student
subject = forms.CharField(label='New label')
Upvotes: 6