python - 如何防止使用装饰器在views.py 中处理表单时出现重复代码?

标签 python django django-forms python-decorators

上下文

我正在 python View 中处理表单。基本的东西。

def index(request):

    # Handle form.
    if request.method == 'POST':
        form = CustomForm(request.POST)
        if form.is_valid():
            # Do stuff
            return HttpResponseRedirect('/thankyou/')
    else:
        form = CustomForm()

    # Render.
    context = RequestContext(request, {
            'form':form,
        })
    return render_to_response('app/index.html', context)

此表单显示在多个页面上,并且我最终在views.py 的多个函数中重复了表单处理代码,从而呈现了不同的模板。 (但是,表单的模板代码位于基本模板中)

这很愚蠢,所以我尝试寻找防止代码重复的方法。我喜欢 this 中建议使用 python 装饰器堆栈溢出问题。我还找到了 python 装饰器的精彩解释 here .

问题

我在尝试编写装饰器时遇到了麻烦。我需要在第一个 if 语句之后返回一个表单,然后执行另一个 if 语句。但是在 python 函数中,return 函数执行后没有任何代码...这是否需要类似嵌套装饰器之类的东西...?

建议?欢迎非装饰者提出建议。

最佳答案

这不是您主要问题的答案,但此信息可能对您或某人有帮助。

关于装饰器的建议问题已经很老了。从1.3版本django开始有class based views - 我想这就是你正在寻找的。通过对 View 进行子类化,您可以减少代码的重复(来自 django docs 的代码仅作为示例):

# Base view
class MyFormView(View):
    form_class = MyForm
    initial = {'key': 'value'}
    template_name = 'form_template.html'

    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        if form.is_valid():
            # <process form cleaned data>
            return HttpResponseRedirect('/success/')

        return render(request, self.template_name, {'form': form})

现在您可以基于 MyFormView View 创建另一个 View 类。表单处理代码保持不变,但您当然可以更改它:

class AnotherView(MyFormView):
    form_class = AnotherForm
    initial = {'key1': 'value1'}
    template_name = 'form1_template.html'

    # you dont need to redefine post here if code stays same,
    # post from base class will be used

关于python - 如何防止使用装饰器在views.py 中处理表单时出现重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21812105/

相关文章:

python - 转换时间字符串并将其插入时间字段 django 的有效方法

Django 验证错误

python - Django 的两个自引用外键

python - 如何将文件文件夹移动到可变命名的文件夹

django - Django 的 render_to_response 是否缓存未渲染的模板或每次都从磁盘加载?

python - 带有 smtp.gmail SMTPAuthenticationError 534 的 Django 电子邮件需要特定于应用程序的密码

python - django 创建后将用户重定向到帖子

django - 自定义标签,例如使用 django-filter

python - 如何动态调整 Bokeh 图大小

python - 从变量名列表构建函数签名