問題: 如果用戶已登錄,我想顯示問候用戶,否則顯示表單,當提交有效資料時,登錄用戶并顯示問候訊息。
我正在嘗試在提交時傳遞資料并更新用戶狀態以登錄。我嘗試過使用和不使用ajax,但兩種方式我都無法找到解決方案。你能幫我為什么它失敗了嗎?我該如何解決這個問題?
HTML 表單:
{% if user.is_authenticated %}
<h5 class="title billing-title ls-10 pt-1 pb-3 mb-0">
Welcome {{ user.username }}!
</h5>
{% else%}
<div class="login-toggle">
Returning customer? <a href="#"
class="show-login font-weight-bold text-uppercase text-dark">Login</a>
</div>
<form name="ajaxLogin" method="POST" action="{% url 'ecommerce:ajaxlogin' %}">
{% csrf_token %}
<p>If you have shopped with us before, please enter your details below.
If you are a new customer, please proceed to the Billing section.</p>
<div >
<div >
<div >
<label>Username or email *</label>
<input type="text" name="username" id="id_email"
required>
</div>
</div>
<div >
<div >
<label>Password *</label>
<input type="password" name="password" id="id_password"
required>
</div>
</div>
</div>
<div >
<input type="checkbox" id="remember" name="remember">
<label for="remember" >Remember me</label>
<a href="#" >Lost your password?</a>
</div>
<button type="submit" >Login</button>
</form>
{% endif%}
視圖.py:
def ajaxlogin(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(user=username, password=password)
if User.is_active and not None :
login(request)
else:
pass
return render('./ecommerce/checkout.html')
阿賈克斯:
$(document).ready(function(){
$('.login-content').on('submit', function(event){
event.preventDefault();
var action_url = $(this).attr('action')
$.ajax({
url: action_url,
type:"POST",
data: $('.login-content').serialize(),
headers: { "X-CSRFToken": $.cookie("csrftoken") },
success: function (data) {
console.log("login Successful");
},
});
});
});
uj5u.com熱心網友回復:
Djangoauthenticate采用關鍵字引數username,password默認情況下使用request可選引數。
在您作為引數views.py傳遞user的 authenticate 中,將其更改為username. 如果用戶處于非活動狀態,則默認authentication回傳 None ,因此您不必檢查is_active是否使用默認身份驗證。
改變你views.py的
def ajaxlogin(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None :
login(request, user)
else:
pass
return render('./ecommerce/checkout.html')
也可以通過省略鍵設定contentType為默認值或將其保留為默認值。application/x-www-form-urlencodedcontentType
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/414247.html
標籤:
下一篇:Ajax沒有發出警報
