Byte Squad

Django Sign-Up and Login with Confirmation Email

December 4, 2023 | by bytessquad.com

django signup and login form

Introduction:
Django, a high-level web framework written in Python, provides a robust authentication system out of the box. In this article, we will delve into the process of creating a user sign-up and login functionality with an additional layer of security through confirmation emails. This extra step ensures that only valid users gain access to your application.

Prerequisites:
Before we begin, make sure you have Django installed. You can install it using the following command:

pip install django

Once Django is installed, you can create a new project using:

django-admin startproject myproject

And create a new app within the project:

cd myproject
python manage.py startapp myapp

Step 1: Set Up User Model:
In your models.py file within the myapp app, create a custom user model:

# myapp/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)

    def __str__(self):
        return self.username

Ensure to include the custom user model in your project’s settings:

# myproject/settings.py
AUTH_USER_MODEL = 'myapp.CustomUser'

Run migrations to apply these changes:

python manage.py makemigrations
python manage.py migrate

Step 2: Create Sign-Up Form:
Create a forms.py file in your myapp folder to define a custom registration form:

# myapp/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser

class SignUpForm(UserCreationForm):
    email = forms.EmailField()

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

Step 3: Implement Sign-Up View:
In your views.py file, create a sign-up view:

# myapp/views.py
from django.shortcuts import render, redirect
from django.contrib.auth import login
from .forms import SignUpForm

def sign_up(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('home')  # Change 'home' to your desired home page URL
    else:
        form = SignUpForm()
    return render(request, 'registration/sign_up.html', {'form': form})

Step 4: Configure URLs:
Define a URL pattern for the sign-up view in your urls.py file:

# myapp/urls.py
from django.urls import path
from .views import sign_up

urlpatterns = [
    path('sign-up/', sign_up, name='sign_up'),
]

Include these app-specific URLs in your project’s urls.py:

# myproject/urls.py
from django.contrib import admin
from django.urls import path, include

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

Step 5: Create Sign-Up Template:
Create an HTML template for the sign-up page. This template can include the form rendered with the form variable:

<!-- myapp/templates/registration/sign_up.html -->
{% extends 'base.html' %}

{% block content %}
  <h2>Sign Up</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign Up</button>
  </form>
{% endblock %}

Step 6: Set Up Email Confirmation:
Django provides the django-allauth package for a comprehensive authentication solution, including email confirmation. Install it using:

pip install django-allauth

Follow the official documentation to configure the package.

Step 7: Update URLs for Confirmation:
Include allauth URLs in your project’s urls.py:

# myproject/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('allauth.urls')),
    path('', include('myapp.urls')),
]

Conclusion:
By following these steps, you’ve created a user sign-up functionality with email confirmation in your Django project. This additional layer of security ensures that only verified users gain access to your application. Feel free to customize the templates, views, and forms to fit your project’s specific requirements.

RELATED POSTS

View all

view all