In the previous section we used Django.http.HttpResponse () to output "Hello world! "。 This approach mixes data with views and does not conform to Django's MVC thinking.
In this section we will give you a detailed introduction to the application of the Django template, which is a text that separates the presentation and content of the document.
1. Enter the appropriate directory and create the project command as follows:
C:\windows\system32>f:
F:\>CD F:\python-work\DjangoDemos
F:\python-work\djangodemos>django-admin Startproject TestView
F:\python-work\djangodemos>
2. Create the view and configure the URL.
(1) Enter the subordinate directory where you just created the project, and create a home.py view file in the urls.py sibling directory. Write the following code:
#-*-Coding:utf-8-*-
#from django.http Import HttpResponse
From Django. Shortcuts import render
def index (Request):
Context = {}
context[ ' hello ' ]< Span class= "hl-code" > = ' hello world! "
return render(request, 'index.html', context)
(2) Configure this view URL address. Open urls.py and configure the following code:
From Django.conf.urls import URL
From Django.contrib Import admin
From. Import Home
Urlpatterns = [
URL (r ' ^admin/', admin.site.urls),
URL (r ' ^index$ ', Home.index),
]
3. Create the template and configure the template path.
(1) Enter the Create project root directory, create the folder "Templates" in the manage.py sibling directory, and then create a index.html page in templates with the following code:
(2) Enter the sub-directory of the project, locate the settings.py, set the template path, find the "DIRS" in the templates, set the template path value as follows:
TEMPLATES = [
{
' Backend ': ' Django.template.backends.django.DjangoTemplates ',
' DIRS ': [base_dir+ "/templates",],
' App_dirs ': True,
' OPTIONS ': {
' Context_processors ': [
' Django.template.context_processors.debug ',
' Django.template.context_processors.request ',
' Django.contrib.auth.context_processors.auth ',
' Django.contrib.messages.context_processors.messages ',
],
},
},
]
4. (3) Start the service.
Python-based Django templates