How do users create their accounts?

Well, in order for users to create their account they will need to complete a form and fill out their details: typically with their username, email, and password.

So, how do we create a registration form in Django?

Step 1:

Create a form that inherits Django's in-built user creation form.

Once we've imported our UserCreationForm and attached it to our class CreateUserForm, we need to define our class as Meta, set our model to the default User model, and select the most relevant fields for our users.

In this case, we require our users to input a username, email, and password

# - forms.py

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

class CreateUserForm(UserCreationForm):

    class Meta:

        model = User
        fields = ['username', 'email', 'password1', 'password2']

Step 2:

Create a basic HTML page and ensure that it is in your 'templates' directory. The HTML page will be called - register.html

From the code below, I have taken the liberty of adding a bootstrap theme from bootswatch. Feel free to edit your login form's basic layout and structure, as you prefer.

We will fill out this section later with the necessary code:

<!-- TO BE COMPLETED -->

register.html

{% load static %}

<!DOCTYPE html>

<html lang="en">

    <head>

        <title> ET | Register </title>

        <meta charset="utf-8" />

        <meta name="viewport" content="width-device-width, initial-scale=1, maximum-scale=1"/>

        <link rel="stylesheet" type="text/css" href="https://bootswatch.com/5/morph/bootstrap.min.css">

        <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">

    </head>


    <body>

        <br>

        <div class="container bg-white p-5 style="width:500px;">

            <h3> Create your account </h3>

            <h5> Share your thoughts today! </h5>

            <br>
            <br>

            <form method="POST" autocomplete="off">

                {% csrf_token %}

                <!---TO BE COMPLETED-->

                <br> <br> 

                <button type="submit" class="btn btn-secondary btn-lg w-100 btn-block p-4"> &nbsp; Create account </button>


            </form>
        

        </div>

        <br>

    </body>

</html>

Step 3:

Create a view that handles user registration for our Django project.

Firstly, we need to import our CreateUserForm, which we created in our forms.py, We also want to import HttpResponse, so that we can be greeted with a simple message that we registered a user.

# - views.py

from .forms import CreateUserForm

from django.http import HttpResponse

Next, we need to create our view itself.

We need to pass in our CreateUserForm() and prepare the form to post the username, email, and password entered by the user.

Next, we need to check if we are sending a POST request from our form, which we will address in the next step. Then we need to see if our form is valid, free of errors and if it has been fully completed by the user. We can then proceed to post/send our user filled-in form with form.save() to our database.

Once our form has been submitted we want to return a basic HTTP response that confirms that the user successfully registered their account - this proves that the registration process was a success.

We need to also ensure that we render our form out to our HTML template - register.html

# - views.py

def register(request):

    form = CreateUserForm()

    if request.method == "POST":

        form = CreateUserForm(request.POST)

        if form.is_valid():
            
            form.save()           

            return HttpResponse("Registration successful!")


    context = {'form':form}

    return render(request, 'register.html', context=context)

Step 4:

We can now return to our HTML page - register.html and render our form's username, email, and password fields.

register.html


{% load static %}

<!DOCTYPE html>

<html lang="en">

    <head>

        <title> ET | Register </title>

        <meta charset="utf-8" />

        <meta name="viewport" content="width-device-width, initial-scale=1, maximum-scale=1"/>

        <link rel="stylesheet" type="text/css" href="https://bootswatch.com/5/morph/bootstrap.min.css">

        <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}">

    </head>


    <body>

        <br>

        <div class="container bg-white p-5 style="width:500px;">

            <h3> Create your account </h3>

            <h5> Share your thoughts today! </h5>

            <br>
            <br>

            <form method="POST" autocomplete="off">

                {% csrf_token %}

                {{form.as_p}}

                <br> <br> 

                <button type="submit" class="btn btn-secondary btn-lg w-100 btn-block p-4"> &nbsp; Create account </button>


            </form>
        

        </div>

        <br>

    </body>

</html>

Step 5:

Next, we need to connect and set our URLpath in urls.py.

We will need to pass in three parameters for our login URL path. First of all, we need to state our route, then attach our view and the name URL.

# - urls.py

from django.urls import path  
from . import views 

urlpatterns =[
    
    # - register url    
    
    path('register', views.register, name="register"),


]

DONE - You can now register new users within your Django project.