Django user registration

Prerequisites

User registration

  • It's an essential component of modern digital experiences
  • Registration allows individuals to create an account, gain access to personalized services, and engage with the platform in a more meaningful way.
  • Whether it's an e-commerce site, social media platform, or a SaaS application, user registration serves as the gateway to the full suite of features offered by the service.

Importance of User Registration

  1. Personalization: Registration enables platforms to tailor content, recommendations, and services to the user's preferences and behaviors, enhancing the user experience.

  2. Security and Privacy: It provides a secure way to manage user access, ensuring that only authorized individuals can access sensitive features or data.

  3. Engagement and Retention: By registering, users often become more engaged with the platform, receiving notifications, updates, and personalized content that encourages ongoing interaction.

  4. Data Collection: Registration allows businesses to collect valuable data about their users, which can be used to improve services, target marketing efforts, and better understand user needs.

Key Elements of a User Registration Process

  1. User Input Fields: Typically includes fields such as name, email, password, and sometimes phone number or other details. It's important to strike a balance between gathering necessary information and maintaining simplicity to avoid user drop-off.

  2. Validation and Verification: Ensuring that the input data is valid (e.g., correct email format) and often includes steps like email verification to confirm the user's identity.

  3. Security Measures: Implementing features like CAPTCHA to prevent bots, strong password requirements, and encryption to protect user data.

  4. User Experience: The registration process should be straightforward, quick, and user-friendly. Providing options like social media logins can streamline the process, reducing friction for users.

  5. Privacy Compliance: Ensuring that the registration process complies with legal requirements such as GDPR or CCPA, which dictate how user data must be handled and stored.

Coding - registration

  • Let's begin the coding part.
  • As we already know how to create project and app let's dive in and create registration form

Create registration form

  • Take below user input for user registration

    • first_name
    • last_name
    • username
    • email
    • password1
    • password2
    • we are considering the default django user modal.
    • create the file my_app/forms.py and add below info to it.

my_app/forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model

class UserRegistrationForm(UserCreationForm):
    email = forms.EmailField(help_text='Enter email', required=True)

    class Meta:
        model = get_user_model()
        fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2']

    def save(self, commit=True):
        user = super().save(commit=False)
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
        return user
  • Above form takes the information required for the registration and provides functions to validates it.

Create registration view

  • Let's implement the registration feature
  • Requirements:
    • If user already logged in then show "Hello, You have logged in".
    • If user accessed the page with GET HTTP request then load the Django form
    • If user accessed the page with POST HTTP request then validate the form data and create the user if form is valid
    • If the form is invalid then render form with validation errors.

my_app/views.py

from django.contrib.auth import login
from django.http.response import HttpResponse
from django.shortcuts import render
from .forms import UserRegistrationForm


def register_user(request):
    # redirect if already login
    if request.user.is_authenticated:
        return HttpResponse(f"Hello, You have logged in")

    if request.method == "POST":
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return HttpResponse(f"Hello, You have logged in")
    else:
        form = UserRegistrationForm()
    template = "register.html"
    context = {"form": form}
    return render(request, template, context)
  • request.user.is_authenticated returns booelan True if user logged in otherwise it returns False
  • HttpResponse returns and HTTP response object.
  • login is used to login the user.
  • render is used to render the template with context and requrns an HttpResponse object.

    • request is the django HttpRequest object.
    • template (i.e register.html) is the template to be rendered.
    • context is the data that we want to available in the template while rendering.

templates/register.html

<html>
  <body>
    <form action="" method="POST">
      {% csrf_token %}
      {{ form }}
      <input type="submit" value="submit" />
    </form>
  </body>
</html>

configure the register view to urls

  • Add the register url to the urls.py file to link the register view.
  • When user accessed the url it will forward the request to the register view.

my_app/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path("register/", views.register_user, name="register_user")
]
  • path is used to link the url pattern and the view.
  • To make my_app urls accessible we need to link these with main project urls.
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("my_app.urls"))
]

Let's test the app

  • Create and save all the files mentioned above and run the development server using command python manage.py runserver 8000
  • Access url http://127.0.0.1:8000/register/ and test the app.
  • Find some tests below.

    • Fill only few fields and submit the form then it will re-render with error info.
    • Fill all required fields and submit the form the it will return message "Hello, You have logged in"

Note: Run migrations if not applied before running the development server.