如何在Django中使用decorator保存post数据



我的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.

注意,那很粗糙。不确定它是否能完美工作。但这应该会给你一个想法。

最新更新