Creating a Registration Page in Django

In this tutorial we are going to build a simple registrtaion 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/register">Register</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="http://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="http://carlofontanos.com" target="_blank">www.carlofontanos.com</a> 2017</p>
                    <p>All Rights Reserved.</p>
                </div>
            </div>
        </div>
    </footer>
</body>
</html>

Then create the registration template: mymodule/templates/mymodule/register.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
{% extends "mymodule/base.html" %}

{% block content %}
    <div class="container">
        <form action="{% url 'mymodule:user_register' %}" method="post">
            {% csrf_token %}
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Register</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="{{ form.username.id_for_label }}" class="col-md-4 control-label text-right">Username<span class="text-red">*</span>:</label>
                            <div class="col-md-6">
                                {{ form.username }}
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="{{ form.email.id_for_label }}" class="col-md-4 control-label text-right">Email<span class="text-red">*</span>:</label>
                            <div class="col-md-6">
                                {{ form.email }}
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="{{ form.password.id_for_label }}" class="col-md-4 control-label text-right">Password<span class="text-red">*</span>:</label>
                            <div class="col-md-6">
                                {{ form.password }}
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="{{ form.password_repeat.id_for_label }}" class="col-md-4 control-label text-right">Confirm password:</label>
                            <div class="col-md-6">
                                {{ form.password_repeat }}
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="{{ form.first_name.id_for_label }}" class="col-md-4 control-label text-right">First Name:</label>
                            <div class="col-md-6">
                                {{ form.first_name }}
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="{{ form.last_name.id_for_label }}" class="col-md-4 control-label text-right">Last Name:</label>
                            <div class="col-md-6">
                                {{ form.last_name }}
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <label for="{{ form.phone_number.id_for_label }}" class="col-md-4 control-label text-right">Phone Number:</label>
                            <div class="col-md-6">
                                {{ form.phone_number }}
                            </div>
                        </div>
                        <div class="col-md-6 col-md-offset-4">
                            <input type="submit" value="Register" class="btn btn-success">
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
{% endblock %}

Create a new file forms.py and place it under mymodule/ directory. In it, include the following field definitions:

1
2
3
4
5
6
7
8
9
10
from django import forms

class RegisterForm(forms.Form):
    username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}))
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))
    password_repeat = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))
    first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    phone_number = forms.CharField(widget=forms.NumberInput(attrs={'class':'form-control'}), required=False)

Create the controller that will handle both GET and POST methods to the registration 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
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
from django.contrib.auth.models import User
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import RegisterForm

def user_register(request):
    # if this is a POST request we need to process the form data
    template = 'mymodule/register.html'
   
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = RegisterForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            if User.objects.filter(username=form.cleaned_data['username']).exists():
                return render(request, template, {
                    'form': form,
                    'error_message': 'Username already exists.'
                })
            elif User.objects.filter(email=form.cleaned_data['email']).exists():
                return render(request, template, {
                    'form': form,
                    'error_message': 'Email already exists.'
                })
            elif form.cleaned_data['password'] != form.cleaned_data['password_repeat']:
                return render(request, template, {
                    'form': form,
                    'error_message': 'Passwords do not match.'
                })
            else:
                # Create the user:
                user = User.objects.create_user(
                    form.cleaned_data['username'],
                    form.cleaned_data['email'],
                    form.cleaned_data['password']
                )
                user.first_name = form.cleaned_data['first_name']
                user.last_name = form.cleaned_data['last_name']
                user.phone_number = form.cleaned_data['phone_number']
                user.save()
               
                # Login the user
                login(request, user)
               
                # redirect to accounts page:
                return HttpResponseRedirect('/mymodule/account')

   # No post data availabe, let's just show the page.
    else:
        form = RegisterForm()

    return render(request, template, {'form': form})

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_register' %} on our template.
urlpatterns = [
    url(r'^register/$', views.user_register, name='user_register')
]