Creating a Login Page in Django

In this tutorial we are going to build a simple login using Django Framework. Above photo is exactly how our app will look like when completed, so let’s get started.

Note: The codes in this tuturial was developed using Django v1.10.6, it may not work with older versions.

Create the base template mymodule/templates/mymodule/base.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html lang="en">
<head>
    <title>MyDjangoApp</title>
   
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
   
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body class="override">
    <nav class="navbar navbar-inverse" role="navigation">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="/mymodule/">MyDjangoApp</a>
            </div>
           
            <div id="navbar" class="collapse navbar-collapse">
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="/mymodule/login">Login</a></li>
                </ul>
            </div>
        </div>
    </nav>
   
    <div class="container">
        <div class="row">
            {% block content %}{% endblock %}
        </div>
    </div>
   
    <footer>
        <div class="container">
            <div class="row well ml-t">
                <div class="col-lg-8 col-md-8">    
                    <h4>Developed by: <a href="https://carlofontanos.com" target="_blank">Carl Victor C. Fontanos</a></h4>
                </div>
                <div class="col-lg-4 col-md-4">
                    <p class="m-t">Copyright &copy <a href="https://carlofontanos.com" target="_blank">www.carlofontanos.com</a> 2017</p>
                    <p>All Rights Reserved.</p>
                </div>
            </div>
        </div>
    </footer>
</body>
</html>

Then create the login template: mymodule/templates/mymodule/login.html and include the code bellow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
{% extends "mymodule/base.html" %}

{% block content %}
    <div class="container">
        <form action="{% url 'mymodule:user_login' %}" method="post">
            {% csrf_token %}
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Login</div>
                    <div class="panel-body">
                        {% if error_message %}
                            <p class="bg-danger p-d ml-b">{{ error_message }}</p>
                        {% endif %}
                        <div class="form-group clearfix">
                            <label for="username" class="col-md-4 control-label text-right">Username:</label>
                            <div class="col-md-6">
                                <input name="username" value="" type="text" class="form-control" />
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="password" class="col-md-4 control-label text-right">Password:</label>
                            <div class="col-md-6">
                                <input name="password" type="password" class="form-control" />
                            </div>
                        </div>
                        <div class="col-md-6 col-md-offset-4">
                            <input name="login" type="submit" value="Login" class="btn btn-success" /> &nbsp;
                            <a href="/mymodule/register">or Register</a>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
{% endblock %}

Create the controller that will handle both GET and POST methods to the login form. The code bellow goes to your mymodule/views.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from django.contrib.auth import authenticate, login
from django.shortcuts import render

def user_login(request):
    if request.method == 'POST':
        # Process the request if posted data are available
        username = request.POST['username']
        password = request.POST['password']
        # Check username and password combination if correct
        user = authenticate(username=username, password=password)
        if user is not None:
            # Save session as cookie to login the user
            login(request, user)
            # Success, now let's login the user.
            return render(request, 'ecommerce/user/account.html')
        else:
            # Incorrect credentials, let's throw an error to the screen.
            return render(request, 'ecommerce/user/login.html', {'error_message': 'Incorrect username and / or password.'})
    else:
        # No post data availabe, let's just show the page to the user.
        return render(request, 'ecommerce/user/login.html')

Finally, register the view in our mymodule/urls.py:

1
2
3
4
5
6
7
from django.conf.urls import url
from . import views

app_name = 'mymodule' # So we can use it like: {% url 'mymodule:user_login' %} on our template.
urlpatterns = [
    url(r'^login/$', views.user_login, name='user_login')
]


Do you need help with a project? or have a new project in mind that you need help with?

Contact Me