project Web 应⽤程序
Django ⼊门
1.创建网页:学习笔记主页
2.创建其他网页
创建网页:学习笔记主页
映射 URL
from django.urls import path, include
path('', include('learning_logs.urls')),
"""定义 learning_logs 的 URL 模式"""
from django.urls import path
from . import views
app_name = 'learning_logs'
urlpatterns = [
# 主⻚
path('', views.index, name='index'),
]
编写视图
def index(request):
# 添加为主⻚编写视图的代码
"""学习笔记的主⻚"""
return render(request, 'learning_logs/index.html')
编写模板
<p>Learning Log</p>
<p>Learning Log helps you keep track of your learning, for any topic
you're
interested in.</p>
创建其他⽹⻚
模板继承
01. ⽗模板
<p>
<a href="{% url 'learning_logs:index' %}">Learning Log</a>
</p>
{% block content %}{% endblock content %}
02. ⼦模板
{% extends 'learning_logs/base.html' %}
{% block content %}
<p>Learning Log helps you keep track of your learning, for any topic
you're
interested in.</p>
{% endblock content %}
显⽰所有主题的⻚⾯
01. URL 模式
# 显⽰所有主题的页面
path('topics/', views.topics, name='topics'),
02. 视图
from .models import Topic
def topics(request):
"""显⽰所有的主题"""
topics = Topic.objects.order_by('date_added') # 查询数据库:请求提供 Topic 对象,并根据属性 date_added 进⾏排序
context = {'topics': topics} # 定义⼀个将发送给模板的上下⽂,上下⽂(context)是⼀个字典
return render(request, 'learning_logs/topics.html', context)
03. 模板
{% 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 %}
<a href="{% url 'learning_logs:index' %}">Learning Log</a> -
<a href="{% url 'learning_logs:topics' %}">Topics</a>
显⽰特定主题的⻚⾯
01. URL 模式
# 特定主题的详细⻚⾯
path('topics/<int:topic_id>/', views.topic, name='topic'),
02. 视图
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)
03. 模板
{% extends 'learning_logs/base.html' %}
{% block content %}
<p>Topic: {{ topic.text }}</p>
<p>Entries:</p>
<ul>
{% for entry in entries %}
<li>
<p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{ entry.text|linebreaks }}</p>
</li>
{% empty %}
<li>There are no entries for this topic yet.</li>
{% endfor %}
</ul>
{% endblock content %}
04. 将显⽰所有主题的⻚⾯中的每个主题都设置为链接
{% extends 'learning_logs/base.html' %}
{% block content %}
<p>Topic: {{ topic.text }}</p>
<p>Entries:</p>
<ul>
{% for topic in topics %}
<li>
<a href="{% url 'learning_logs:topic' topic.id %}">
{{ topic.text }}</a>
</li>
{% empty %}
<li>No topics have been added yet.</li>
{% endfor %}
{% for entry in entries %}
<li>
<p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
<p>{{ entry.text|linebreaks }}</p>
</li>
{% empty %}
<li>There are no entries for this topic yet.</li>
{% endfor %}
</ul>
{% endblock content %}