|
| 1 | +title: django.template.response SimpleTemplateResponse Example Code |
| 2 | +category: page |
| 3 | +slug: django-template-response-simpletemplateresponse-examples |
| 4 | +sortorder: 50192 |
| 5 | +toc: False |
| 6 | +sidebartitle: django.template.response SimpleTemplateResponse |
| 7 | +meta: Python open source example code for the SimpleTemplateResponse class in Django within django.template.response. |
| 8 | + |
| 9 | + |
| 10 | +[SimpleTemplateResponse](https://docs.djangoproject.com/en/stable/ref/template-response/#simpletemplateresponse-objects) |
| 11 | +([source code](https://github.com/django/django/blob/master/django/template/response.py)) |
| 12 | +is a class provided by [Django](/django.html) that retains context for the |
| 13 | +HTTP request that originated the call to a view. SimpleTemplateResponse |
| 14 | +is a superclass for the similar |
| 15 | +[TemplateResponse](/django-template-response-templateresponse-examples.html) |
| 16 | +class. It is useful for modifying a response before it is rendered, which |
| 17 | +cannot be done with a traditional static |
| 18 | +[HttpResponse](/django-http-httpresponse-examples.html) object. |
| 19 | + |
| 20 | + |
| 21 | +## Example 1 from django-cms |
| 22 | +[django-cms](https://github.com/divio/django-cms) |
| 23 | +([project website](https://www.django-cms.org/en/)) is a Python-based |
| 24 | +content management system (CMS) [library](https://pypi.org/project/django-cms/) |
| 25 | +for use with Django web apps that is open sourced under the |
| 26 | +[BSD 3-Clause "New"](https://github.com/divio/django-cms/blob/develop/LICENSE) |
| 27 | +license. |
| 28 | + |
| 29 | +[**django-cms / cms / admin / pageadmin.py**](https://github.com/divio/django-cms/blob/develop/cms/admin/pageadmin.py) |
| 30 | + |
| 31 | +```python |
| 32 | +# -*- coding: utf-8 -*- |
| 33 | +from collections import namedtuple |
| 34 | +import copy |
| 35 | +import json |
| 36 | +import sys |
| 37 | +import uuid |
| 38 | + |
| 39 | + |
| 40 | +import django |
| 41 | +from django.contrib.admin.helpers import AdminForm |
| 42 | +from django.conf import settings |
| 43 | +from django.conf.urls import url |
| 44 | +from django.contrib import admin, messages |
| 45 | +from django.contrib.admin.models import LogEntry, CHANGE |
| 46 | +from django.contrib.admin.options import IS_POPUP_VAR |
| 47 | +from django.contrib.admin.utils import get_deleted_objects |
| 48 | +from django.contrib.contenttypes.models import ContentType |
| 49 | +from django.contrib.sites.models import Site |
| 50 | +from django.core.exceptions import (ObjectDoesNotExist, |
| 51 | + PermissionDenied, ValidationError) |
| 52 | +from django.db import router, transaction |
| 53 | +from django.db.models import Q, Prefetch |
| 54 | +from django.http import ( |
| 55 | + HttpResponseRedirect, |
| 56 | + HttpResponse, |
| 57 | + Http404, |
| 58 | + HttpResponseBadRequest, |
| 59 | + HttpResponseForbidden, |
| 60 | +) |
| 61 | +from django.shortcuts import render, get_object_or_404 |
| 62 | +from django.template.defaultfilters import escape |
| 63 | +from django.template.loader import get_template |
| 64 | +~~from django.template.response import SimpleTemplateResponse, TemplateResponse |
| 65 | +from django.utils.encoding import force_text |
| 66 | +from django.utils.translation import ugettext, ugettext_lazy as _, get_language |
| 67 | +from django.utils.decorators import method_decorator |
| 68 | +from django.views.decorators.http import require_POST |
| 69 | +from django.http import QueryDict |
| 70 | + |
| 71 | + |
| 72 | +## ... source code abbreviated to get to SimpleTemplateResponse example ... |
| 73 | + |
| 74 | + |
| 75 | + def changelist_view(self, request, extra_context=None): |
| 76 | + from django.contrib.admin.views.main import ERROR_FLAG |
| 77 | + |
| 78 | + if not self.has_change_permission(request, obj=None): |
| 79 | + raise PermissionDenied |
| 80 | + |
| 81 | + if request.method == 'POST' and 'site' in request.POST: |
| 82 | + site_id = request.POST['site'] |
| 83 | + |
| 84 | + if site_id.isdigit() and Site.objects.filter(pk=site_id).exists(): |
| 85 | + request.session['cms_admin_site'] = site_id |
| 86 | + |
| 87 | + site = self.get_site(request) |
| 88 | + # Language may be present in the GET dictionary but empty |
| 89 | + language = request.GET.get('language', get_language()) |
| 90 | + |
| 91 | + if not language: |
| 92 | + language = get_language() |
| 93 | + |
| 94 | + query = request.GET.get('q', '') |
| 95 | + pages = self.get_queryset(request) |
| 96 | + pages, use_distinct = self.get_search_results(request, pages, query) |
| 97 | + |
| 98 | + changelist_form = self.changelist_form(request.GET) |
| 99 | + |
| 100 | + try: |
| 101 | + changelist_form.full_clean() |
| 102 | + pages = changelist_form.run_filters(pages) |
| 103 | + except (ValueError, ValidationError): |
| 104 | + # Wacky lookup parameters were given, so redirect to the main |
| 105 | + # changelist page, without parameters, and pass an 'invalid=1' |
| 106 | + # parameter via the query string. If wacky parameters were given |
| 107 | + # and the 'invalid=1' parameter was already in the query string, |
| 108 | + # something is screwed up with the database, so display an error |
| 109 | + # page. |
| 110 | +~~ if ERROR_FLAG in request.GET.keys(): |
| 111 | +~~ return SimpleTemplateResponse('admin/invalid_setup.html', { |
| 112 | +~~ 'title': _('Database error'), |
| 113 | +~~ }) |
| 114 | + return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1') |
| 115 | + |
| 116 | + if changelist_form.is_filtered(): |
| 117 | + pages = pages.prefetch_related( |
| 118 | + Prefetch( |
| 119 | + 'title_set', |
| 120 | + to_attr='filtered_translations', |
| 121 | + queryset=Title.objects.filter(language__in=get_language_list(site.pk)) |
| 122 | + ), |
| 123 | + ) |
| 124 | + pages = pages.distinct() if use_distinct else pages |
| 125 | + # Evaluates the queryset |
| 126 | + has_items = len(pages) >= 1 |
| 127 | + else: |
| 128 | + has_items = pages.exists() |
| 129 | + |
| 130 | + context = self.admin_site.each_context(request) |
| 131 | + context.update({ |
| 132 | + 'opts': self.model._meta, |
| 133 | + 'media': self.media, |
| 134 | + 'CMS_MEDIA_URL': get_cms_setting('MEDIA_URL'), |
| 135 | + 'CMS_PERMISSION': get_cms_setting('PERMISSION'), |
| 136 | + 'site_languages': get_language_list(site.pk), |
| 137 | + 'preview_language': language, |
| 138 | + 'changelist_form': changelist_form, |
| 139 | + 'cms_current_site': site, |
| 140 | + 'has_add_permission': self.has_add_permission(request), |
| 141 | + 'module_name': force_text(self.model._meta.verbose_name_plural), |
| 142 | + 'admin': self, |
| 143 | + 'tree': { |
| 144 | + 'site': site, |
| 145 | + 'sites': self.get_sites_for_user(request.user), |
| 146 | + 'query': query, |
| 147 | + 'is_filtered': changelist_form.is_filtered(), |
| 148 | + 'items': pages, |
| 149 | + 'has_items': has_items, |
| 150 | + }, |
| 151 | + }) |
| 152 | + context.update(extra_context or {}) |
| 153 | + request.current_app = self.admin_site.name |
| 154 | + return TemplateResponse(request, self.change_list_template, context) |
| 155 | + |
| 156 | + |
| 157 | +## ... source code continues with no further examples ... |
| 158 | +``` |
| 159 | + |
| 160 | + |
| 161 | +## Example 2 from django-debug-toolbar |
| 162 | +[django-debug-toolbar](https://github.com/jazzband/django-debug-toolbar) |
| 163 | +([project documentation](https://github.com/jazzband/django-debug-toolbar) |
| 164 | +and [PyPI page](https://pypi.org/project/django-debug-toolbar/)) |
| 165 | +grants a developer detailed request-response cycle information while |
| 166 | +developing a [Django](/django.html) web application. |
| 167 | +The code for django-debug-toolbar is |
| 168 | +[open source](https://github.com/jazzband/django-debug-toolbar/blob/master/LICENSE) |
| 169 | +and maintained by the developer community group known as |
| 170 | +[Jazzband](https://jazzband.co/). |
| 171 | + |
| 172 | +[**django-debug-toolbar / debug_toolbar / panels / redirects.py**](https://github.com/jazzband/django-debug-toolbar/blob/master/debug_toolbar/panels/redirects.py) |
| 173 | + |
| 174 | +```python |
| 175 | +~~from django.template.response import SimpleTemplateResponse |
| 176 | +from django.utils.translation import gettext_lazy as _ |
| 177 | + |
| 178 | +from debug_toolbar.panels import Panel |
| 179 | + |
| 180 | + |
| 181 | +class RedirectsPanel(Panel): |
| 182 | + """ |
| 183 | + Panel that intercepts redirects and displays a page with debug info. |
| 184 | + """ |
| 185 | + |
| 186 | + has_content = False |
| 187 | + |
| 188 | + nav_title = _("Intercept redirects") |
| 189 | + |
| 190 | + def process_request(self, request): |
| 191 | + response = super().process_request(request) |
| 192 | + if 300 <= int(response.status_code) < 400: |
| 193 | + redirect_to = response.get("Location", None) |
| 194 | + if redirect_to: |
| 195 | + status_line = "{} {}".format( |
| 196 | + response.status_code, response.reason_phrase |
| 197 | + ) |
| 198 | + cookies = response.cookies |
| 199 | +~~ context = {"redirect_to": redirect_to, "status_line": status_line} |
| 200 | +~~ # Using SimpleTemplateResponse avoids running global context processors. |
| 201 | +~~ response = SimpleTemplateResponse( |
| 202 | +~~ "debug_toolbar/redirect.html", context |
| 203 | +~~ ) |
| 204 | +~~ response.cookies = cookies |
| 205 | +~~ response.render() |
| 206 | +~~ return response |
| 207 | + |
| 208 | +``` |
| 209 | + |
| 210 | + |
0 commit comments