What is a context in Django?

一笑奈何 提交于 2019-11-27 03:20:19
Sid

When you use a Django Template, it is compiled once (and only once) and stored for future use, as an optimization. A template can have variable names in double curly braces, such as {{ myvar1 }} and {{ myvar2 }}.

A Context is a dictionary with variable names as the key and their values as the value. Hence, if your context for the above template looks like: {myvar1: 101, myvar2: 102}, when you pass this context to the template render method, {{ myvar1 }} would be replaced with 101 and {{ myvar2 }} with 102 in your template. This is a simplistic example, but really a Context object is the context in which the template is being rendered.

As for a ContextProcessor, that is a slightly advanced concept. You can have in your settings.py file listed a few Context Processors which take in an HttpRequest object and return a dictionary (similar to the Context object above). The dictionary (context) returned by the Context Processor is merged into the context passed in by you (the user) by Django.

A use case for a Context Processor is when you always want to insert certain variables inside your template (for example the location of the user could be a candidate). Instead of writing code to insert it in each view, you could simply write a context processor for it and add it to the TEMPLATE_CONTEXT_PROCESSORS settings in settings.py.

Hope this makes sense. Thanks for taking the class!

A context is a variable name -> variable value mapping that is passed to a template.

Context processors let you specify a number of variables that get set in each context automatically – without you having to specify the variables in each render() call.

sk1p

The Context is described quite well in the official documentation. In short:

  1. In day-to-day use, mostly indirectly, because helper functions construct the Context for you

  2. See 1.: you only need it if you use the low-level api

  3. No, a context processor is a function that takes a request and returns a dictionary of variables that are then available in all templates that are rendered with a RequestContext, for example:

    def get_stuff_from_session(request):
        return {'stuff': request.session['stuff']}
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!