[英]How do I save post data using a decorator in Django
我的django应用程序中有以下视图。
def edit(request, collection_id):
collection = get_object_or_404(Collection, pk=collection_id)
form = CollectionForm(instance=collection)
if request.method == 'POST':
if 'comicrequest' in request.POST:
c = SubmissionLog(name=request.POST['newtitle'], sub_date=datetime.now())
c.save()
else:
form = CollectionForm(request.POST, instance=collection)
if form.is_valid():
update_collection = form.save()
return redirect('viewer:viewer', collection_id=update_collection.id)
return render(request, 'viewer/edit.html', {'form': form})
它显示一个表格,使您可以编辑图像集合。 我html的页脚包含一个表格,该表格使您可以从管理员那里请求一个新的图像源。 它提交给与CollectionForm不同的数据模型。 由于这是每个视图的页脚,因此我想提取代码的5-7行并将其转换为装饰器。 这可能吗,如果可以的话,我该怎么做呢?
我将创建一个新视图来处理表单的发布。 然后将空白表单实例放在上下文处理器或其他东西中,以便可以将其打印在每一页上。
如果您确实想做一个装饰器,我建议使用基于类的视图。 这样,您可以轻松地创建一个处理表单的基视图类,而其他所有视图都可以对其进行扩展。
编辑:
以下是基于类的视图的文档: https : //docs.djangoproject.com/en/dev/topics/class-based-views/intro/
注意,我仍然建议为POST表单使用一个单独的视图,但是以下是基于类的视图的解决方案:
class SubmissionLogFormMixin(object):
def get_context_data(self, **kwargs):
context = super(SubmissionLogFormMixin, self).get_context_data(**kwargs)
# since there could be another form on the page, you need a unique prefix
context['footer_form'] = SubmissionLogForm(self.request.POST or None, prefix='footer_')
return context
def post(self, request, *args, **kwargs):
footer_form = SubmissionLogForm(request.POST, prefix='footer_')
if footer_form.is_valid():
c = footer_form.save(commit=False)
c.sub_date=datetime.now()
c.save()
return super(SubmissionLogFormMixin, self).post(request, *args, **kwargs)
class EditView(SubmissionLogFormMixin, UpdateView):
form_class = CollectionForm
model = Collection
# you can use SubmissionLogFormMixin on any other view as well.
请注意,这非常粗糙。 不知道它是否会完美地工作。 但这应该给您一个想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.