复习django项目三——视图显示模板templates

1.在项目根目录创建templates文件夹,并在setting里设置模板路径DIR

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(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',
            ],
        },
    },
]

2.打开文件:mysite/templates/myapp/index.html

{% if user_list %}
    <ul>
    {% for user in user_list %}
        <li><a href="/myapp/{{ user.id }}/">{{ user.phone }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No user are available.</p>
{% endif %}

3.打开视图myapp/views.py来导入模板
方法一

from django.http import HttpResponse
from django.template import loader
from .models import User
def index(request):
    user_list = User.objects.order_by('name')  #按name排序
    template = loader.get_template('myapp/index.html')
    context = {
        'user_list': user_list,
    }
    return HttpResponse(template.render(context, request))

方法二

from django.shortcuts import render
from .models import User
def index(request):
    user_list = User.objects.order_by('name')
    context = {'user_list': user_list}
    return render(request, 'myapp/index.html', context)

4.管理静态文件
(1)在settings 文件中定义静态内容

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

(2)在项目根目录下创建static目录,再创建当前应用名称的目录

mysite/static/myapp/

(3)在模板中可以使用硬编码

<img src="/static/myapp/myexample.jpg" alt="My image"/>

在模板中可以使用static编码

{% load static from staticfiles %}
<img src="{% static 'myapp/myexample.jpg' %}" alt="My image"/>

猜你喜欢

转载自blog.csdn.net/lazybones_3/article/details/79586113
今日推荐