Functions
Functions are the building blocks of Python code. In a Django project you'll use functions for:
- HTTP request handlers (function-based views)
- Utility helpers (shared logic used across views, forms, tasks)
- Template filters and simple template tags
- Signal receivers and management command helpers
Why functions matter in Django
Functions keep code DRY and testable. Use small, single-responsibility functions in your views and move business logic to utilities so you can unit-test them without HTTP requests.
Basic function syntax
A simple Python function:
def add(a, b):
"""
Add two numbers and return the result.
"""
return a + b
Example: function-based view (simple)
A minimal function-based view that uses a helper function:
# views.py
from django.http import HttpResponse
from .utils import render_welcome_message
def welcome_view(request):
message = render_welcome_message(request.user)
return HttpResponse(message)
# utils.py
def render_welcome_message(user):
if user.is_authenticated:
return f"Welcome back, {user.username}!"
return "Welcome, guest!"
Example: small utility function for tests
Extract logic into utilities to make testing easy:
# utils/strings.py
def slugify_title(title: str) -> str:
"""Return a URL-friendly slug for a blog title."""
return "-".join(title.lower().split())
Decorator example (useful for views and utilities)
Decorators let you wrap functions with reusable behaviors, e.g., a simple execution timer for debugging:
import time
from functools import wraps
def timing(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
print(f"{func.__name__} took {elapsed:.3f}s")
return result
return wrapper
@timing
def expensive_calculation(n):
# ...
return n * n
Common pitfalls
- Too much logic in views: move complex code to utilities or services
- Mutable default args: avoid using mutable objects as default parameter values
- Circular imports: place shared helpers in a separate module (e.g.,
utils
) and import lazily if needed
Quick exercise
Create a helper function format_currency(amount, currency="NPR")
that returns a formatted string like "NPR 1,234.00"
. Write a unit test for it.
Further reading / next steps
After you’re comfortable with functions, the next subtopic is Modules — learn to organize those functions into modules and packages that make your Django apps maintainable and reusable.