python - wrapper() 得到了一个意外的关键字参数 'id'

标签 python django-views

我有 wiev 函数:

@login_required
def index(request):

@login_required
def detail(request, id):

装饰器:

@decorator
def login_required(wiev_function, request, *args, **kwargs):
    print(args)
    print(kwargs)
    if not request.user.is_authenticated():
        return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
    return wiev_function(request, *args, **kwargs)

“index”功能正常,但“detail”功能出错:

TypeError: wrapper() got an unexpected keyword argument 'id'

附言id 参数在 url 模式中

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^new/(?P<id>\d+)/$', views.new, name = 'new'),

最佳答案

这不是你编写装饰器的方式。装饰器是返回另一个函数的函数;该内部函数必须执行一些逻辑并(可选)调用装饰函数。外部函数本身不接受传递给原始函数的参数;内部函数。

def login_required(view_function):
    def inner(request, *args, **kwargs):
        print(args)
        print(kwargs)
        if not request.user.is_authenticated():
            return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
        return view_function(request, *args, **kwargs)
    return inner

然而,所有这些似乎毫无意义,因为 Django 已经提供了一个 login_required decorator .

关于python - wrapper() 得到了一个意外的关键字参数 'id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48097400/

相关文章:

python - 在来自另一个程序的 python 3 字符串中,ü 是两个字符,即 u 和元音变音。为什么?

python - 在 Python 中检测装饰器

python - 覆盖 Django 中的模板

Django:forms.ChoiceField,覆盖表单 __init__

python - 如何让 django 输出星期几?都在 View 和模板中

python - pandas如何在不创建新列的情况下进行外连接

python - Pandas 键列表列和值列表列到字典列表列

python - 如何有条件地跳过pytest中 fixture 的实例化?

python - update_or_create 的 Django GenericRelation

django DeleteView - 如何传递用于 success_url 的参数?