我的 Django 应用程序中有以下 View 。
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 不同的数据模型。由于这是在每个 View 的页脚中,我想提取代码的第 5-7 行并将其变成装饰器。这可能吗?如果可能,我该怎么做?
最佳答案
我会创建一个新 View 来处理表单的发布。然后将空白表单实例粘贴到上下文处理器或其他东西中,这样您就可以在每个页面上打印出来。
如果你确实想做一个装饰器,我建议使用基于类的 View 。这样,您就可以轻松地创建一个处理表单的基 View 类,并且每个其他 View 都可以扩展它。
编辑:
这是关于基于类的 View 的文档:https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/
请注意,我仍然建议为表单 POST 使用单独的 View ,但使用基于类的 View ,您的解决方案可能如下所示:
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.
请注意,那非常粗糙。不确定它是否会完美运行。但这应该会给你一个想法。
关于python - 如何在 Django 中使用装饰器保存发布数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26305762/