我是 Django 框架的初学者编程,我正在学习如何在 view.py 文件中实现 CreateView(基于类的 View ,用于创建基于模型的表单)。
最佳答案
不, View 不会自动为您创建模型表单,但您必须选择覆盖它。
假设您有 MyModel
,您可以执行以下操作:
from myapp.models import MyModel
# views.py
class MyCreateView(CreateView):
model = MyModel
fields = ['something', 'somethingelse'] # these are fields from MyModel
如果您不指定字段
,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
,因为如果我们这样做,它也会抛出错误,原因是 View 将获取字段从表格中。
更多信息: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
关于python - 为了在Django 2.0.2中实现CreateView(CBV),是否需要在我们的项目中实现ModelForm?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53795938/