我是Django框架中的初学者,我正在学习如何在views.py文件中实现CreateView(基于类的视图,用于基于模型创建表单)。
答案 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/