Laughing Blog Tutorial part 5 : Django User Registration

published on: | by cindy In category: Tutorial Series

In the Previous article Django Authentication Framework we used Django built-in views to log in already existing users.

In this article, we will learn how to register users using Django built-in form UserCreationForm However, we will create our own registration view as Django doesn't provide views for registering users.

UserCreationForm inherits from ModelForm class and come with three fields username, password1 and a password2 for confirmation.

in the accounts app we will create a file forms.py

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

class SignupForm(UserCreationForm):
    email = forms.EmailField(max_length=200, help_text='Required')

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    def clean_email(self):
        email = self.cleaned_data['email']
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('Please use another Email, that is already taken')
        return email

To use the UserCreationForm we need to import it from from django.contrib.auth.forms and also import the User object.

Django authentication framework by default uses username to authenticate users but in the above code we define the email field and set it to required

We will need it later when we will ask users to activate their accounts after registration by sending tokens to their email address,

We have to clean our email field to ensure that it is unique. The function clean_email checks if the email already exists and throw an error We then create a function to clean email field and check if the email already exists and throws an error `'Please use another Email, that is already taken'

Creating the User Creation View

from django.shortcuts import render, redirect
from .forms import SignupForm

def register(request):
    if request.method == 'POST':
        userform = SignupForm(request.POST)
        if userform.is_valid():
            userform.save()
            return redirect('login')
    else:
        userform = SignupForm()
    context = {'userform': userform}
    template = "accounts/signup.html"
    return render(request, template, context)

To use the UserCreationForm we have to import it from forms.py We check it 's a POST request else we return the SignUpForm. If it is aPOST request, we instantiate a form instance and populate it with data from the request, check if the form is valid and save. If the user is created successfully, we redirect them to the login view

accounts/urls.py

from django.urls import path
from .views import register 
urlpatterns = [
    path(''register/'', register, name=''register'')
]

laughing_blog/urls.py

path(''accounts/'', include(''accounts.urls'')),

Creating signup template

accounts/templates/accounts create a file signup.html

{% extends "base.html" %}
{% block title %}Create an account{% endblock %}
{% block content %}
<h2>Create an account</h2>
<form action="." method="post">{% csrf_token %}
{{ userform.as_p }}
<input type="submit" name='' value='Save changes'>
</form> 
{% endblock %}

Its time to visit the registration form. navigate to http://127.0.0.1:8000/accounts/register/ and if everything works as it should, this ugly form should appear on the browser!

Conclusion

This is part 5 of the laughing blog tutorial series, so if you miss on anything, please refer to the previous articles.

We can now add create users and I hope you enjoyed this simple registration

Authorization vs Authentication

Authentication: verify user credentials such as username against password to ascertain the user is who they say they are. Authorization determines that the authenticated user is authorized to perform some given operation (usually by checking against granted permissions)

The code can be found on github github and to view this article code, go to this commit