G
G
gh0sty2019-09-18 13:11:25
JavaScript
gh0sty, 2019-09-18 13:11:25

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);
        }
    });
});


Here is my login_user view:
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)


And herein lies the problem.
Function
login(request, user)
or not executed, or performed somehow wrong.
With correct data, the alert in js always shows false;
And the data on the page says the same.
And print in the view says - true, everything is OK, bro! And the user correctly displays.
And I don’t remember exactly what I changed, but at some point this thing arose.

I'm new to django and need your help. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
Jason7Wane, 2019-09-20
@gh0sty

This worked for me in views.py
from django.contrib import auth
def login(request):
...
auth.login(request, user)
....

M
Maxim Gerasimov, 2019-10-02
@MaxGS

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>');
            }
            }
        });
    });

views.py
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")

urls.py template login.html
<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">&times;</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>

Calling a modal window:
Maybe someone from beginners will help, I have been looking for the information I need for a long time - there is no ready-made recipe, unfortunately.

S
Sergey Nizhny Novgorod, 2019-09-18
@Terras

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 question

Ask a Question

731 491 924 answers to any question