Showing posts with label Python Web Development. Show all posts
Showing posts with label Python Web Development. 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.


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


Django Authentication: Build Login, Logout, and Signup from Scratch

← Back to Home

 

๐Ÿ”’ Django Authentication System from Scratch (Login, Logout, Signup)


Introduction

User authentication is a fundamental part of any modern web application. Whether you're building a blog, e-commerce store, or social network, you need a secure way for users to log in and manage their accounts.

In this guide, you’ll learn how to create a simple but functional authentication system in Django — including user registration (signup), login, and logout.


Prerequisites

Before you begin, make sure:

  • You have Python 3.x and Django installed
    Install Django (if not yet installed):

    pip install django
    
  • You have a basic Django project and app already created.
    If not, run:

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

Then, add 'accounts' to your INSTALLED_APPS in settings.py.


Step 1: Set Up URLs

In authproject/urls.py

from django.contrib import admin
from django.urls import path, include

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

In accounts/urls.py

Create this file inside your accounts app:

from django.urls import path
from . import views

urlpatterns = [
    path('signup/', views.signup_view, name='signup'),
    path('login/', views.login_view, name='login'),
    path('logout/', views.logout_view, name='logout'),
]

Step 2: Create Views

In accounts/views.py:

from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import login, logout

def signup_view(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('/')
    else:
        form = UserCreationForm()
    return render(request, 'accounts/signup.html', {'form': form})

def login_view(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('/')
    else:
        form = AuthenticationForm()
    return render(request, 'accounts/login.html', {'form': form})

def logout_view(request):
    if request.method == 'POST':
        logout(request)
        return redirect('/')

Step 3: Create Templates

Create a templates/accounts/ folder inside your app and add the following:

signup.html

<h2>Sign Up</h2>
<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Sign Up</button>
</form>

login.html

<h2>Login</h2>
<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Login</button>
</form>

Step 4: Add Logout Button

In your base template or homepage, add a logout form:

{% if user.is_authenticated %}
  <form method="POST" action="{% url 'logout' %}">
    {% csrf_token %}
    <button type="submit">Logout</button>
  </form>
{% endif %}

Step 5: Protect Pages with Login

You can protect views by adding the login-required decorator:

from django.contrib.auth.decorators import login_required

@login_required
def dashboard(request):
    return render(request, 'dashboard.html')

Also, set the login redirect URL in settings.py:

LOGIN_URL = '/accounts/login/'

Conclusion

You now have a fully functional authentication system in Django — built from scratch! Users can sign up, log in, and log out. You’ve learned how to:

  • Use Django’s built-in authentication forms

  • Secure routes with decorators

  • Render and protect user data

✅ You can now build on this foundation by adding user profiles, password resets, and more.



Top 10 Python Libraries You Must Know in 2025 — Complete Guide for Beginners & Experts

← Back to Home

Top 10 Python Libraries You Must Know in 2025 (With Use Cases)


Introduction

Python’s rich ecosystem of libraries is one reason why it’s loved by developers worldwide. Whether you’re a beginner eager to learn or an expert looking to stay updated, knowing the right libraries can boost your productivity and open doors to new possibilities.

In this post, I’ll introduce you to the top 10 Python libraries you must know in 2025, along with their core use cases, installation tips, and mini code examples to get you started quickly.


1. NumPy

Use case: Numerical computing and powerful array operations.
NumPy is the foundation for scientific computing in Python. It allows fast operations on large multi-dimensional arrays and matrices.

Mini Example:

import numpy as np
arr = np.array([1, 2, 3])
print(arr * 2)  # Output: [2 4 6]

Install:

pip install numpy

2. Pandas

Use case: Data manipulation and analysis.
Pandas offers data structures like DataFrames that simplify working with structured data, making data cleaning and analysis intuitive.

Mini Example:

import pandas as pd
data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)

Install:

pip install pandas

3. Requests

Use case: HTTP requests made simple.
Requests makes it easy to send HTTP/1.1 requests without the hassle of manual connection handling, perfect for web scraping or API consumption.

Mini Example:

import requests
response = requests.get('https://api.github.com')
print(response.status_code)

Install:

pip install requests

4. Matplotlib

Use case: Data visualization.
Create static, animated, and interactive plots in Python. Matplotlib is versatile and widely used for plotting graphs.

Mini Example:

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

Install:

pip install matplotlib

5. FastAPI

Use case: Modern, fast web APIs.
FastAPI is a high-performance framework for building APIs quickly with Python 3.7+ based on standard Python type hints.

Mini Example:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

Install:

pip install fastapi uvicorn

6. Pydantic

Use case: Data validation and settings management.
Pydantic uses Python type annotations to validate data, ideal for ensuring your APIs or configs are robust and error-free.

Mini Example:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str

user = User(id=1, name="Alice")
print(user)

Install:

pip install pydantic

7. Selenium

Use case: Browser automation and testing.
Automate browsers for testing web applications or scraping dynamic web pages.

Mini Example:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.python.org')
print(driver.title)
driver.quit()

Install:

pip install selenium

8. BeautifulSoup

Use case: Web scraping.
Parse HTML and XML documents to extract data easily.

Mini Example:

from bs4 import BeautifulSoup

html = "<html><head><title>Test</title></head><body><p>Hello</p></body></html>"
soup = BeautifulSoup(html, 'html.parser')
print(soup.title.string)

Install:

pip install beautifulsoup4

9. TensorFlow

Use case: Machine learning and deep learning.
TensorFlow is a powerful library for building and training ML models, widely used in AI applications.

Mini Example:

import tensorflow as tf

hello = tf.constant('Hello, TensorFlow!')
tf.print(hello)

Install:

pip install tensorflow

10. Plotly

Use case: Interactive data visualization.
Plotly helps you create beautiful interactive charts and dashboards for data analysis.

Mini Example:

import plotly.express as px

fig = px.bar(x=["a", "b", "c"], y=[1, 3, 2])
fig.show()

Install:

pip install plotly

Why Learn These Libraries?

  • Beginners: They provide a strong foundation in Python’s most practical applications — data science, web development, automation, and AI. Learning these tools opens doors to exciting projects and job opportunities.

  • Experts: Staying current with the latest tools and frameworks helps maintain efficiency, write cleaner code, and leverage improvements in performance and usability.


Conclusion

Mastering these libraries will supercharge your Python journey in 2025, whether you’re just starting out or refining advanced skills. Don’t just read about them — try building small projects or scripts using these libraries to gain hands-on experience. The Python ecosystem is vast and powerful, and these libraries are your gateway to making the most of it.


← Back to Home

Build a Blog and To-Do App in Django: Full Step-by-Step Guide with Code (2025)

← Back to Home

 

๐Ÿงฑ Build a Blog and To-Do List App in Django – Step-by-Step (With Code)


Here's a step-by-step Django tutorial to help you:

  1. ✅ Build a Blog App

  2. ✅ Build a To-Do List App

  3. ✅ Combine both into a single Django project with two separate apps

๐Ÿงฐ Prerequisites

  • Python installed

  • Django installed:

    pip install django
    
  • Basic knowledge of Python and HTML


1️⃣ Create the Django Project

django-admin startproject mysite
cd mysite

2️⃣ Create the Blog App

python manage.py startapp blog

➕ Register Blog App in mysite/settings.py

INSTALLED_APPS = [
    ...
    'blog',
]

๐Ÿงพ blog/models.py

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

๐Ÿ” Run Migrations

python manage.py makemigrations
python manage.py migrate

๐Ÿงพ blog/views.py

from django.shortcuts import render
from .models import Post

def post_list(request):
    posts = Post.objects.all().order_by('-created_at')
    return render(request, 'blog/post_list.html', {'posts': posts})

๐Ÿงพ blog/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
]

๐Ÿงพ mysite/urls.py (Edit)

from django.contrib import admin
from django.urls import path, include

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

๐Ÿ–ผ️ blog/templates/blog/post_list.html

<!DOCTYPE html>
<html>
<head><title>My Blog</title></head>
<body>
    <h1>Blog Posts</h1>
    {% for post in posts %}
        <h2>{{ post.title }}</h2>
        <p>{{ post.content }}</p>
        <small>{{ post.created_at }}</small><hr>
    {% empty %}
        <p>No posts yet.</p>
    {% endfor %}
</body>
</html>

Test it:

python manage.py runserver

Visit: http://127.0.0.1:8000/blog/


3️⃣ Create the To-Do App

python manage.py startapp todo

➕ Add 'todo' to INSTALLED_APPS


๐Ÿงพ todo/models.py

from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=100)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title
python manage.py makemigrations
python manage.py migrate

๐Ÿงพ todo/views.py

from django.shortcuts import render, redirect
from .models import Task

def task_list(request):
    tasks = Task.objects.all()
    return render(request, 'todo/task_list.html', {'tasks': tasks})

def add_task(request):
    if request.method == 'POST':
        title = request.POST['title']
        Task.objects.create(title=title)
    return redirect('task_list')

def toggle_task(request, task_id):
    task = Task.objects.get(id=task_id)
    task.completed = not task.completed
    task.save()
    return redirect('task_list')

๐Ÿงพ todo/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.task_list, name='task_list'),
    path('add/', views.add_task, name='add_task'),
    path('toggle/<int:task_id>/', views.toggle_task, name='toggle_task'),
]

๐Ÿงพ mysite/urls.py (Add to existing)

path('todo/', include('todo.urls')),

๐Ÿ–ผ️ todo/templates/todo/task_list.html

<!DOCTYPE html>
<html>
<head><title>To-Do List</title></head>
<body>
    <h1>My To-Do List</h1>
    <form method="post" action="{% url 'add_task' %}">
        {% csrf_token %}
        <input type="text" name="title" placeholder="New task">
        <button type="submit">Add</button>
    </form>
    <ul>
        {% for task in tasks %}
            <li>
                <a href="{% url 'toggle_task' task.id %}">
                    {% if task.completed %}
                        <s>{{ task.title }}</s>
                    {% else %}
                        {{ task.title }}
                    {% endif %}
                </a>
            </li>
        {% empty %}
            <li>No tasks yet!</li>
        {% endfor %}
    </ul>
</body>
</html>

Test:
Visit http://127.0.0.1:8000/todo/


๐Ÿงฉ 4️⃣ Combine Both Apps in One Project

You already did it — both blog and todo are separate apps inside one project, accessible via:

  • http://127.0.0.1:8000/blog/

  • http://127.0.0.1:8000/todo/

Each app:

  • Has its own models, views, templates, and URL routes

  • Can be developed independently

  • Shares the same database and project settings


๐ŸŽ Bonus: Add Navigation Links

Add this nav to both templates:

<a href="/blog/">Blog</a> | <a href="/todo/">To-Do</a>

๐Ÿ Conclusion

You’ve built:

  • ✅ A full-featured Blog app

  • ✅ A functional To-Do List app

  • ✅ A combined Django project that includes both

This modular approach mirrors how real-world Django sites are structured — scalable and organized.



Featured Post

Extra Challenge: Using References Between Documents

  ๐ŸŽฏ ๐Ÿ’ก Extra Challenge: Using References Between Documents Here's an  Extra Challenge  designed to build on the original MongoDB mod...

Popular Posts