Use a template in a view
We already have our own view in mysite. Views. py, which should be like this.
from django.http import HttpResponseimport datetimedef current_dt(request): now = datetime.datetime.now() html = "
Let me modify and use the template based on the content of Django TEMPLATE 1 and Django template 2.
I created a new view file named temp. py. The transformed code is as follows:
1 import datetime 2 from django.template import Template,Context 3 from django.http import HttpResponse 4 5 def current_datetime(request): 6 now = datetime.datetime.now() 7 t=Template(‘
The import module datetime is used to obtain the current time.
The template and context of Django. template are imported to call the template.
Do you still remember how to use it?
Write template, createTemplateObject, createContext, CallRender ()Method.
The httpresponse of Django. HTTP is imported to generate the final web page.
Do not forget to configure the access path in URLs. py. The following two statements will not be explained.
from temp import *
url(r‘^time/$‘,current_datetime),
Okay. Let's run it and try it.
We tried to add a filter to him. Modify this line.
t=Template(‘
So far, our website has used the template system, but it has not solved our problem. That is to say, the template is still embedded in Python code, data and performance are not truly separated. Next, let's place the template in a separate file and let the view load the file to solve this problem.