What is a context in Django?

后端 未结 3 978
闹比i
闹比i 2020-11-28 03:37

I\'m a django beginner so I\'m trying to understand the concept of context and context processor.

  • What is a context and why do you use it?
  • Is a conte
相关标签:
3条回答
  • 2020-11-28 04:22

    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!

    0 讨论(0)
  • 2020-11-28 04:30

    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']}
      
    0 讨论(0)
  • 2020-11-28 04:34

    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.

    0 讨论(0)
提交回复
热议问题