Skip to content

Commit 3eae94a

Browse files
committed
adding new simpletemplatersponse django examples
1 parent fab4f2f commit 3eae94a

7 files changed

+253
-24
lines changed

content/pages/examples/django/django-http-response-httpresponsepermanentredirect.markdown renamed to content/pages/examples/django/django-http-httpresponsepermanentredirect-examples.markdown

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
title: django.http.responses HttpResponsePermanentRedirect Python Code Examples
1+
title: django.http HttpResponsePermanentRedirect Python Code Examples
22
category: page
3-
slug: django-http-responses-httpresponsepermanentredirect-examples
3+
slug: django-http-httpresponsepermanentredirect-examples
44
sortorder: 50057
55
toc: False
6-
sidebartitle: django.http.responses HttpResponsePermanentRedirect
7-
meta: Example code that shows you how to use the HttpResponsePermanentRedirect class from the django.http.response module.
6+
sidebartitle: django.http HttpResponsePermanentRedirect
7+
meta: Example code that shows you how to use the HttpResponsePermanentRedirect class from the django.http module.
88

99

1010
[HttpResponsePermanentRedirect](https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpResponsePermanentRedirect)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,210 @@
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+

content/pages/examples/django/django-template-response-templateresponse.markdown

+3-2
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,10 @@ meta: Python code examples for the TemplateResponse class that is part of Django
1010
[TemplateResponse](https://docs.djangoproject.com/en/stable/ref/template-response/)
1111
([source code](https://github.com/django/django/blob/master/django/template/response.py))
1212
is a class provided by [Django](/django.html) that retains context for the
13-
HTTP Request that caused the view to generate the response. TemplateResponse
13+
HTTP request that caused the view to generate the response. TemplateResponse
1414
is useful for modifying a response before it is rendered, which cannot be
15-
done with a traditional static HttpResponse object.
15+
done with a traditional static
16+
[HttpResponse](/django-http-httpresponse-examples.html) object.
1617

1718

1819
## Example 1 from django-cms

content/pages/meta/00-change-log.markdown

+1
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ on GitHub.
2828
* [django.http HttpResponseForbidden](/django-http-httpresponseforbidden-examples.html)
2929
* [django.http HttpResponseRedirect](/django-http-httpresponseredirect-examples.html)
3030
* [django.template.response TemplateResponse](/django-template-response-templateresponse-examples.html)
31+
* [django.template.response SimpleTemplateResponse](/django-template-response-simpletemplateresponse-examples.html)
3132
* [django.urls reverse_lazy](/django-urls-reverse-lazy-examples.html)
3233

3334
### August
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<meta http-equiv="refresh" content="0; url=https://www.fullstackpython.com/django-http-httpresponsepermanentredirect-examples.html">
5+
</head>
6+
<body>
7+
</body>
8+
</html>

theme/templates/css/toc.css

+1-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

theme/templates/table-of-contents.html

+26-17
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ <h4 class="bp"><a href="https://testdriven.io/courses/microservices-with-docker-
229229

230230
<h2>Example Python Code</h2>
231231
<div class="row">
232-
<div class="c6">
232+
<div class="c12">
233233
<h3 style="margin-top:16px"><a href="/django-code-examples.html">Django code examples</a></h3>
234234
<h4 class="bp"><a href="/django-apps-config-appconfig-examples.html">django.apps.config AppConfig</a></h4>
235235
<h4 class="bp"><a href="/django-conf-settings-examples.html">django.conf.settings</a></h4>
@@ -244,32 +244,41 @@ <h4 class="bp"><a href="/django-core-mail-send-mail-examples.html">django.core.m
244244
<h4 class="bp"><a href="/django-core-mail-messages-emailmessage-examples.html">django.core.mail.messages EmailMessage</a></h4>
245245
<h4 class="bp"><a href="/django-core-management-base-basecommand-examples.html">django.core.management.base BaseCommand</a></h4>
246246
<h4 class="bp"><a href="/django-db-operationalerror-examples.html">django.db OperationalError</a></h4>
247-
<h4 class="bp"><a href="/django-db-models-autofield-examples.html">django.db.models AutoField</a></h4>
248-
<h4 class="bp"><a href="/django-db-models-booleanfield-examples.html">django.db.models BooleanField</a></h4>
249-
<h4 class="bp"><a href="/django-db-models-charfield-examples.html">django.db.models CharField</a></h4>
250-
<h4 class="bp"><a href="/django-db-models-datefield-examples.html">django.db.models DateField</a></h4>
251-
<h4 class="bp"><a href="/django-db-models-datetimefield-examples.html">django.db.models DateTimeField</a></h4>
252-
<h4 class="bp"><a href="/django-db-models-integerfield-examples.html">django.db.models IntegerField</a></h4>
253-
<h4 class="bp"><a href="/django-db-models-model-examples.html">django.db.models Model</a></h4>
254-
<h4 class="bp"><a href="/django-db-models-textfield-examples.html">django.db.models TextField</a></h4>
247+
<h4 class="bp">django.db.models
248+
<a href="/django-db-models-autofield-examples.html">AutoField</a>,
249+
<a href="/django-db-models-booleanfield-examples.html">BooleanField</a>,
250+
<a href="/django-db-models-charfield-examples.html">CharField</a>,
251+
<a href="/django-db-models-datefield-examples.html">DateField</a>,
252+
<a href="/django-db-models-datetimefield-examples.html">DateTimeField</a>,
253+
<a href="/django-db-models-integerfield-examples.html">IntegerField</a>,
254+
<a href="/django-db-models-model-examples.html">Model</a>,
255+
<a href="/django-db-models-textfield-examples.html">TextField</a>
256+
</h4>
255257
<h4 class="bp"><a href="/django-db-models-signal-examples.html">django.db.models.signal</a></h4>
256258
<h4 class="bp"><a href="/django-dispatch-dispatcher-signal-examples.html">django.dispatch.dispatcher Signal</a></h4>
257259
<h4 class="bp"><a href="/django-forms-examples.html">django.forms</a></h4>
258-
<h4 class="bp"><a href="/django-http-http404-examples.html">django.http Http404</a></h4>
259-
<h4 class="bp"><a href="/django-http-httpresponse-examples.html">django.http HttpResponse</a></h4>
260-
<h4 class="bp"><a href="/django-http-httpresponsebadrequest-examples.html">django.http HttpResponseBadRequest</a></h4>
261-
<h4 class="bp"><a href="/django-http-httpresponseforbidden-examples.html">django.http HttpResponseForbidden</a></h4>
262-
<h4 class="bp"><a href="/django-http-responses-httpresponsepermanentredirect-examples.html">django.http HttpResponsePermanentRedirect</a></h4>
263-
<h4 class="bp"><a href="/django-http-httpresponseredirect-examples.html">django.http HttpResponseRedirect</a></h4>
260+
<h4 class="bp">django.http
261+
<a href="/django-http-httpresponse-examples.html">HttpResponse</a>
262+
<a href="/django-http-httpresponsebadrequest-examples.html">HttpResponseBadRequest</a>
263+
<a href="/django-http-httpresponseforbidden-examples.html">HttpResponseForbidden</a>,
264+
<a href="/django-http-http404-examples.html">Http404</a>,
265+
<a href="/django-http-httpresponsepermanentredirect-examples.html">HttpResponsePermanentRedirect</a>,
266+
<a href="/django-http-httpresponseredirect-examples.html">HttpResponseRedirect</a>
267+
</h4>
264268
<h4 class="bp"><a href="/django-urls-exceptions-noreversematch-examples.html">django.urls.exceptions NoReverseMatch</a></h4>
265269
<h4 class="bp"><a href="/django-urls-path-examples.html">django.urls.path</a></h4>
266270
<h4 class="bp"><a href="/django-urls-reverse-lazy-examples.html">django.urls reverse_lazy</a></h4>
267271
<h4 class="bp"><a href="/django-utils-html-format-html-examples.html">django.utils.html format_html</a></h4>
268-
<h4 class="bp"><a href="/django-template-response-templateresponse-examples.html">django.template.response TemplateResponse</a></h4>
272+
<h4 class="bp">django.template.response
273+
<a href="/django-template-response-simpletemplateresponse-examples.html">SimpleTemplateResponse</a>,
274+
<a href="/django-template-response-templateresponse-examples.html">TemplateResponse</a>
275+
</h4>
269276
<h4 class="bp"><a href="/django-utils-timezone-examples.html">django.utils.timezone</a></h4>
270277
</div>
278+
</div>
271279

272-
<div class="c6">
280+
<div class="row">
281+
<div class="c12">
273282
<h3 style="margin-top:16px"><a href="/flask-core-extensions-code-examples.html">Flask core and extensions examples</a></h3>
274283
<h4 class="bp"><a href="/flask-redirect-examples.html">flask redirect</a></h4>
275284
<h4 class="bp"><a href="/flask-request-examples.html">flask request</a></h4>

0 commit comments

Comments
 (0)