python - 如何在 Django 中使用装饰器保存发布数据

标签 python django forms decorator

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

相关文章:

python - “pip”不被识别为内部或外部命令、可操作程序或批处理文件

django - 在开发期间在本地托管管理媒体

html - 从另一个域预填充 iframe 表单

javascript - 在不知道 ID 的情况下将焦点设置在动态创建的输入字段上

python - 拆分列表中的每个项目

python - 检查变量是否在字典中并且变量是否等于字典键的更好方法是什么?

python - Django 1.9 URLField 删除必要的 http ://prefix

Django-如何从模型中选择特定的列?

ModelFormset 的 Django 删除按钮操作

javascript - 为什么我的表单没有提交我想要的内容?