是否需要在我们的项目中实现ModelForm以便在Django 2.0.2中实现CreateView(CBV)?

时间:2018-12-15 18:13:42

标签: python django django-class-based-views django-2.0

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

2 个答案:

答案 0 :(得分:1)

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

假设您有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

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

更多信息: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

答案 1 :(得分:0)

您无需创建ModelForm,只需在model属性中指定模型,例如Author模型集model = Author

CreateView使用ModelFormMixin,该https://docs.djangoproject.com/en/2.1/ref/class-based-views/mixins-editing/#django.views.generic.edit.ModelFormMixin.model使用此model属性来处理ModelForm:

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

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

在此处查看更多信息:https://react-bootstrap.github.io/getting-started/introduction/