The road to WeChat applet development (2) Django framework learning

The road to WeChat applet development (2) Application of Django framework learning template 1
We use django.http.HttpResponse() to output "Hello World!". This method mixes data with views, which does not conform to Django's MVC thinking.
I will introduce the application of Django templates in detail. A template is a text used to separate the presentation and content of the document.
Then the project in the previous chapter will create the templates directory under the HelloWorld directory and create the runoob.html file. The entire directory structure is as follows:

HelloWorld/
|-- HelloWorld
|   |-- __init__.py
|   |-- __init__.pyc
|   |-- settings.py
|   |-- settings.pyc
|   |-- urls.py
|   |-- urls.pyc
|   |-- views.py
|   |-- views.pyc
|   |-- wsgi.py
|   `-- wsgi.pyc
|-- manage.py
`-- templates
    `-- runoob.html

The code of the runoob.html file is as follows:
Insert picture description here
From the template, we know that the variable uses double brackets.
Next, we need to explain the path of the template file to Django, modify HelloWorld/settings.py, and modify the DIRS in TEMPLATES [os.path.join(BASE_DIR, 'templates')]as follows:
Modify the code
We now modify views.py to add a new object to submit data to the template:

from django.shortcuts import render
 
def runoob(request):
    context          = {
    
    }
    context['hello'] = 'Hello World!'
    return render(request, 'runoob.html', context)

Insert picture description here

from django.urls import path
 
from . import views
 
urlpatterns = [
    path('runoob/', views.runoob),
]

Insert picture description here
As you can see, we use render here to replace the HttpResponse used before. Render also uses a dictionary context as a parameter.
The key value hello of the element in the context dictionary corresponds to the variable { {hello }} in the template .
Visit http://127.0.0.1:8000/runoob again, you can see the page: It
Insert picture description here
means that an error 404 is reported, but why (it may be that you didn’t save it)
Insert picture description here
Modify the path. In the setting of this sentence, this sentence is Point to the "BASE_DIR/templates" folder to get the template. You can find that BASE_DIR is actually the Hello World folder on the first level, and templates are in the Hello World folder on the second level, so errors are always prompted. Note that BASE_DIR is the path where the manage.py file is located. In
Insert picture description here
Insert picture description here
this way, we have completed the use of templates to output data, thereby achieving separation of data and views.

Guess you like

Origin blog.csdn.net/xulei1132562/article/details/113550487