Django study notes (2) --- HTML template

Life is too short~ 

Tips: Only applicable to Python 3+ (not much difference anyway, py2 can also be changed). Because according to the father of Python, Guido van Rossum, the official support for Python 2 will be stopped in 2020, so if you are still using Python 2, you should prepare early. After all, it is not satisfactory to use without official support.

 

1. Create a template directory

Create a folder templates in our project  HelloDjango directory

 

2. Set the template path

Open the  folder HelloDjango in the HelloDjango directory of our project, find and open the file settings.py, find the DIRS in TEMPLATES, and modify the following red content:

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',
            ],
        },
    },
]

 

3. Add a template

Create our template index.html file under the templates directory we created with the following contents:

<!DOCTYPE html>
<html>
<head>
    <title>HelloDjango</title>
</head>
<body>
    <a href="/mydjango/index/">Index</a><hr />
    <h3>HelloDjango</h3>
    动态数据:<strong>{{ mydata }}</strong>
</body>
</html>

 

4. Modify the view function

Open the /mydjango/views.py file in the application, and modify the hello view function in study note 1. The modification is as follows:

def hello(request):
    data = { 'mydata':'哇~ This is Return MSG' }
    return render(request, 'index.html', data)

Among them, mydata and {{mydata}} in the html template correspond to each other, which is the data that needs to be echoed


5. Results

Open the service python manage.py runserver and enter the URL  http://127.0.0.1:8000/mydjango/hello/ to access:

~ I learn Python

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325345410&siteId=291194637