登录必需的修饰符未重定向到登录URL | Django的

时间:2020-06-01 13:43:10

标签: django django-forms django-views django-templates

@login_required装饰器无法将我重定向到登录页面

当我单击添加到购物车按钮时,它不会将我重定向到登录页面。它只是什么都不做。我在另一个函数中尝试了登录所需的装饰器。像主视图动作一样。当我尝试访问主页时,它直接将我重定向到登录页面。但是在combo_add_to_cart中似乎无效。但是我在终端中发现了一些东西。我已经看到,当我单击“添加到购物车”按钮时,它首先发送一个post的{​​{1}}请求,然后它发送一个"POST /carts/cart/combo/add-to-cart/ "的请求get

"GET /accounts/login/?next=/carts/cart/combo/add-to-cart/"

accounts views.py

class Login(FormView): form_class = LoginForm success_url = '/' template_name = 'accounts/login.html' def form_valid(self, form): request = self.request next_ = request.GET.get('next') next_post = request.POST.get('next') redirect_path = next_ or next_post or None email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) if is_safe_url(redirect_path, request.get_host()): return redirect(redirect_path) else: return redirect("/") return super(Login, self).form_invalid(form)

cart views.py
@login_required(login_url='/accounts/login/')
def combo_add_to_cart(request):    
    combo_id = request.POST.get('combo_id')
    if combo_id is not None:
        try:
            combo_obj = Combo.objects.get(id=combo_id)
        except Combo.DoesNotExist:
            return("carts:cart")

        combo = combo_obj

        cart_item, created = ComboCartItem.objects.get_or_create(
            combo=combo,
            user=request.user,
            ordered=False
        )

        cart_obj, new_obj = Cart.objects.new_or_get(request)

        if cart_obj.combo_item.filter(combo__id=combo.id).exists():
            cart_item.quantity += 1
            cart_item.save()
            print("Cart Item Updated")
            added = False
            updated = True
            # return redirect("carts:cart")
        else:
            cart_obj.combo_item.add(cart_item)
            print("Combo Added")
            added = True
            updated = False
            # return redirect("carts:cart")

        # print(combo_id)
        cartCount = cart_obj.get_cartItems()
        print(cartCount)
        if request.is_ajax():
            print("Ajax Request")
            json_data = {
            "added": added,
            # "not_added": not added,
            "updated": updated,
            # "not_updated": not updated
            "ItemCount": cartCount
            }   
            return JsonResponse(json_data, status=200)
            # return JsonResponse("message: Error", status_code=400)

    return redirect("carts:cart")

class ComboList(ListView): template_name = 'products/list.html' def get_context_data(self, *args, **kwargs): context = super(ComboList, self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) context['cart'] = cart_obj return context def get_queryset(self, *args, **kwargs): request = self.request combo = Combo.objects.all() return combo

combo-update.html

<form method="POST" action="{% url 'carts:combo_add_to_cart' %}" data-endpoint="{% url 'carts:combo_add_to_cart' %}" class="form add-ajax"> {% csrf_token %} <input type="hidden" name="combo_id" value="{{ combo.id }}"> <span class="submit-span"> <button type="submit" class="btn btn-success">Add to Cart</button> </span> </form>

list.html

{% extends 'base.html' %} {% block content %} <div class="container"> <h1>Combos</h1> <hr> {% for obj in object_list %} <b style="font-size: 1.5em;">{{ obj.title }} | Regular Rs.{{ obj.combo_regular_price }} | Sale Rs.{{ obj.combo_sale_price }}</b> {% include "products/snippets/combo-update.html" with combo=obj %} <br> {% endfor %} </div> {% endblock %}

base.js

var comboForm = $(".add-ajax") comboForm.submit(function(event){ event.preventDefault(); var thisForm = $(this) var actionEndpoint = thisForm.attr("data-endpoint"); var httpMethod = thisForm.attr("method"); var formData = thisForm.serialize(); $.ajax({ url: actionEndpoint, method: httpMethod, data: formData, success: function(data){ var submitSpan = thisForm.find(".submit-span") if(data.added){ submitSpan.html('<button type="submit" class="btn btn-success">Add More?</button>') swal({ title: "", text: "Added to cart!", icon: "success", button: "Okay", }) }else{ if(data.updated){ submitSpan.html('<button type="submit" class="btn btn-success">Add More?</button>') }else{ submitSpan.html('<button type="submit" class="btn btn-success">Add to Cart</button>') } } var cartCount = $(".cart-count") cartCount.text(data.ItemCount) console.log(data.ItemCount) if(window.location.href.indexOf('cart') != -1){ refreshCart() } }, error: function(errorData){ swal({ title: "Opps!", text: "An error occured!", icon: "error", button: "Okay", }) console.log("No API") console.log("error", errorData) } }) })

Traceback

2 个答案:

答案 0 :(得分:0)

这是因为我写的JavaScript!

我添加的cart views.py文件中的文件

def combo_add_to_cart(request):    
    combo_id = request.POST.get('combo_id')
    if not request.user.is_authenticated:
        if request.is_ajax():
            print("Ajax Request")
            json_data = {
            "noUser": True,
            }   
            return JsonResponse(json_data, status=200)
    else:        
        if combo_id is not None:
            try:
                combo_obj = Combo.objects.get(id=combo_id)

base.js的ajax调用中,我添加了一个条件

        if(data.noUser){
          swal({
            title: "Opps! You are not logged in",
            text: "Redirecting......",
            button: false,
          })
          setTimeout(function(){
            window.location.href='/accounts/login/'
          }, 1000)
        }else{
          if(data.added){
            submitSpan.html('<button type="submit" class="btn btn-success">Add More?</button>')
            swal({
            title: "",
            text: "Added to cart!",
            icon: "success",
            button: "Okay",
          })
          }else{
            if(data.updated){
              submitSpan.html('<button type="submit" class="btn btn-success">Add More?</button>')
            }else{
              submitSpan.html('<button type="submit" class="btn btn-success">Add to Cart</button>')
            }
          }
        }

因此,即使没有login_required装饰器,它也可以正常工作。

答案 1 :(得分:0)

甚至不需要js部分。答案很简单

我刚刚将@login_required(login_url='/accounts/login/')替换为@login_required(login_url="accounts:login")

我实际上不知道为什么URL正确映射后为什么不起作用。现在,我将其更改为使用namespaceurl名称,并且可以使用。