18.3 创建网页:学习笔记主页
使用Django创建网页的三个阶段:定义URL、编写视图和编写模版。
3.1 映射URL
打开learning_log中urls.py
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'',include('learning_logs.urls',namespace='learning_logs')),]
在learning_logs中定义urls.py
'''定义learning_logs的URL模式'''from Django.conf.urls import urlfrom . import viewsurlpatterns = [#主页url(r'^$',views.index,name='index'),]
3.2 编写视图
打开learning_logs中views.py
from django.shortcuts import render# Create your views here.def index(request): '学习笔记主页' return render(request,'learning_logs/index.html')
3.3 编写模版
在learning_logs中建立文件templates/learning_logs/index.html,写入代码:
Learning Log
Learning Log helps you keep track of your learning,for any topic you'relearning about.
18.4 创建其他网页
4.1 模版继承
1 父模版
在learning_logs中建立文件templates/learning_logs/base.html,写入代码:
{ % block content %}{% endblock content %}
2 子模版
重写index.html继承base.html
{% extends 'learning_logs/base.html' %}{ % block content %}Learning Log helps you keep track of your learning,for any topic you're learning about.
{ % endblock content %}
4.2 显示所有主题的页面
1 URL模式
修改learning_logs/urls.py:
url(r'^$',views.index,name='index'),#显示所有的主题url(r'^topics/$',views.topics,name='topics'),]
2 视图
views.py
from django.shortcuts import renderfrom .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)
3 模版
创建topics.html
{% extends 'learning_logs/base.html' %}{ % block content %}Topics
- { % for topic in topics %}
- { { topic }} { % empty %}
- No topics have been added yet. { % endfor %}
修改base.html
{ % block content %}{% endblock content %}
4.3 显示特定主题的页面
1.URL模式
修改learning_logs/urls.py:
#特定主题的详细页面url(r'^topics/(?P\d+)/$',views.topics,name='topics'),
2.视图
views.py
def topic(request,topic_id): '''显示单个主题及其所有的条目''' topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = { 'topic':topic,'entries':entries} return render(request,'learning_logs/topic.html',context)
3.模版
topic.html
{% extends 'learning_logs/base.html' %}{ % block content %}Topic:{
{ topic }}Entries
- { % for entry in entries %}
-
{
{ entry.date_added|date:'M d,Y H:i' }}{
{ entry.text|linebreaks}} { % empty %} - There are no entries for this topic yet. { % endfor %}
4.将显示所有主题的页面中的每个主题都设置为链接
topics.html
{% for topic in topics %}