在Django 2.0.2中实现一个CreateView(CBV)是否有必要在我们的项目中实现ModelForm?

is it necessary to implement ModelForm in our project to implement a CreateView (CBV) in Django 2.0.2?

我是 Django 框架的初学者编程,我正在学习如何在我的 views.py 文件中实现 CreateView(基于 class 的视图,用于创建基于模型的表单)。

不,您不会认为视图会自动为您创建模型表单,但您必须选择覆盖它。

假设您有 MyModel,您可以这样做:

from myapp.models import MyModel

# views.py

class MyCreateView(CreateView):
    model = MyModel
    fields = ['something', 'somethingelse']  # these are fields from MyModel

如果不指定 fields Django 会抛出错误。

如果您想以某种方式自定义您的表单验证,您可以这样做:

# forms.py
class MyForm(ModelForm):
    class Meta:
        model = MyModel
        fields = ['something']  # form fields that map to the model

        # ... do some custom stuff

# views.py
class MyCreateView(CreateView):
    model = MyModel
    form_class = MyForm

请注意,我们不再在 MyView 上指定 fields,因为如果我们这样做也会引发错误,原因是视图将从表单中获取字段。

更多信息:https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-editing/

处理 form_class 的代码:https://github.com/django/django/blob/master/django/views/generic/edit.py#L74

不需要创建ModelForm,只需要在model属性中指定模型即可,例如对于 Author 模型集 model = Author.

CreateView 使用 ModelFormMixin,它使用这个 model 属性来处理 ModelForm:

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

class AuthorCreate(CreateView):
    model = Author
    fields = ['name']

在此处查看更多信息:https://docs.djangoproject.com/en/2.1/ref/class-based-views/mixins-editing/#django.views.generic.edit.ModelFormMixin.model