django模型表单定制字段

django模型表单定制字段

本文介绍了django模型表单定制字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个具有一些类的模型:

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)
(...)

并且在同一个models.py文件中,我添加了一个对应于我的一个模型的类,以便我可以创建一个表单:

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

如何自定义通过ModelForm类创建的表单字段?我正在读django文档,我无法理解覆盖默认类型的部分。
例如,在文档中,他们说这将工作:

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

我必须创建一个像models.py一样的文件,具有与Model类相同的字段,然后自定义它们?是否可以使用模型窗体来更改单个字段的CSS属性,如width,height?

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 ?

推荐答案

表单的字段使用差异库创建一个从。您需要导入 django.forms 并使用特定字段 form.XXX

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

这篇关于django模型表单定制字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 23:18