1

I am trying to build a login form in Django, and when the user hits login, I wish to send the username and password to check which type of user it is as my system has 3 different kinds of users.

Following is the code:

views.py

from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User



def index(request):
    return render(request, "login.html")


@csrf_protect
def auth_login(request):
    print("Hello !")
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    group = User.objects.get(username=username).groups.values()[0]['name']
    print(username)
    print(user)
    print(password)
    return render(request, "add_form.html")


@csrf_protect
def logout(request):
    logout(request)

login.html - (I have a simple bootstrap login form)

<!DOCTYPE html>
<html lang="en">
<head>
    {% load staticfiles %}
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <title>Login</title>

<style>
        html,
body {
  height: 100%;
}

body {
  display: -ms-flexbox;
  display: -webkit-box;
  display: flex;
  -ms-flex-align: center;
  -ms-flex-pack: center;
  -webkit-box-align: center;
  align-items: center;
  -webkit-box-pack: center;
  justify-content: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: white;
}

.form-signin {
  width: 100%;
  max-width: 330px;
  padding: 15px;
  margin: 0 auto;
}
.form-signin .checkbox {
  font-weight: 400;
}
.form-signin .form-control {
  position: relative;
  box-sizing: border-box;
  height: auto;
  padding: 10px;
  font-size: 16px;
}
.form-signin .form-control:focus {
  z-index: 2;
}
.form-signin input[type="text"] {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}
    </style>
</head>
<body class="text-center">
   <form class="form-signin" id="login-form">{% csrf_token %}
      <img class="mb-4" src="{% static "download.png" %}" alt="Logo"  align="center" height="112" width="112">
      <h1 class="h3 mb-4 font-weight-normal">Please sign in</h1>
      <label for="inputEmail" class="sr-only">Username</label>
      <input type="text" id="uname" class="form-control" placeholder="Username" required autofocus>
      <label for="inputPassword" class="sr-only">Password</label>
      <input type="password" id="passwd" class="form-control" placeholder="Password" required>
      <div class="checkbox mb-4">
      </div>
      <button class="btn btn-lg btn-primary btn-block" id="loginbutton" type="submit">Sign in</button>

      <p class="mt-3 mb-5 text-muted">Planning Tool</p>
    </form>

<script type="text/javascript">
    $(document).ready(function () {

        $("#login-form").on('submit', function (e) {
            e.preventDefault();
            login();
        });

    function login(){
        alert($("#uname").val())
          $.ajax({
                url: {% url 'auth:Login' %},
                method : "POST",
                data : {
                    "username" : $("#uname").val(),
                    "password" : $("#passwd").val(),
                    'csrfmiddlewaretoken' :  "{{ csrf_token }}"
                },
              success : function (data) {
                  alert("successful")
              },
              failure : function (data) {
                  alert("did not pass")
              }
            });
    }

    });

</script>
</body>
</html>

urls.py

from django.conf.urls import url
from django.urls import path
from . import views
from django.conf import settings

app_name = 'auth'

urlpatterns = [
    url(r'^', views.index, name='Home'),
    path('auth-login/', views.auth_login, name='Login'),
    path('auth-logout/', views.logout, name='Logout'),
]

---- Django console ----

(venv) C:\Users\Krushika.Tapedia\PycharmProjects\schedulingtool>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
November 26, 2019 - 11:50:45
Django version 2.2.4, using settings 'schedulingtool.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[26/Nov/2019 11:50:48] "GET / HTTP/1.1" 200 3825
[26/Nov/2019 11:50:48] "GET /static/download.png HTTP/1.1" 304 0
[26/Nov/2019 11:51:00] "POST /auth-login/ HTTP/1.1" 200 3825


I have referred different answers on the forum, I have tried with this also click here

but it does not enter into the function and print the first statement on the terminal. I am unable to debug this and not able to understand the problem here.

Thanks in advance.

EDIT : Pasting the whole HTML File for you to try and also the Django console

17
  • Your url in the js script uses auth:Login while the django uses the path auth-login. Also you may use the developer console for debugging js. Commented Nov 26, 2019 at 15:55
  • On the developer console for js when I use {% url 'auth:Login' %} (auth is the app name and Login is the name of the path) it renders as '/auth-login/' Commented Nov 26, 2019 at 16:06
  • I'm sorry. I didn't see app_name. Do you see any errors in the browser? Commented Nov 26, 2019 at 16:17
  • No, sadly, I see no errors :( Commented Nov 26, 2019 at 16:18
  • Does the post request get received at the server? Commented Nov 26, 2019 at 16:37

1 Answer 1

3

You probably need to change this inside the file urls.py:

url(r'^', views.index, name='Home'),

to

path(r'^', views.index, name='Home'),

From the official documentation regarding the url function

This function is an alias to django.urls.re_path(). It’s likely to be deprecated in a future release.

Your url function matches any string and hence all requests are sent to the index function inside your views.py file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.