django Model Forms customizing fields

别来无恙 提交于 2019-12-22 08:53:11

问题


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 ?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/14027185/django-model-forms-customizing-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!