Django: Restricting Pages and creating a registration form

Alifia Ghantiwala
4 min readApr 16, 2023

Django is simpler than it seems!

Photo by Boitumelo Phetla on Unsplash

Introduction:

In continuation to my last blog where I created a login and logout mechanism using Django, in this article I would be creating the registration form for signing up a new user and exploring how we can restrict access to certain web pages.

Linking my last article, in case you would want to have a look.

Restricting user access to web applications:

You would want to control the access a user has on your application, say you would want to allow only the admin of a group to add or remove members, or you would only want people who are logged in to your application to be able to create, edit or delete groups.

You could do this simply, by using a built-in decorator in Django. A decorator is simply a way you can add functionality to a function without changing it. For example, say you have a function to create a room in your code, you would use Django’s built-in decorator: login_required to restrict the user from creating a room without logging in.

Code in Action:


from django.contrib.auth.decorators import login_required
@login_required(redirect_field_name="{% url 'login' %}")
# The decorator login_required would check if the user is logged in and if not
# redirect the user to the login page.
def create_room(request):
'''Function to create a room/group'''

Creating a registration page for a user to sign up for your web app:

We would use Django’s UserCreationForm module which inherits from the ModelForm class. The module allows us to create a new user. If the user is sending data to the form i.e the method is POST, we check if the form is valid and then save the user details, i.e username(after lowercasing) and the user’s entered password. We have written this function in our views.py file. I have explained the entire file structure of a typical Django project in my previous post here.

Next, we create a register.html file where we would define how we would want to render the registration page. First, we are extending, the template from main.html and creating a form within the {%block content%}, (this again has been explained in my previous post). In the form, we are setting the action parameter to our register url[see urls.py linked below where we have added the reference to the link with the name ‘register’]. We are then passing a csrf token, [used to prevent Cross-Site Request Forgery] and rendering the UserCreationForm, next, we have a submit button and we are redirecting the user to the login page if they have already signed up to our web app.

Below is the code in action:

# views.py: Function to register user 
def registerPage(request):
form = UserCreationForm()
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.username = user.username.lower()
user.save()
login(request, user)
return redirect("home")
else:
messages.error(request, "An error occour during registration")
# register.html

{% extends 'main.html' %}

{% block content %}
<div>
<form action="{% url 'register' %}" method="POST">
{% csrf_token %}

{{ form.as_p }}

<input type="submit" value="Register" />
</form>

<p>Already signed up yet?</p>
<a href="{% url 'login' %}">Login</a>
</div>
{% endblock content %}
# urls.py 
from django.urls import path, include
from . import views

urlpatterns = [
path("accounts/", include("django.contrib.auth.urls")),
path('register/',views.registerPage,name='register'),
path('',views.home,name='home'),
path('room/<str:pk>/',views.room,name='room'),
path('create-room/',views.create_room,name='create-room'),
path('update-room/<str:pk>/',views.update_room,name='update-room'),
path('delete-room/<str:pk>/',views.delete_room,name='delete-room')
]

You can also extend the UserCreationForms and create a custom form that allows you to include any fields like the email address of a user. The standard user creation form takes in only the username and password of a user as input to register a person to your app.

Image by Author.

Conclusion:

In conclusion, all in all, Django provides a good layer of encapsulation making a beginner like me feel at home. We used a decorator today ‘login_required’ which forces a user to log in before he can access certain functionalities on your webpage and used the UserCreationForms to create a basic user registration form.

Shameless Self-Promotion:

I have written some articles on automation using Python, linking them here, in case you would want to have a look :P

Thanks for reading along, have fun Pythoning :)

--

--