为什么不能在装饰器内访问request属性? [英] Why can't I access request attribute inside a decorator?

查看:44
本文介绍了为什么不能在装饰器内访问request属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当提交表单时,我都会在Django装饰器( @save_post_request )中使用 request.POST.get('...')我遇到同样的错误

I'm using request.POST.get('...') inside my Django decorator (@save_post_request) whenever my form is submitted, on each tentative I get this same error

(带有 request.< anything> 的错误):

(error with request.<anything>):

AttributeError:"collectData"对象没有属性"POST"

AttributeError: 'collectData' object has no attribute 'POST'

我的装饰器在 CollectData classBasedView内的 post()函数顶部被调用.

My decorator is called on top of a post() function inside CollectData classBasedView.

#views.py
class collectData(View):
    template_name = 'collect_data.html'
    context = {...}

    def get(self, request, *args, **kwargs):
        ...
        return render(request, self.template_name, self.context)


    @save_post_request
    def post(self, request, *args, **kwargs):
        ...
        return redirect(reverse('collectData'))


#decorators.py
def save_post_request(function):
    def wrap(request, *args, **kwargs):

        title = request.POST.get('title') # <---
        ...
        return function(request, *args, **kwargs)
    wrap.__doc__ = function.__doc__
    wrap.__name__ = function.__name__
    return wrap

我不确定是否可以使用 classBasedViews 这样调用装饰器,但是我认为应该是正确的,我的错误是什么?

I'm not sure if a decorator can be called like so using classBasedViews, but I think it should be right, what is my mistake?

推荐答案

内部函数的第一个参数应为 self :

First argument of inner function should be self:

def save_post_request(function):
    def wrap(self, request, *args, **kwargs):

        title = request.POST.get('title') # <---
        ...
        return function(self, request, *args, **kwargs)
    wrap.__doc__ = function.__doc__
    wrap.__name__ = function.__name__
    return wrap

这篇关于为什么不能在装饰器内访问request属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆