gpt4 book ai didi

python - 在为 django 模型创建表单时使用 CreateView 和 forms.Modelform 之间的区别?

转载 作者:太空宇宙 更新时间:2023-11-03 19:55:42 26 4
gpt4 key购买 nike

我有一个 Django 模型来存储文章的信息,我看到了创建表单的方法,用户可以通过该表单创建文章并将其保存在数据库中,但我无法找到两者之间的区别请在这件事上给予我帮助?

1.这是使用 django 表单中的 ModelForm 的第一个方法

...

from django.forms import ModelForm
from myapp.models import Article

class ArticleForm(ModelForm):
class Meta:
model = Article
fields = ['pub_date', 'headline', 'content', 'reporter']

...

2.这是使用createview的第二种方法

from django.views.generic.edit import CreateView
from myapp.models import Article

class ArticleForm(CreateView):
model = Article
... fields = ['pub_date', 'headline', 'content', 'reporter']

使用这两种方法有什么区别?

最佳答案

CreateView 用于创建新对象,它自己处理大部分事情。

Django 文档:

A view that displays a form for creating an object, redisplaying the form with validation errors (if there are any) and saving the object.

对于简单的表单或当所有部件都已制作完成时,您通常会使用 CreateView

另一方面,ModelForm 只是一个基于模型的表单,它处理可以从模型中提取的基本验证,例如可为空、最大长度、数据类型等。但是您需要处理渲染、错误显示甚至保存。如果您有更复杂的验证并且需要重用它们,您可能最终会使用 ModelForm

关于python - 在为 django 模型创建表单时使用 CreateView 和 forms.Modelform 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59551446/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com