Answer the question
In order to leave comments, you need to log in
Why doesn't login with Django login() work?
In short, I am writing an authentication system in django, using popups and ajax requests.
The structure is something like this:
The page has a bootstrap popup (#LoginModal), it contains a form (#login-form).
On submit, an ajax request is made to the login view (url : "/login/" --> login_user).
This view (login_user) returns the result and then js displays error information or redirects the user (if the login is successful).
Those. #LoginModal --> #login-form --> ajax --> /login/ --> login_user --> ajax-data --> reload or show errors
Here is my js + ajax code:
alert('{{user.is_authenticated}}');
$('#login-form').on('submit', function(event){
event.preventDefault();
$('#login-form .alert-success').remove();
$('#login-form #login_btn').addClass('disabled');
$('#login-form #login_btn').prop('disabled', true);
$.ajax({
url : "/login/",
type : "get",
data : $('#login-form').serialize()
}).done(function(data) {
if (data == "OK") {
$('#login-form .alert-danger').remove();
$('#login-form').prepend('<div class="alert alert-success" role="alert"><strong>Успешно!</strong><br>Подождите секундочку...</div>');
document.location.href = document.location.href.replace('#open_login', '');
} else {
if (!$('#login-form .alert-danger').length) {
$('#login-form').prepend('<div class="alert alert-danger" role="alert"><strong>Ошибка!</strong><br>Введите правильное имя пользователя и пароль.</div>');
}
$('#login-form #login_btn').removeClass('disabled');
$('#login-form #login_btn').prop('disabled', false);
}
});
});
def login_user(request):
username = request.GET.get('username')
password = request.GET.get('password')
auth_form = AuthenticationForm(request, {'username': username, 'password': password})
if auth_form.is_valid():
if request.GET.get('remember') == "true":
pass
else:
request.session.set_expiry(0)
user = authenticate(username=username, password=password)
login(request, user)
print(user.is_authenticated)
ret = 'OK'
else:
ret = 'field_errors'
return HttpResponse(ret)
login(request, user)or not executed, or performed somehow wrong.
Answer the question
In order to leave comments, you need to log in
This worked for me in views.py
from django.contrib import auth
def login(request):
...
auth.login(request, user)
....
Your code helped me, I made an entrance through the bootstrap modal window.
ajax
$('#login-form').on('submit', function(event){
event.preventDefault();
var csrf_token = $('#login-form [name="csrfmiddlewaretoken"]').val();
var idu = $('#idu').val();
var idp = $('#idp').val();
$.ajax({
url : "/login/",
type : "POST",
data : { csrfmiddlewaretoken: csrf_token, lgn: idu, pswd: idp},
traditional: true
}).done(function(response) {
if (response == "OK") {
$('#login-form .alert-danger').remove();
$('#login-form').prepend('<div class="alert alert-success" role="alert"><strong>Успешно!</strong><br>Подождите секундочку...</div>');
document.location.href = document.location.href.replace('#open_login', '');
} else {
if (!$('#login-form .alert-danger').length) {
$('#login-form').prepend('<div class="alert alert-danger" role="alert"><strong>Ошибка!</strong><br>Введите правильное имя пользователя и пароль.</div>');
}
}
});
});
def auth_view(request):
username = request.POST.get('lgn', '')
password = request.POST.get('pswd', '')
user = auth.authenticate(username=username, password=password)
if user is not None:
if user.is_active:
auth.login(request, user)
return HttpResponse('OK')
else :
return HttpResponse("False")
<div class="modal fade" id="LogModal" tabindex="-1" role="dialog" aria-labelledby="LogModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="LogModalLabel">Вход в учетную запись</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="login-form" method="post" action="">{% csrf_token %}
<div class="modal-body">
<label for="id_username">Имя пользователя:</label>
<input class="form-control" type="text" name="username" maxlength="30" id="idu"/>
<label for="id_password">Пароль:</label>
<input class="form-control" type="password" name="password" id="idp"/>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Войти</button>
</div>
</form>
</div>
</div>
</div>
1) The standard Django mechanism does not pull data without a page refresh.
2) I wrote a scheme when I saved the current user page into a variable, upon login (if successful, I sent the response to json) - I did a forced refresh of the page to the page that I had previously saved.
3) After that, I received an authorization user and all the fields I needed.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question