[英]Can I use standard generic CreateView for model formset?
I am again stuck with model formset.我再次被 model formset 卡住了。 I have following form:
我有以下表格:
ArticleFormSet = modelformset_factory(Article, fields=('title', 'pub_date'), extra=3)
and View for this model formset:并查看此 model 表单集:
class ArticleCreateView(CreateView):
model = Article
form_class = ArticleFormSet
template_name = 'article_form_view.html'
success_url = "/"
Reading documentation here: https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/#model-formsets I understand that, I can use ArticleFormSet instead of standard form for form_class attribute.在此处阅读文档: https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/#model-formsets我了解,我可以使用 ArticleFormSet 而不是标准表单作为 form_class 属性。
So basically, what I am expecting is, this should display 3 forms for the same Article model and I should be able to create three articles at the same time.所以基本上,我所期待的是,这应该为同一篇文章 model 显示 3 forms,我应该能够同时创建三篇文章。
But I am getting "TypeError: init () got an unexpected keyword argument 'instance' ".但我收到“TypeError: init () got an unexpected keyword argument 'instance'”。
So the question is, is this how it supposed to work?所以问题是,这是它应该如何工作的吗? Or what would be the correct way of creating few articles at the same time?
或者同时创建几篇文章的正确方法是什么?
I do not think that the generic CreateView
is by default capable of handling formsets;我不认为通用的
CreateView
默认能够处理表单集。 however, it should be easier to customize the view so it works as you intend.但是,自定义视图应该更容易,因此它可以按您的意愿工作。
From what I see the exception is raised when the view tries to create the form to render.从我看到的情况来看,当视图尝试创建要呈现的表单时会引发异常。 So overriding the
get_form
method is required:因此需要覆盖
get_form
方法:
class ArticleCreateView(CreateView):
...
def get_form(self):
if self.request.method == 'POST':
return self.form_class(self.request.POST)
return self.form_class()
The method either returns the modelformset as created by the factory (in case of calling the formset) or fills it with your posted data.该方法要么返回工厂创建的模型表单集(在调用表单集的情况下),要么用您发布的数据填充它。
One more issue seems to be the success_url.另一个问题似乎是success_url。 You will get an expception when you use a formset.
使用表单集时会出现异常。 So you also need to override that method, eg
因此,您还需要覆盖该方法,例如
...
def get_success_url(self):
return self.success_url
Now it should work.现在它应该可以工作了。
However: If I understand you correctly, you want the view to be used for creating new data.但是:如果我理解正确,您希望该视图用于创建新数据。 The `` modelformset_factory``` fetches all your model instance and appends 3 empty forms.
``modelformset_factory``` 获取所有 model 实例并附加 3 个空 forms。 This might not be what you want.
这可能不是你想要的。 In order to get an empty formset look at this SO post:
为了获得一个空的表单集,请查看此 SO 帖子:
Empty ModelFormset in Django's FormWizard Django 的 FormWizard 中的空 ModelFormset
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.