Showing posts with label django email verification. Show all posts
Showing posts with label django email verification. Show all posts

Add Email Verification to Django Signup for Secure User Activation

← Back to Home

 

📧 Adding Email Verification to Django Signup (Step-by-Step Guide)


🔐 Mini-Series Reference

This is Part 2 of our Django Authentication Mini-Series:

  1. Customize the Django User Model

  2. 📧 Email Verification During Signup (You are here)

  3. 👤 Creating User Profiles in Django

  4. 🔄 Password Reset via Email


Introduction

Adding email verification to your Django app helps prevent spam, fake signups, and improves trust. In this tutorial, you’ll learn how to:

  • Send a verification email after user signup

  • Create activation links with secure tokens

  • Activate users only after email confirmation

We’ll use Django’s built-in token system and the EmailMessage utility — no third-party apps needed.


Step 1: Configure Email Backend

For development, use Django’s console backend:

# settings.py
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DEFAULT_FROM_EMAIL = 'noreply@yourdomain.com'

For production, configure SMTP (e.g. Gmail or SendGrid).


Step 2: Update Your Signup View

In your accounts/views.py:

from django.contrib.auth import get_user_model
from django.contrib.sites.shortcuts import get_current_site
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.utils.encoding import force_bytes, force_str
from django.template.loader import render_to_string
from django.contrib.auth.tokens import default_token_generator
from django.core.mail import EmailMessage

User = get_user_model()

def signup_view(request):
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False  # Deactivate account until email confirmed
            user.save()
            
            # Email verification
            current_site = get_current_site(request)
            mail_subject = 'Activate your account'
            message = render_to_string('accounts/activation_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': default_token_generator.make_token(user),
            })
            email = EmailMessage(mail_subject, message, to=[user.email])
            email.send()
            
            return HttpResponse('Check your email for a confirmation link.')
    else:
        form = CustomUserCreationForm()
    return render(request, 'accounts/signup.html', {'form': form})

Step 3: Create Email Template

Create templates/accounts/activation_email.html:

Hi {{ user.full_name }},

Thanks for registering. Please click the link below to activate your account:

http://{{ domain }}/accounts/activate/{{ uid }}/{{ token }}

Step 4: Handle Activation Link

In accounts/views.py, add:

from django.http import HttpResponse

def activate(request, uidb64, token):
    try:
        uid = force_str(urlsafe_base64_decode(uidb64))
        user = User.objects.get(pk=uid)
    except:
        user = None

    if user and default_token_generator.check_token(user, token):
        user.is_active = True
        user.save()
        return HttpResponse('Your account is activated! You can now log in.')
    else:
        return HttpResponse('Activation link is invalid or expired.')

Step 5: Add Activation URL

In accounts/urls.py:

path('activate/<uidb64>/<token>/', views.activate, name='activate'),

Step 6: Optional — Customize Success Message

You can redirect to login page with a success message instead of showing plain HttpResponse.


Final Notes

✅ You've now added email verification to your Django signup process!

you learned to secure your Django app by adding email verification during user signup and learned to send confirmation emails and activate users safely.

here are the three steps from this article:

  1. Add email verification to Django signup 
  2. Send activation links and 
  3. Secure user registration

Your users can’t log in until they verify their email, improving app security and trust.


What’s Next?

👉 In Part 3, we’ll build User Profiles in Django to store additional data like bio, avatar, or social links.


Featured Post

Number Guessing Game (code) in python

← Back to Projects About the project: This is a simple number guessing game and it is suitable for beginners who are learning python progra...

Popular Posts