【问题标题】:Decorator is not working on a view function in Django装饰器不在 Django 中处理视图函数
【发布时间】:2018-12-12 07:10:20
【问题描述】:

我有两个模型类,分别是 ShopkeeperCustomer,它们具有来自 User Model 的 onetoone 键。现在我有一个观点

@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.

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

【问题讨论】:

  • 能否请您修复代码中的缩进?
  • @EugenePrimako 缩进现已修复。

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


【解决方案1】:

我猜你的 lambda 函数

lambda u: u.is_authenticated and is_customer

应该看起来像

lambda u: u.is_authenticated and is_customer(u)

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2016-09-27
    • 2012-08-02
    • 1970-01-01
    • 2016-12-14
    • 2018-10-18
    • 2019-10-21
    相关资源
    最近更新 更多