django登录用户,成功登录后用户停留在同一页面上

时间:2017-02-22 10:52:37

标签: django python-2.7 python-3.x django-templates django-views

我必须在django中实现Login,但登录可以在产品购买时,创建评论等时完成。 在这里,我在登录后重定向用户在索引页面上。 但我必须让用户留在他登录的(订单,评级)页面的同一页面上。

  

我怎么能这样做?

这是我实施的内容:

def login_view(request):
    if request.method=='POST':
        form=UserLoginForm(request.POST  or None)
        if form.is_valid():
            email = form.cleaned_data["email"]
            password = form.cleaned_data["password"]
            try:
                user = Customer.objects.get(email=email)
                if user.check_password(password) :
                    if user.is_active and user.is_customer:
                        if user.mobile_verified :
                            user = authenticate(username=user.email, password=password)
                            login(request, user)
                            if request.POST.get('card_data'):
                                for items in request.POST.get('card_data').split(","):
                                    cart = Cart(user=user, product_id=items)
                                    cart.save()
                                total_cart = user.card_user.count()
                            else:
                                total_cart = 0
                            messages.success(request, "Login successfully.")
                            responss =  redirect("Peru:home")
                            responss.delete_cookie('add_card_token')
                            return responss
                        else:
                            messages.success(request,"Mobile number is not verified")
                            return redirect("Peru:home")
                    else :
                        messages.info(request, "Your account may not be activated")
                        return redirect("Peru:home")
                else:
                    messages.error(request,"Email or Password does not match")
                    return redirect("Peru:home")
            except Exception as e:
                messages.error(request, "User may not exists !")
                return redirect("Peru:home")
        else:
            return redirect("Peru:home", forms=form)
    else:
        return redirect('Peru:home')

1 个答案:

答案 0 :(得分:1)

您需要在模板中传递下一个URL,并在登录视图中检查下一个URL。

在模板中:

<a href="{% url 'login' %}?next={{request.path}}">Login</a>

login视图中:

from django.utils.http import is_safe_url

def login(request):
    redirect_to = request.POST.get('next', request.GET.get('next', ''))
    # check form validity
    # authenticate user
    if redirect_to and is_safe_url(url=redirect_to, host=request.get_host()):
        return redirect(redirect_to)
    else:
        return redirect('index')