Web Development 701 ~ Registration
In the previous blog we covered the basic implementation of authentication using the built-in authentication system of Django. In this blog we are going to cover how to handle user registration. The first thing to do is to add the following line to the urls.py
file under our authentication
app.
path('register', views.register, name='register')
Now to create the corresponding view in the views.py
file.
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(username=username, password=password)
login(request, user)
return redirect('index')
else:
form = UserCreationForm()
context = {'form': form}
return render(request, 'registration/register.html', context)
We are using a built-in form from Django (UserCreationForm
) and built-in functions to handle authentication/login, so we also need to add the following imports at the top of views.py
.
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
We are also using redirect
, so we need to add that on the end of the import of django.shortcuts
.
from django.shortcuts import render, redirect
Now to create the register.html
template, which is as follows.
{% extends "skeleton.html" %}
{% block title %}Register{% endblock %}
{% block body %}
<form method="POST" action="{% url 'register' %}">
{% csrf_token %}
{% if form.errors %}
<p>Errors in the form</p>
{% endif %}
{{ form }}
<p><input type="submit" value="register"></p>
</form>
{% endblock %}
To make a way of determining if a user is authenticated or not we can add some additional code to the index.html
template, which is as follows.
{% extends "skeleton.html" %}
{% block title %}Index{% endblock %}
{% block body %}
<h1>Index Page</h1>
{% if user.is_authenticated %}
<h2>{{ user.username }}</h2>
{% else %}
<h2>Not authenticated</h2>
{% endif %}
{% endblock %}
Now when the user is authenticated, their username will be shown, and if they are not then it will just show not authenticated.