def footer(get_response): # Do one-time configuration and initialization here # this function is called for every view def middleware(request): # do required process before the view is called here response = get_response(request) # Call view and get response # Add copyright message at the end of output generated by view response.write("<p></p><hr/><div style='color:blue;text-align:center'>Copyright © Srikanth Technologies. All rights reserved.</div>") return response # return response object return middleware # return the function that is to be called to hook process
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'webdemo.footer_middleware.footer', ]
from django.shortcuts import render def about(request): return render(request, 'about.html')
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>About</title> </head> <body> <h1>About</h1> Using custom middleware! </body> </html>
from django.urls import path, include urlpatterns = [ path('demo/', include('demo.urls')), ]
from django.urls import path from . import views urlpatterns = [ path('about/', views.about), ]