【Django】登錄后回到之前的頁面


在任意頁面點擊登錄,登錄成功后,跳轉到之前點擊登錄的那個頁面

1. 用戶在A.html頁面點擊登錄
2. 用戶到登錄頁面login.html
3. 用戶輸入信息登錄成功
4. 自動跳轉回到A.html

  1. 所有的登錄鏈接路徑:{% url 'login' %}?next={{ request.path }}

    <a href="{% url 'login' %}?next={{ request.path }}">登錄</a>
    <!-- request.path: 當前頁面的url -->
    

    GET路徑為:.../login/?next=當前url/

  2. login視圖函數獲取next的值:next=request.GET.get('next','/')
    在返回的login頁面的登錄表單中添加:<input type="hidden" name="next" value="{{ next }}">

  3. 將登錄表單的值包括$('input[name="next"]')的值提交到視圖函數,視圖函數獲取next值進行下一步跳轉。


/views.py

def login(request):
	if request.method == "POST":
		ret = {
			'status': None,
			'msg': '',
		}

		username = request.POST.get("username")
		password = request.POST.get("password")
		next = request.POST.get('next')

		if geetest_auth.geetest_auth(request):
			user = auth.authenticate(username=username, password=password)
			if user:
				auth.login(request, user)
				ret["msg"] = next
			else:
				ret["status"] = 1
				ret["msg"] = "用戶名或密碼錯誤!"

		return JsonResponse(ret)

	elif request.method == "GET":
		next = request.GET.get('next', '/')
		return render(request, "login.html", {'next': next})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM