Showing posts with label django tutorials. Show all posts
Showing posts with label django tutorials. Show all posts

Password Reset via Email in Django: Complete Step-by-Step Tutorial

 

🔄 Implementing Password Reset via Email in Django (Step-by-Step)


🔐 Mini-Series Reference

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

  1. Customize the Django User Model

  2. 📧 Add Email Verification to Signup

  3. 👤 Create User Profiles

  4. 🔄 Password Reset via Email (You are here)


Introduction

Password reset functionality is essential for any user-based application. Django provides built-in views and forms to handle this securely.

This post will guide you through configuring and customizing password reset emails and workflows in your Django app.


Step 1: Configure Email Backend

For development, use the console backend (prints emails to console):

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

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


Step 2: Add URL Patterns for Password Reset

In your accounts/urls.py:

from django.urls import path
from django.contrib.auth import views as auth_views

urlpatterns = [
    # Password reset URLs
    path('password_reset/', auth_views.PasswordResetView.as_view(template_name='accounts/password_reset_form.html'), name='password_reset'),
    path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='accounts/password_reset_done.html'), name='password_reset_done'),
    path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='accounts/password_reset_confirm.html'), name='password_reset_confirm'),
    path('reset_done/', auth_views.PasswordResetCompleteView.as_view(template_name='accounts/password_reset_complete.html'), name='password_reset_complete'),
]

Step 3: Create Templates

Create the following templates in templates/accounts/:

password_reset_form.html

<h2>Reset Password</h2>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Send Reset Email</button>
</form>

password_reset_done.html

<p>An email has been sent with instructions to reset your password.</p>

password_reset_confirm.html

<h2>Set New Password</h2>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Reset Password</button>
</form>

password_reset_complete.html

<p>Your password has been reset successfully! You can now <a href="{% url 'login' %}">log in</a>.</p>

Step 4: Customize Password Reset Email Template (Optional)

Create registration/password_reset_email.html (this path is required):

{% autoescape off %}
Hi {{ user.get_full_name|default:user.email }},

You're receiving this email because you requested a password reset for your account.

Please go to the following link and set your new password:

{{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %}

If you didn’t request this, please ignore this email.

Thanks,
Your Website Team
{% endautoescape %}

Step 5: Test the Flow

  • Visit /password_reset/

  • Enter your email and submit

  • Check console (in dev) for email with reset link

  • Click link, set new password

  • Verify you can log in with new password


Conclusion

You’ve successfully added a secure password reset feature to your Django app with minimal effort by leveraging Django’s built-in auth views.

This completes our Django Authentication Mini-Series! You now have a solid foundation for user management, including custom users, email verification, profiles, and password reset.

Thank you for your patience! keep learning...

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.


How to Customize the Django User Model (Complete Step-by-Step Guide)

← Back to Home


🔐 Django Authentication : Mini Series


✅ Part 1: How to Customize the Django User Model

This is Part 1 of our Django Authentication Mini-Series.

    Next up: Email Verification → User Profiles → Password Reset



🔐 How to Customize the Django User Model in Django (Step-by-Step)


Introduction

While Django’s built-in User model works for many use cases, real-world apps often require custom fields like full name, phone number, or even profile images. Instead of modifying the default model (which can be tricky later), Django allows you to create your own user model from the beginning.

In this post, you'll learn how to build and use a custom user model in Django — safely and properly.


Step 1: Start a New Project or App

⚠️ This should be done before applying migrations if you're starting from scratch.

django-admin startproject myproject
cd myproject
python manage.py startapp accounts

Step 2: Create a Custom User Model

In accounts/models.py:

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from django.utils import timezone

class CustomUserManager(BaseUserManager):
    def create_user(self, email, password=None, **extra_fields):
        if not email:
            raise ValueError("Email is required")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        return self.create_user(email, password, **extra_fields)

class CustomUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True)
    full_name = models.CharField(max_length=100)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    date_joined = models.DateTimeField(default=timezone.now)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['full_name']

    objects = CustomUserManager()

    def __str__(self):
        return self.email

Step 3: Update settings.py

In your myproject/settings.py:

AUTH_USER_MODEL = 'accounts.CustomUser'

This tells Django to use your custom model instead of the default one.


Step 4: Create & Apply Migrations

Only do this if you haven't applied migrations yet (new project):

python manage.py makemigrations
python manage.py migrate

Step 5: Update admin.py (Optional but Useful)

In accounts/admin.py:

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser

class CustomUserAdmin(UserAdmin):
    model = CustomUser
    list_display = ('email', 'full_name', 'is_staff', 'is_active')
    list_filter = ('is_staff', 'is_active')
    search_fields = ('email',)
    ordering = ('email',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal Info', {'fields': ('full_name',)}),
        ('Permissions', {'fields': ('is_staff', 'is_active', 'is_superuser', 'groups', 'user_permissions')}),
        ('Dates', {'fields': ('last_login',)}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('email', 'full_name', 'password1', 'password2', 'is_staff', 'is_active')}
        ),
    )

admin.site.register(CustomUser, CustomUserAdmin)

Step 6: Use Custom User in Forms

Replace any UserCreationForm or AuthenticationForm with ones adapted to use CustomUser.

Example:

from django.contrib.auth.forms import UserCreationForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = CustomUser
        fields = ('email', 'full_name')

Conclusion

You’ve now created a fully customizable authentication model that supports your project’s future needs. With this foundation, you can:

  • Add new fields anytime

  • Use email instead of usernames

  • Extend it easily in the next posts (user profiles, email verification, etc.)


Next in this mini-series:

📧 Add Email Verification to Django Signup


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