装饰器无法在Django中使用视图功能

时间:2018-07-03 22:30:31

标签: python django-models django-views python-decorators

我有两个模型类,分别是 Shopkeeper Customer ,它们具有 User Model 中的按键。现在我有一个看法

@require_customer()
def add_to_wishlist(request, pk):
    product = Product.objects.get(pk=pk)
    customer = Customer.objects.get(user=request.user)
    wl = WishListProduct(product=product, customer=customer)
    wl.save()
    return HttpResponse("Added to Wish List !")

装饰器如下:

def require_customer(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/'):
    def is_customer(u):
        return Customer.objects.filter(user=u).exists()
    actual_decorator = user_passes_test(lambda u: u.is_authenticated and is_customer, login_url=login_url,
    redirect_field_name=redirect_field_name)
    if function:
        return actual_decorator(function)
    else:
        return actual_decorator

现在,如果我以Shopkeeper身份登录并且使用以下网址调用此视图:

path('products/<pk>/addToCart/', views.add_to_cart, name='add_to_cart'),

它应该重定向到登录页面,但是却给我一个错误

OnlineShops.models.DoesNotExist: Customer matching query does not exist.

您能帮我在这里找到错误吗?

1 个答案:

答案 0 :(得分:1)

我猜你是lambda函数

lambda u: u.is_authenticated and is_customer

应该像

lambda u: u.is_authenticated and is_customer(u)

此错字可能会允许未经身份验证的用户进入您的视图,而不是将其重定向到“登录”页面。

如果仍不能解决问题,请提供完整的追溯信息,而不仅仅是异常文本。

相关问题