Problem: If user is loggedin, I want to show greet user else show the form and when the valid data is submitted, log in the user and show greet message.
I am trying to pass the data on submit and update the user status to login. I tried with and without ajax but with both ways I could not figure out solution. Could you please help me why its failing? And how I can solve this?
HTML Form:
{% if user.is_authenticated %}
<h5 >
Welcome {{ user.username }}!
</h5>
{% else%}
<div >
Returning customer? <a href="#"
>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%}
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(user=username, password=password)
if User.is_active and not None :
login(request)
else:
pass
return render('./ecommerce/checkout.html')
AJAX:
$(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");
},
});
});
});
CodePudding user response:
Django authenticate takes keyword arguments username and password for the default case with request as optional parameter.
In your views.py you pass user as parameter in authenticate change it to username.
The default authentication returns None if user is in-active so you don't have to check for is_active if you are using default authentication.
Change your views.py as
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')
Also set contentType as application/x-www-form-urlencoded or leave it at the default by omitting the contentType key.
