Add User Registration to Python Django Web Application, Login, Logout

Add User Registration to Python Django Web Application, Login, Logout

This tutorial will cover in great detail steps, to add user registration to your Python Django web application. You will need a Django Project – to work with. If not, follow this Tutorial to get started with Django.

Also read: Django Website Tutorial, creating a django project from scratch

python django user authentication
python django user authentication

User Registration Process

A user registration process is a combination of registration form, web page and profile that request users to add account, profile information and data in an online web/mobile application. The aim is to collect individual identification and access data, to ensure the integrity of the users and the application.

User profiles provide the following benefits to application developers:

  • Ensure integrity of users, real users that are accessing your application and not bots or programmes
  • Allow app developers to customise data and information served to users – customisation can be geographically based (such as restaurants in a specific area) or user based (such as groups followed by specific users).
  • Track user interests on your application so you can better serve them appropriate data in future
  • If you are serving a paid service/app, you can track accounts using profile data

All of this requires a secure, reliable user registration process to be implemented. We are going to describe how to add user registration to Python Django Web Application.

Add User Registration to Python Django Web App

Step 1: Create a new Users App

Django works with projects and apps, by now you should have a Django project running – go ahead a create a new app and call it “users”.

python manage.py createapp users

Do not forget to register the new app in the settings.py file. Under installed apps, just add ‘users’ to the list.

The new folder structure, should look like this – if some files or folders are missing, create them:

users/
│
├── __init__.py 
|__ admin.py 
│__ apps.py
|__ forms.py 
|__ migrations/
|__ models.py
|__ templates/
│       ├── register.html
│       ├── login.html
│       └── logout.html
|__ tests.py
└── views.py 

Migrations/ and templates/ are folders while the rest are files. Inside the templates folder, please add register, login, logout html files. They can be empty for now.

Step 2: Create the user registration form

There are three main steps you need to cover to create your registration process:

user registration process
user registration process

(1) Create a register form with all the fields required such as – username and password

(2) Create a view to talk to the form and html that will render the form and save the form data when form is submitted

(3) Create the register html that is wired to the view and form to display form and collect data from the client

Details of the user registration form:

from django import forms
from django.contrib.auth.models import User 
from django.contrib.auth.forms import UserCreationForm

class RegisterForm(UserCreationForm):
    email = forms.EmailField(
                    max_length=100, 
                    required = True,
                    help_text='Enter Email Address', 
                    widget=forms.TextInput(attrs={'class': 'form-control', 
                                                 'placeholder': 'Email'}),
                    )
                    
    first_name = forms.CharField(
                    max_length=100, 
                    required = True,
                    help_text='Enter First Name',
                    widget=forms.TextInput(attrs={'class': 'form-control', 
                                                 'placeholder': 'First Name'}),
                    )
                    
    last_name = forms.CharField(
                    max_length=100, 
                    required = True,
                    help_text='Enter Last Name',
                    widget=forms.TextInput(attrs={'class': 'form-control', 
                                                  'placeholder': 'Last Name'}),
                    )
    username = forms.CharField(
                    max_length=200,
                    required = True,
                    help_text='Enter Username',
                    widget=forms.TextInput(attrs={'class': 'form-control', 
                                                   'placeholder': 'Username'}),
                    )
    password1 = forms.CharField(
                    help_text='Enter Password',
                    required = True,
                    widget=forms.PasswordInput(attrs={'class': 'form-control', 
                                                   'placeholder': 'Password'}),
                    )
    password2 = forms.CharField(
                    required = True,
                    help_text='Enter Password Again',
                    widget=forms.PasswordInput(attrs={'class': 'form-control', 
                                             'placeholder': 'Password Again'}),
                    )
    check = forms.BooleanField(required = True)



    class Meta:
        model = User 
        fields = [
        'username', 'email', 'first_name', 'last_name', 'password1', 
        'password2', 'check',
        ]

This is a long and detailed way of creating our RegisterForm, it however allows us the flexibility to set css classes and form placeholders for our register form.

Placeholder – the placeholder is a useful attribute in any form, clients can see the expected data for any form field.

Custom CSS – This allows us to style our form with our specific template CSS

Step 3 – Views Python File

The views file is the one that talks to the Form created. The view file also renders the html file, and passes the form object to the html file.

add user registration to python django
add user registration to python django

All the variables created in the form, will be fields within the HTML for user input.

from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import RegisterForm


def register(request):
    if request.method == 'GET':
        form  = RegisterForm()
        context = {'form': form}
        return render(request, 'register.html', context)

    if request.method == 'POST':
        form  = RegisterForm(request.POST)
        if form.is_valid():
            form.save()
            user = form.cleaned_data.get('username')
            messages.success(request, 'Account was created for ' + user)
            return redirect('home_page')
        else:
            print('Form is not valid')
            messages.error(request, 'Error Processing Your Request')
            context = {'form': form}
            return render(request, 'register.html', context)



    return render(request, 'register.html', {})

The Views file does two things:

(1) Handles the GET request by rendering the html file, sends the form object to the front end for display

(2) Handles the POST request, gets the data posted and processes it – saving it to the database

Step 4: The Register HTML FILE

The Register html file shows the user in the front-end the form. It collects the data to the back-end, views.py file. Then the data gets daved.

Note: Only the FORM part of the file is shown below, not the entire Register HTML file

<form class="login-form" method="POST">

                          {% csrf_token %}


                            <div class="row">

                              <div class="col-md-12">
                                {% if form.errors %}
                                  {% for field in form %}
                                      {% for error in field.errors %}
                                          <div class="alert alert-danger">
                                              <strong>{{ error|escape }}</strong>
                                              <strong>{{ field|escape }}</strong>
                                          </div>
                                      {% endfor %}
                                  {% endfor %}
                                  {% for error in form.non_field_errors %}
                                      <div class="alert alert-danger">
                                          <strong>{{ error|escape }}</strong>
                                      </div>
                                  {% endfor %}
                              {% endif %}
                              </div>


                                <div class="col-md-6">
                                    <div class="form-group position-relative">
                                        <label>First name <span class="text-danger">*</span></label>
                                        {{form.first_name}}
                                    </div>
                                    {% if form.first_name.errors %}
                                    {% for error in form.first_name.errors %}
                                        <div class="alert alert-danger">
                                            <strong>{{ error|escape }}</strong>
                                        </div>
                                    {% endfor %}
                                    {% endif %}
                                </div>
 <div class="col-md-6">
                                    <div class="form-group position-relative">
                                        <label>Last name <span class="text-danger">*</span></label>
                                        {{form.last_name}}
                                    </div>
                                    {% if form.last_name.errors %}
                                    {% for error in form.last_name.errors %}
                                        <div class="alert alert-danger">
                                            <strong>{{ error|escape }}</strong>
                                        </div>
                                    {% endfor %}
                                    {% endif %}
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group position-relative">
                                        <label>Your Email <span class="text-danger">*</span></label>
                                        {{form.email}}
                                    </div>
                                    {% if form.email.errors %}
                                    {% for error in form.email.errors %}
                                        <div class="alert alert-danger">
                                            <strong>{{ error|escape }}</strong>
                                        </div>
                                    {% endfor %}
                                    {% endif %}
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group position-relative">
                                        <label>Username <span class="text-danger">*</span></label>
                                        {{form.username}}
                                    </div>
                                    {% if form.username.errors %}
                                    {% for error in form.username.errors %}
                                        <div class="alert alert-danger">
                                            <strong>{{ error|escape }}</strong>
                                        </div>
                                    {% endfor %}
                                    {% endif %}
                                </div>
 <div class="col-md-12">
                                    <div class="form-group position-relative">
                                        <label>Password <span class="text-danger">*</span></label>
                                        {{form.password1}}
                                    </div>
                                    {% if form.password1.errors %}
                                    {% for error in form.password1.errors %}
                                        <div class="alert alert-danger">
                                            <strong>{{ error|escape }}</strong>
                                        </div>
                                    {% endfor %}
                                    {% endif %}
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group position-relative">
                                      <label>Confirm Password <span class="text-danger">*</span></label>
                                      {{form.password2}}
                                    </div>
                                    {% if form.password2.errors %}
                                    {% for error in form.password2.errors %}
                                        <div class="alert alert-danger">
                                            <strong>{{ error|escape }}</strong>
                                        </div>
                                    {% endfor %}
                                    {% endif %}
                                </div>
                                <div class="col-md-12">
                                    <div class="form-group">
                                        <div class="custom-control">
                                            {{form.check}}
                                            <label >I Accept <a href="{% url 'terms' %}" class="text-primary">Terms And Condition</a></label>
                                        </div>
                                        {% if form.check.errors %}
                                        {% for error in form.check.errors %}
                                            <div class="alert alert-danger">
                                                <strong>{{ error|escape }}</strong>
                                            </div>
                                        {% endfor %}
                                        {% endif %}
                                    </div>
                                </div>
                                <div class="col-md-12">
                                    <button class="btn btn-primary w-100" type="submit" >Register</button>
                                </div>
                                <div class="mx-auto">
                                    <p class="mb-0 mt-3"><small class="text-dark mr-2">Already have an account ?</small> <a href="{% url 'login' %}" class="text-dark font-weight-bold">Sign in</a></p>
                                </div>
                            </div>
                        </form>

The form is very manual, instead of allowing Django to render the entire form, we have elected to enter the fields manually. This is a long process and defeats the point of using Django forms, but in our case, we wanted to have more flexibility in the way the form is displayed. We wanted to use our own CSS, styling, html.

We also managed to style our form errors. It is a good idea to learn development with the long detailed code – so you understand what they frameworks are really doing when they oversimplify the code.

Step 5: URL Pattern

The last step is to add the URL pattern for the register page . . . so Django can display this register html page.

Within the urls.py add the following line, make sure you import it at the top:


. . . . 
from users import views as users_views
. . . . 

. . . . 
path('register/',users_views.register, name='register'),
. . . . 

Full Video Tutorial

The full video tutorial is available on Youtube here

Leave a Reply

Your email address will not be published.

Subscribe to our mailing list

And get this 💃💃 Free😀 eBook !

Holler Box