Как войти в django с помощью формы входа? С помощью Ajax или без него

Проблема: Если пользователь вошел в систему, я хочу показать приветствие пользователю, в противном случае показать форму и когда будут отправлены правильные данные, войти в систему и показать приветствие.

Я пытаюсь передать данные при отправке и обновить статус пользователя до login. Я пробовал с 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 class="login-content" 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 class="row">
                <div class="col-xs-6">
                    <div class="form-group">
                        <label>Username or email *</label>
                        <input type="text" class="form-control form-control-md" name="username" id="id_email"
                            required>
                    </div>
                </div>
                <div class="col-xs-6">
                    <div class="form-group">
                        <label>Password *</label>
                        <input type="password" class="form-control form-control-md" name="password" id="id_password"
                            required>
                    </div>
                </div>
            </div>
            <div class="form-group checkbox">
                <input type="checkbox" class="custom-checkbox" id="remember" name="remember">
                <label for="remember" class="mb-0 lh-2">Remember me</label>
                <a href="#" class="ml-3">Lost your password?</a>
            </div>
            <button class="btn btn-rounded btn-login" 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");
            
        },
        
        
    });
  });
  });

Django authenticate принимает аргументы ключевых слов 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-urlencoded или оставьте по умолчанию, опустив клавишу contentType.

Вернуться на верх