Discussion on the parameter problem of django's render function

  • 2020-12-16 06:01:57
  • OfStack

hello. html file code is as follows:


HelloWorld/templates/hello.html  File code: 
<h1>{{ hello }}</h1>

HelloWorld/HelloWorld/ ES8en.py file code:


# -*- coding: utf-8 -*-
 
#from django.http import HttpResponse
from django.shortcuts import render
 
def hello(request):
 context   = {}
 context['hello'] = 'Hello World!'
 return render(request, 'hello.html', context)

The key value of the element in the ontext dictionary "hello" corresponds to the variable "{{hello}}" in the template.

Once you create an Template object, you can use context to pass data to it. 1 context is a collection of 1 variables and their values.

context is represented as the Context class in Django and in the ES26en.template module. Its constructor takes one optional argument: a dictionary-mapped variable and its value. Call the render() method of the Template object and pass context to populate the template:


>>> from django.template import Context, Template

>>> t = Template('My name is {{ name }}.')

>>> c = Context({'name': 'nowamagic'})

>>> t.render(c)

u'My name is nowamagic.'

One point we must point out is that t. render(c) returns a value of 1 Unicode object, not the normal Python string. You can tell the difference by u before the string. In the framework, Django 1 uses Unicode objects instead of regular strings. If you understand how convenient this is for you, be grateful as much as you can for Django's methodical work behind the scenes. If you don't understand what you're getting out of it, don't worry. Just be aware of Django's support for Unicode, which will make it easy for your application to handle a wide variety of character sets, not just the basic ES45en-ES46en English characters.

from django.shortcuts import render

The help documentation describes as follows:

render(request, template_name, context=None, content_type=None, status=None, using=None)

Returns a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments.

The effect of this method - combines a given template with a given context dictionary, and returns a rendered HttpResponse object.

In layman's terms, the contents of context are loaded into a file defined in templates and rendered in a browser.

Parameter explanation:

request: it's a fixed parameter, nothing to talk about.

template_name: The file defined in templates, pay attention to the pathname. For example, 'templates\polls\ index.html ', the parameter would be 'polls\ index.html'

context: To pass in data for rendering in the file, the default is dictionary format

content_type: The TYPE of MIME to use for the generated document. The default value is the DEFAULT_CONTENT_TYPE setting.

status: The response code for http, default is 200.

using: Name of the template engine used to load templates.


Related articles: