{"id":75722,"date":"2020-01-20T11:52:26","date_gmt":"2020-01-20T06:22:26","guid":{"rendered":"https:\/\/www.vskills.in\/certification\/tutorial\/?p=75722"},"modified":"2024-04-12T14:17:15","modified_gmt":"2024-04-12T08:47:15","slug":"requestcontext-and-context-processors-2","status":"publish","type":"page","link":"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/","title":{"rendered":"RequestContext and Context Processors"},"content":{"rendered":"<p>When rendering a template, you need a context. This can be an instance of django.template.Context, but Django also comes with a subclass, django.template.RequestContext, that acts slightly differently.<\/p>\n<p>RequestContext adds a bunch of variables to your template context by default \u2013 things like the HttpRequest object or information about the currently logged-in user.<\/p>\n<p>The render() shortcut creates a RequestContext unless it\u2019s passed a different context instance explicitly. For example, consider these two views:<\/p>\n<p>from django.template import loader, Context<\/p>\n<p>def view_1(request):<br>\n# &#8230;<br>\nt = loader.get_template(&#8216;template1.html&#8217;)<br>\nc = Context({<br>\n&#8216;app&#8217;: &#8216;My app&#8217;,<br>\n&#8216;user&#8217;: request.user,<br>\n&#8216;ip_address&#8217;: request.META[&#8216;REMOTE_ADDR&#8217;],<br>\n&#8216;message&#8217;: &#8216;I am view 1.&#8217;<br>\n})<br>\nreturn t.render(c)<\/p>\n<p>def view_2(request):<br>\n# &#8230;<br>\nt = loader.get_template(&#8216;template2.html&#8217;)<br>\nc = Context({<br>\n&#8216;app&#8217;: &#8216;My app&#8217;,<br>\n&#8216;user&#8217;: request.user,<br>\n&#8216;ip_address&#8217;: request.META[&#8216;REMOTE_ADDR&#8217;],<br>\n&#8216;message&#8217;: &#8216;I am the second view.&#8217;<br>\n})<br>\nreturn t.render(c)<\/p>\n<p>(Note that I\u2019m deliberately not using the render() shortcut in these examples \u2013 we\u2019re manually loading the templates, constructing the context objects and rendering the templates. I\u2019m \u201cspelling out\u201d all of the steps for the purpose of clarity.)<\/p>\n<p>Each view passes the same three variables \u2013 app, user and ip_address \u2013 to its template. Wouldn\u2019t it be nice if we could remove that redundancy? RequestContext and context processors were created to solve this problem. Context processors let you specify a number of variables that get set in each context automatically \u2013 without you having to specify the variables in each render() call.<\/p>\n<p>The catch is that you have to use RequestContext instead of Context when you render a template. The most low-level way of using context processors is to create some processors and pass them to RequestContext. Here\u2019s how the above example could be written with context processors:<\/p>\n<p>from django.template import loader, RequestContext<\/p>\n<p>def custom_proc(request):<br>\n# A context processor that provides &#8216;app&#8217;, &#8216;user&#8217; and &#8216;ip_address&#8217;.<br>\nreturn {<br>\n&#8216;app&#8217;: &#8216;My app&#8217;,<br>\n&#8216;user&#8217;: request.user,<br>\n&#8216;ip_address&#8217;: request.META[&#8216;REMOTE_ADDR&#8217;]\n}<\/p>\n<p>def view_1(request):<br>\n# &#8230;<br>\nt = loader.get_template(&#8216;template1.html&#8217;)<br>\nc = RequestContext(request,<br>\n{&#8216;message&#8217;: &#8216;I am view 1.&#8217;},<br>\nprocessors=[custom_proc])<br>\nreturn t.render(c)<\/p>\n<p>def view_2(request):<br>\n# &#8230;<br>\nt = loader.get_template(&#8216;template2.html&#8217;)<br>\nc = RequestContext(request,<br>\n{&#8216;message&#8217;: &#8216;I am the second view.&#8217;},<br>\nprocessors=[custom_proc])<br>\nreturn t.render(c)<\/p>\n<p>Let\u2019s step through this code:<\/p>\n<ul>\n<li>First, we define a function custom_proc. This is a context processor \u2013 it takes an HttpRequest object and returns a dictionary of variables to use in the template context. That\u2019s all it does.<\/li>\n<li>We\u2019ve changed the two view functions to use RequestContext instead of Context. There are two differences in how the context is constructed. One, RequestContext requires the first argument to be an HttpRequest object \u2013 the one that was passed into the view function in the first place (request). Two, RequestContext takes an optional processors argument, which is a list or tuple of context processor functions to use. Here, we pass in custom_proc, the custom processor we defined above.<\/li>\n<li>Each view no longer has to include app, user or ip_address in its context construction, because those are provided by custom_proc.<\/li>\n<li>Each view still has the flexibility to introduce any custom template variables it might need. In this example, the message template variable is set differently in each view.<\/li>\n<li>The render() shortcut, which saves you from having to call loader.get_template(), then create a Context, then call the render() method on the template.<\/li>\n<\/ul>\n<p>In order to demonstrate the lower-level workings of context processors, the above examples didn\u2019t use render(). But it\u2019s possible \u2013 and preferable \u2013 to use context processors with render(). Do this with the context_instance argument, like so:<\/p>\n<p>from django.shortcuts import render<br>\nfrom django.template import RequestContext<\/p>\n<p>def custom_proc(request):<br>\n# A context processor that provides &#8216;app&#8217;, &#8216;user&#8217; and &#8216;ip_address&#8217;.<br>\nreturn {<br>\n&#8216;app&#8217;: &#8216;My app&#8217;,<br>\n&#8216;user&#8217;: request.user,<br>\n&#8216;ip_address&#8217;: request.META[&#8216;REMOTE_ADDR&#8217;]\n}<\/p>\n<p>def view_1(request):<br>\n# &#8230;<br>\nreturn render(request, &#8216;template1.html&#8217;,<br>\n{&#8216;message&#8217;: &#8216;I am view 1.&#8217;},<br>\ncontext_instance=RequestContext(<br>\nrequest, processors=[custom_proc]\n)<br>\n)<\/p>\n<p>def view_2(request):<br>\n# &#8230;<br>\nreturn render(request, &#8216;template2.html&#8217;,<br>\n{&#8216;message&#8217;: &#8216;I am the second view.&#8217;},<br>\ncontext_instance=RequestContext(<br>\nrequest, processors=[custom_proc]\n)<br>\n)<\/p>\n<p>Here, we\u2019ve trimmed down each view\u2019s template rendering code to a single (wrapped) line. This is an improvement, but, evaluating the conciseness of this code, we have to admit we\u2019re now almost overdosing on the other end of the spectrum. We\u2019ve removed redundancy in data (our template variables) at the cost of adding redundancy in code (in the processors call).<\/p>\n<p>Using context processors doesn\u2019t save you much typing if you have to type processors all the time. For that reason, Django provides support for global context processors. The context_processors setting (in your settings.py) designates which context processors should always be applied to RequestContext. This removes the need to specify processors each time you use RequestContext.<\/p>\n<p>By default, context_processors is set to the following:<\/p>\n<p>&#8216;context_processors&#8217;: [<br>\n&#8216;django.template.context_processors.debug&#8217;,<br>\n&#8216;django.template.context_processors.request&#8217;,<br>\n&#8216;django.contrib.auth.context_processors.auth&#8217;,<br>\n&#8216;django.contrib.messages.context_processors.messages&#8217;,<br>\n],<\/p>\n<p>This setting is a list of callables that use the same interface as our custom_proc function above \u2013 functions that take a request object as their argument and return a dictionary of items to be merged into the context. Note that the values in context_processors are specified as strings, which means the processors are required to be somewhere on your Python path (so you can refer to them from the setting).<\/p>\n<p>Each processor is applied in order. That is, if one processor adds a variable to the context and a second processor adds a variable with the same name, the second will override the first. Django provides a number of simple context processors, including the ones that are enabled by default:<\/p>\n<p><strong>auth<\/strong><\/p>\n<p>django.contrib.auth.context_processors.auth<\/p>\n<p>If this processor is enabled, every RequestContext will contain these variables:<\/p>\n<ul>\n<li>user \u2013 An auth.User instance representing the currently logged-in user (or an AnonymousUser instance, if the client isn\u2019t logged in).<\/li>\n<li>perms \u2013 An instance of django.contrib.auth.context_processors.PermWrapper, representing the permissions that the currently logged-in user has.<br>\ndebug<br>\ndjango.template.context_processors.debug<br>\nIf this processor is enabled, every RequestContext will contain these two variables \u2013 but only if your DEBUG setting is set to True and the request\u2019s IP address (request.META[&#8216;REMOTE_ADDR&#8217;]) is in the INTERNAL_IPS setting:<\/li>\n<li><strong>debug<\/strong> \u2013 True. You can use this in templates to test whether you\u2019re in DEBUG mode.<\/li>\n<li>sql_queries \u2013 A list of {&#8216;sql&#8217;: &#8230;, &#8216;time&#8217;: &#8230;} dictionaries, representing every SQL query that has happened so far during the request and how long it took. The list is in order by query and lazily generated on access.<br>\ni18n<br>\ndjango.template.context_processors.i18n<\/li>\n<\/ul>\n<p>If this processor is enabled, every RequestContext will contain these two variables:<\/p>\n<ul>\n<li>LANGUAGES \u2013 The value of the LANGUAGES setting.<\/li>\n<li>LANGUAGE_CODE \u2013 request.LANGUAGE_CODE, if it exists. Otherwise, the value of the LANGUAGE_CODE setting.<br>\n<strong>media<\/strong><br>\ndjango.template.context_processors.media<br>\nIf this processor is enabled, every RequestContext will contain a variable MEDIA_URL, providing the value of the MEDIA_URL setting.<br>\n<strong>static<\/strong><br>\ndjango.template.context_processors.static<br>\nIf this processor is enabled, every RequestContext will contain a variable STATIC_URL, providing the value of the STATIC_URL setting.<br>\n<strong>csrf<\/strong><br>\ndjango.template.context_processors.csrf<br>\nThis processor adds a token that is needed by the csrf_token template tag for protection against cross site request forgeries.<br>\n<strong>request<\/strong><br>\ndjango.template.context_processors.request<\/li>\n<\/ul>\n<p>If this processor is enabled, every RequestContext will contain a variable request, which is the current HttpRequest.<\/p>\n<p><strong>messages<\/strong><\/p>\n<p>django.contrib.messages.context_processors.messages<\/p>\n<p>If this processor is enabled, every RequestContext will contain these two variables:<\/p>\n<ul>\n<li>messages \u2013 A list of messages (as strings) that have been set via the messages framework.<\/li>\n<li>DEFAULT_MESSAGE_LEVELS \u2013 A mapping of the message level names to their numeric value.<\/li>\n<\/ul>\n\n\n<p><a href=\"https:\/\/www.vskills.in\/certification\/tutorial\/certified-django-developer\/\" target=\"_blank\" rel=\"noreferrer noopener\">Back to Tutorial<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>When rendering a template, you need a context. This can be an instance of django.template.Context, but Django also comes with a subclass, django.template.RequestContext, that acts slightly differently. RequestContext adds a bunch of variables to your template context by default \u2013 things like the HttpRequest object or information about the currently logged-in user. The render() shortcut&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"categories":[8655],"tags":[2630],"class_list":["post-75722","page","type-page","status-publish","hentry","category-django-web-development","tag-requestcontext-and-context-processors"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>RequestContext and Context Processors - Tutorial<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"RequestContext and Context Processors - Tutorial\" \/>\n<meta property=\"og:description\" content=\"When rendering a template, you need a context. This can be an instance of django.template.Context, but Django also comes with a subclass, django.template.RequestContext, that acts slightly differently. RequestContext adds a bunch of variables to your template context by default \u2013 things like the HttpRequest object or information about the currently logged-in user. The render() shortcut...\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/\" \/>\n<meta property=\"og:site_name\" content=\"Tutorial\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/vskills.in\/\" \/>\n<meta property=\"article:modified_time\" content=\"2024-04-12T08:47:15+00:00\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"7 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/\",\"name\":\"RequestContext and Context Processors - Tutorial\",\"isPartOf\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\"},\"datePublished\":\"2020-01-20T06:22:26+00:00\",\"dateModified\":\"2024-04-12T08:47:15+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"RequestContext and Context Processors\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#website\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"name\":\"Tutorial\",\"description\":\"Vskills - A initiative in elearning and certification\",\"publisher\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#organization\",\"name\":\"Vskills\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"contentUrl\":\"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg\",\"width\":73,\"height\":55,\"caption\":\"Vskills\"},\"image\":{\"@id\":\"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/vskills.in\/\",\"https:\/\/x.com\/vskills_in\",\"https:\/\/www.linkedin.com\/company-beta\/1371554\/\",\"https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"RequestContext and Context Processors - Tutorial","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/","og_locale":"en_US","og_type":"article","og_title":"RequestContext and Context Processors - Tutorial","og_description":"When rendering a template, you need a context. This can be an instance of django.template.Context, but Django also comes with a subclass, django.template.RequestContext, that acts slightly differently. RequestContext adds a bunch of variables to your template context by default \u2013 things like the HttpRequest object or information about the currently logged-in user. The render() shortcut...","og_url":"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/","og_site_name":"Tutorial","article_publisher":"https:\/\/www.facebook.com\/vskills.in\/","article_modified_time":"2024-04-12T08:47:15+00:00","twitter_misc":{"Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/","name":"RequestContext and Context Processors - Tutorial","isPartOf":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website"},"datePublished":"2020-01-20T06:22:26+00:00","dateModified":"2024-04-12T08:47:15+00:00","breadcrumb":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/requestcontext-and-context-processors-2\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.vskills.in\/certification\/tutorial\/"},{"@type":"ListItem","position":2,"name":"RequestContext and Context Processors"}]},{"@type":"WebSite","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#website","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","name":"Tutorial","description":"Vskills - A initiative in elearning and certification","publisher":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.vskills.in\/certification\/tutorial\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#organization","name":"Vskills","url":"https:\/\/www.vskills.in\/certification\/tutorial\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/","url":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","contentUrl":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-content\/uploads\/2017\/07\/vskills-min-logo.jpg","width":73,"height":55,"caption":"Vskills"},"image":{"@id":"https:\/\/www.vskills.in\/certification\/tutorial\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/vskills.in\/","https:\/\/x.com\/vskills_in","https:\/\/www.linkedin.com\/company-beta\/1371554\/","https:\/\/www.youtube.com\/channel\/UCMWnscxPwRF_PqXo9B7q_Tw"]}]}},"_links":{"self":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75722","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/comments?post=75722"}],"version-history":[{"count":4,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75722\/revisions"}],"predecessor-version":[{"id":83365,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/pages\/75722\/revisions\/83365"}],"wp:attachment":[{"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/media?parent=75722"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/categories?post=75722"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vskills.in\/certification\/tutorial\/wp-json\/wp\/v2\/tags?post=75722"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}