Django:从函数重定向不起作用

时间:2018-09-04 08:19:17

标签: python django

任何人都可以告诉我,为什么我的重定向不起作用?我可以在终端中看到“ SHOULD REDIRECT 2”,但是以某种方式重定向从未发生。有重定向导入。

helpers.py

def get_reserved_items_or_redirect(request):
    session_order_reference = request.session.get('order_reference')
    if request.session.get('order_reference'):
        reserved_items = ReservedItem.objects.filter(
            order_reference=session_order_reference
        )
        print("session_order_reference: ", session_order_reference)
        if not reserved_items:
            print( "SHOULD REDIRECT 1")
            return redirect('website:index')
    else:
        print( "SHOULD REDIRECT 2")
        return redirect('website:index')

views.py

class CheckoutView(TemplateView):
    # To check make an order

    template_name = "checkout/checkout_new.html"

    # make it a decorator
    def dispatch(self, request, *args, **kwargs):
        get_reserved_items_or_redirect(request)
        return super().dispatch(request, *args, **kwargs)

1 个答案:

答案 0 :(得分:2)

在您的CheckoutView中,您仅呼叫get_reserved_items_or_redirect(request)。 要使其工作,只需重构您的dispatch方法以返回此方法的返回值即可。

def dispatch(self, request, *args, **kwargs):
    if some_value: # Check if you need to perform redirect
        return get_reserved_items_or_redirect(request)
    else: # If redirect is not required
        return super().dispatch(request, *args, **kwargs)