The input in the previous section is the return httpresponse () section in the view. The content in the function is <HTML> <body> ......
This means that front-end files must be written and printed every time, which is very troublesome. Generally, it includes many contents, such as JS files and CSS files. In addition, the design page is not easy to design, or it is well designed, and then paste the HTML string for output. HTML code and Python background Code are also mixed.
1. Custom,
Write data directly in the view. The newly created view (function) hello_who is as follows:
Def hello_who (request ):
T = template. template ('Hello {name }}')
C = template. Context ({'name': 'songjiang '})
Return httpresponse (T. Render (c ))
By creating a template, output hello, WHO
Here, who is named Song Jiang in Chinese ., If Chinese characters are displayed normally on the page, you need to set export age_code = 'zh-cn' in settings. py'
In the View File views. py, add # encoding = UTF-8 to the first line.
2. Use templates
Create a template file with any file name. The template file is the HTML foreground file. Similar to the ASPX page. Create a hello.html file first. As follows:
<HTML>
<Body>
<Div style = "color: red;"> <B> hello, {name }}</B> </div>
</Body>
</Html>
Load the template in the view and assign values to the variables.
Change the view hello_who:
Def hello_who (request ):
T = get_template('hello.html ')
Html = T. Render (context ({'name': 'songjiang '}))
Return httpresponse (HTML)
You can use a function to obtain the template and the rendering function, as shown below:
Def hello_who (request ):
Return render_to_response('hello.html ', {'name': 'songjiang '})
To use this function, you need to introduce:
From Django. Shortcuts import render_to_response
Return all defined mappings through locals ()
Def hello_who (request ):
Name = 'songjiang'
Return render_to_response('hello.html ', locals ())