Django 的 forms.Form 与 forms.ModelForm [英] Django's forms.Form vs forms.ModelForm

查看:22
本文介绍了Django 的 forms.Form 与 forms.ModelForm的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能向我解释一下 Django forms.Form 的异同?forms.ModelForm?

Could anyone explain to me similarities and differences of Django's forms.Form & forms.ModelForm?

推荐答案

forms.Form 创建的表单由您手动配置.您最好将这些用于不直接与模型交互的表单.例如,联系表单或时事通讯订阅表单,您可能不一定会在其中与数据库进行交互.

Forms created from forms.Form are manually configured by you. You're better off using these for forms that do not directly interact with models. For example a contact form, or a newsletter subscription form, where you might not necessarily be interacting with the database.

forms.ModelForm 创建的表单将自动创建,然后可以由您调整.最好的例子确实来自 Django 网站上提供的极好的文档.

Where as a form created from forms.ModelForm will be automatically created and then can later be tweaked by you. The best examples really are from the superb documentation provided on the Django website.

forms.Form:
文档:表单对象
使用 forms.Form 创建的普通表单示例:

forms.Form:
Documentation: Form objects
Example of a normal form created with forms.Form:

from django import forms

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

forms.ModelForm:
文档:从模型创建表单
直接来自文档:

forms.ModelForm:
Documentation: Creating forms from models
Straight from the docs:

如果您的表单将用于直接添加或编辑 Django 模型,您可以使用 ModelForm 来避免复制您的模型描述.

If your form is going to be used to directly add or edit a Django model, you can use a ModelForm to avoid duplicating your model description.

使用 forms.Modelform 创建的模型表单示例:

Example of a model form created with forms.Modelform:

from django.forms import ModelForm
from . import models

# Create the form class.
class ArticleForm(ModelForm):
    class Meta:
        model = models.Article

此表单自动具有与创建它的 Article 模型相同的所有字段类型.

This form automatically has all the same field types as the Article model it was created from.

这篇关于Django 的 forms.Form 与 forms.ModelForm的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆