装饰器不在 Django 中的视图函数上工作

Decorator is not working on a view function in Django

我有两个模型 class 作为 ShopkeeperCustomer,它们具有来自 User 模型的一对一密钥。现在我的观点是

@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 的身份登录,并使用以下 url:

调用此视图
path('products/<pk>/addToCart/', views.add_to_cart, name='add_to_cart'),

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

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

你能帮我找出这里的错误吗?

我猜你的 lambda 函数

lambda u: u.is_authenticated and is_customer

应该是

lambda u: u.is_authenticated and is_customer(u)

此拼写错误可能允许未经身份验证的用户进入您的视图,而不是将他们重定向到登录页面。

如果它不能解决问题 - 请给我们整个追溯,而不仅仅是异常文本。