MVC vs. MTV Architecture
MVC (Model-View-Controller) is a popular design pattern, but Django follows the MTV (Model-Template-View) approach:
- Model: Manages database interactions and business logic.
- Template: Handles the presentation layer (HTML).
- View: Acts as a controller, processing requests and returning responses.
Request-Response Cycle in Django
URL Dispatcher: Matches the URL to a view function via urls.py.
View Function: Processes the request, interacts with the database, and prepares data.
Template Rendering: Combines data with a template if necessary.
HTTP Response: Returns an HttpResponse object to the client.
Key Point: Middleware processes requests and responses during this cycle.
Middleware in Django
- Middleware is a framework of hooks into Django's request/response processing.
- AuthenticationMiddleware: Associates users with requests.
- CSRF Middleware: Protects against cross-site request forgery.
- SessionMiddleware: Manages user sessions.
- Key Point: Middleware is processed in a sequence defined in MIDDLEWARE setting.
Custom Middleware
class CustomHeaderMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# Before view is called
response = self.get_response(request)
# After view is called
response['X-Custom-Header'] = 'Hello Django'
return response
__init__(self, get_response)
Purpose: Initializes middleware with a get_response function to process requests.
When Called: Only once when Django starts.
-
__call__(self, request)
Purpose: Handles each HTTP request.
When Called: Every time a request is received.
Before View: Modify or validate the request object.
Call View: Pass the request to the view using get_response.
After View: Modify or validate the response object.
Security Practices in Django
CSRF Protection:
- Use
{% csrf_token %}
in HTML forms to prevent CSRF attacks.
XSS Prevention:
- Django auto-escapes HTML in templates by default.
SQL Injection Prevention:
- Use Django ORM instead of raw SQL queries.
- For raw SQL, use parameterized queries to prevent injection.
HTTP Security Headers:
- X-Frame-Options: Prevents clickjacking.
X_FRAME_OPTIONS = 'DENY'
- Content-Security-Policy: Restricts resource loading.
Password Security:
- Use make_password and check_password for secure password handling.
- Django’s authentication system handles hashing and salting.
HTTPS and Secure Cookies:
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
- Enforces HTTPS for cookies and redirects.
Top comments (0)