7.再写一个页面
2022/1/9大约 1 分钟pythonweb框架
7.再写一个页面
再写一个页面重复一下配 URL 写 view 里的方法,及 Template 的过程。
加一个 urlpattern
learning_logs/urls.py
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^$', views.index, name='index'),
re_path(r'^index$', views.index, name='index'),
re_path(r'^topics$', views.topics, name='topics'),
]
这次就加了个 topics 的 path,映射到 views 模块里的 topics 方法,再给这个映射命名为 topics。
马上在 views.py 写一个 topics 方法跟上上面的调用!
from django.shortcuts import render
from .models import Topic
## Create your views here.
def index(request):
return render(request, 'learning_logs/index.html')
def topics(request):
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'learning_logs/topics.html', context)
继续继续,在 learning_logs/templates/learning_logs/ 下加一个 html 模板 topics.html
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Topics</p>
<ul>
{% for topic in topics %}
<li>{{ topic.text }}</li>
{% empty %}
<li>No topics have been added yet.</li>
{% endfor %}
</ul>
{% endblock content %}
重复一套下来,就应该理清了从 Django 项目里的 urls.py 开始,web 访问 path 到 html 模板的调用链路了。
我们再来看一下代码,views.topics return 的 render() 多了个上下文参数,这个上下文要求是个 dict ,其中的 key 会传递给 html 模板中的变量,而 key 的值就是数据模型的所有实例了,上下文承上启下地封装了数据模型实例作为了 render() 的第三个参数