简体   繁体   English

Django 重定向在基于 class 的视图中不起作用

[英]Django redirect doesn't work in class based view

I have a class based view which i am checking some conditions and redirecting to another page, i see the GET request to that page in the terminal and it returns 200, but it doesn't redirect to the page:我有一个基于 class 的视图,我正在检查一些条件并重定向到另一个页面,我在终端中看到对该页面的 GET 请求,它返回 200,但它没有重定向到该页面:

class CheckoutFinalView(CartOrderMixin, View):
def post(self, request, *args, **kwargs):
    cart_obj, new_obj = Cart.objects.new_or_get(request)
    order_obj = None
    if cart_obj.items.count() == 0:
        return redirect("carts:cart")
    billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request)
    has_card = False
    if billing_profile is not None:
        order_obj, order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj)
        order_obj.save()
        has_card = billing_profile.has_card
    is_prepared = order_obj.check_done()
    user = User.objects.get(id=request.user.id)
    if is_prepared:
        print(is_prepared)
        did_charge, crg_msg = billing_profile.charge(order_obj)
        print(did_charge)
        if did_charge:
            order_obj.mark_paid()  # sort a signal for us
            request.session['cart_items'] = 0
            del request.session['cart_id']
            del request.session["order_id"]
            if not billing_profile.user:
                print("not billing profile user: ", billing_profile.user)
                billing_profile.set_cards_inactive()
            return redirect("checkout_final")
        else:
            print(crg_msg)
            return redirect("checkout_final")

def get(self, request, *args, **kwargs):
    return redirect("carts:success")

I tried return HttpResponseRedirect(reverse('carts:success')) , too.我也试过return HttpResponseRedirect(reverse('carts:success')) But it doesn't work, too.但它也不起作用。

I see the GET request to that page in the terminal and it returns 200.我在终端中看到对该页面的 GET 请求,它返回 200。

That is perfectly normal, you only specify to redirect for a POST request, since you override def post .这是完全正常的,您只指定重定向 POST 请求,因为您覆盖了def post

You thus should implement it for a GET request with:因此,您应该为 GET 请求实现它:

class CheckoutFinalView(CartOrderMixin, View):

    def get(self, request, *args, **kwargs):
        return redirect('carts:success')

    def post(self, request, *args, **kwargs):
       return redirect('carts:success')

Note that this view however does not do much, it simply redirects.请注意,这个视图并没有太多,它只是重定向。 In that case, you can make use of a RedirectView :在这种情况下,您可以使用RedirectView

from django.views.generic import RedirectView
from django.urls import reverse_lazy

class CheckoutFinalView(RedirectView):
    url = reverse_lazy('carts:success')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM