4
votes

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 ?

2
Please specific what happen when you say it's not working. For example from your code you not indent a line after "class" define (line contain : name = ... ) that will made a syntax error. - Pattapong J
not working is for example i can't use CharField alone i need to add models.CharField, but then the label is not changing because models.CharField dont have label attribute. The runserver command is hanging at Validating models... with no errors. And i forgot indendts writing my question here but not in project - Chris

2 Answers

6
votes

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')
1
votes

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