Creating a User Registration System in Django with Bootstrap
Written on
Chapter 1: Introduction to User Registration
In the previous section, we explored how to set up a login form. However, to enhance user experience, it is essential to implement a registration form to avoid the tedious task of manual user creation. This guide will delve into how to create a registration form in Django.
Note: If you haven't already, please review the previous section for context.
Section 1.1: Defining the Registration Form
Let's begin by establishing a user registration form that aligns with the user model in Django. The built-in user model in Django includes essential fields such as username, first name, and email, so we won't need to redefine these.
For improved aesthetics, I've included the fields: username, first name, and email using Bootstrap classes. This approach not only makes the form visually appealing but also clarifies our design intentions.
The clean_password2 method is responsible for validating that the second password matches the first one. If they do not match, a validation error is raised. The naming convention follows the clean_() pattern, which is used for any field validation in the form.
class UserRegistrationForm(forms.ModelForm):
username = forms.CharField(label="Username", widget=forms.TextInput(attrs={"class": "form-control"}))
first_name = forms.CharField(label="First Name", widget=forms.TextInput(attrs={"class": "form-control"}))
email = forms.EmailField(label="Email", widget=forms.EmailInput(attrs={"class": "form-control"}))
password = forms.CharField(label="Password", widget=forms.PasswordInput(attrs={"class": "form-control"}))
password2 = forms.CharField(label="Confirm Password", widget=forms.PasswordInput(attrs={"class": "form-control"}))
class Meta:
model = User
fields = ("username", "first_name", "email")
def clean_password2(self):
cd = self.cleaned_data
if cd["password"] != cd["password2"]:
raise forms.ValidationError("Passwords do not match.")
return cd["password2"]
Section 1.2: Handling Requests
To manage user requests, we need to distinguish between GET and POST requests. For GET requests, we render the registration form. For POST requests, we validate the form and, if valid, save the new user to the database. Django automatically handles password hashing.
def register(request):
if request.method == "POST":
form = UserRegistrationForm(request.POST)
if form.is_valid():
new_user = form.save(commit=False)
new_user.set_password(form.cleaned_data["password"])
new_user.save()
return render(request, "account/register_done.html", {"form": form})
else:
form = UserRegistrationForm()
return render(request, "account/register.html", {"form": form})
After a successful registration, the password will not be stored in plain text. Let’s complete the tutorial by creating two new HTML templates for our registration process.
Chapter 2: Setting Up URLs and Templates
Before we create our templates, we need to register the view in urls.py.
urlpatterns = [
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
path('', views.dashboard, name='dashboard'),
path('register/', views.register, name='register'), # new
]
Templates Creation:
register.html:
I prefer to manually render forms as it gives me better control over their layout. Starting with {{ user.as_p }} is convenient, but manual rendering allows for easier styling adjustments.
{% extends "base.html" %}
{% block title %}Register User{% endblock %}
{% block content %}
<h2>Register</h2>
<form method="post">
{{ form.username.errors }}
<label>Username</label>
{{ form.username }}
{{ form.first_name.errors }}
<label>First Name</label>
{{ form.first_name }}
{{ form.email.errors }}
<label>Email</label>
{{ form.email }}
{{ form.password.errors }}
<label>Password</label>
{{ form.password }}
{{ form.password2.errors }}
<label>Repeat Password</label>
{{ form.password2 }}
{% csrf_token %}
<button type="submit">Register</button></form>
{% endblock %}
register_done.html:
This template will inform users of a successful registration.
{% extends "base.html" %}
{% block title %}Welcome{% endblock %}
{% block content %}
<h2>Welcome {{ new_user.first_name }}!</h2>
<p>Your account has been successfully created. You may now log in.</p>
{% endblock %}
base.html (Update):
Make sure to update base.html to include user authentication checks.
{% if request.user.is_authenticated %}
<p>Hello {{ request.user.first_name|default:request.user.username }},</p>
<a href="{% url 'logout' %}">Logout</a>
{% csrf_token %}
{% endif %}
{% block content %}
{% endblock %}
Login Form Update:
Ensure that the login page provides an easy way for users to navigate to the registration form if they don’t have an account.
<h2>Log In</h2>
<p>Don't have an account? <a href="{% url 'register' %}">Register here</a>.</p>
Running the Application:
Now, run your application with the command:
python manage.py runserver
Let's test the functionality, including the registration, login, and logout processes.
Video Resource:
To enhance your understanding of crafting registration forms in Django with Bootstrap, check out the following resources:
This video titled "Style Django Registration Forms - Django Wednesdays #26" provides a detailed walkthrough of styling registration forms in Django.
Additional Video Resource:
For further insights into creating a custom user registration form using Bootstrap in Django, view the following video:
Titled "User registration in django | Custom User register form using bootstrap," this video will guide you through the process.
Thank you for following along with this guide! If you found this information helpful, consider joining our community for more insights and discussions. Your feedback is always appreciated!