# 昨日知識點回顧
? ? ? ? 創建主頁、繼承模版、顯示特定主題頁面? ? ? ??
# view.py
from django.shortcuts import render# 導入所需數據相關聯的模型
from .models import Topic# Create your views here.
def index(request):"""學習筆記的主頁"""# 傳遞兩個實參:對象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)def topic(request, topic_id):"""顯示單個主題"及所有的條目"""# get()獲得制定主題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)
? ? ? ? 修改后瀏覽器輸入網址localhost:8000/topics/2/顯示:
# 今日知識點學習
第19章 用戶賬號
19.1 讓用戶輸入數據
? ? ? ? 使用Django表單創建工具創建讓用戶能夠輸入數據的頁面
? ? ? ? 19.1.1 添加新主題
? ? ? ? ? ? ? ? 1.用于添加主題的表單
? ? ? ? ? ? ? ? ? ? ? ? 在Django中,創建表單最簡單的方式是使用ModelForm
# learning_log\learning_logsforms.py
from django import formsfrom .models import Topicclass TopicForm(forms.ModelForm):class Meta:model = Topicfields = ['text']labels = {'text': ''}
? ? ? ? ? ? ? ? 2.URL模式new_topic????????????????
"""定義learining——logs的URL模式。"""
# 為映射視圖,導入path
from django.urls import path
# 從當前文件夾引入view.py
from . import views
# app_name 區分同項目同名文件
app_name = 'learning_logs'# urlpatterns包含learning_logs中請求的頁面
urlpatterns = [# 主頁path('', views.index, name='index'),# 第一個幫助Django正確路由請求,空字符串與基礎URL匹配,第二個實參指定調用函數,第三個指定URL模式名稱指定為index# 顯示所有的主題path('topics/', views.topics, name='topics'),# 特定主題的詳細頁面path('topics/<int:topic_id>/', views.topic, name='topic'),# 用于添加新主題的頁面path('new_topic/', views.new_topic, name='new_topic')
]
? ? ? ? ? ? ? ? 3.視圖函數new_topic()
? ? ? ? ? ? ? ? ? ? ? ? 處理兩種情形:①剛進入new_topic頁面顯示空表單,②對提交的表單進行處理,將用戶重定向回topics
# view.py
from django.shortcuts import render# 導入所需數據相關聯的模型
from .models import Topic
from .forms import TopicForm# Create your views here.
def index(request):"""學習筆記的主頁"""# 傳遞兩個實參:對象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)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)def new_topic(request):"""添加新主題"""if request.method != 'POST':# 未提交數據:創建一個新表單form = TopicForm()else:# POST提交的數據:對數據進行處理form = TopicForm(data=request.POST)if form.is_valid():form.save()return redirect('learning_logs:topics')# 顯示空表單后指出表單數據無效context = {'form': form}return render(request, 'learning_logs/new_topic.html', context)
? ? ? ? ? ? ? ? ?4.GET請求和POST請求
? ? ? ? ? ? ? ? ? ? ? ? 創建Web應有程序時,用到的兩個主要請求類型GET請求和POST請求。
? ? ? ? ? ? ? ? ? ? ? ? 對于只是從服務器讀取數據的頁面,使用GET請求
? ? ? ? ? ? ? ? ? ? ? ? 在用戶需要通過表單提交信息時,通常使用POST請求
? ? ? ? ? ? ? ? 5.模版new_topic????????
# new_topic.html
{% extends "learning_logs/base.html" %}{% block content %}<p>Add a new topic:</p><form action="{% url 'learning_logs:new_topic' %}" method='post'>
# 防止攻擊者利用表單獲取服務器未經授權的訪問(這種攻擊成為跨站請求偽造){% csrf_token %}{{ form.as_p }}<button name="submit">Add topic</button> </form>{% endblock content %}
? ? ? ? ? ? ? ? 6.鏈接到頁面new_topic
# topics.html
{% extends "learning_logs/base.html" %}{% block content %}<p>Topics</p><ul>{% for topic in topics %}<li><a href =" {% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></li>{% empty %}<li>No topics have been added yet.</li>{% endfor %}</ul><a href="{% url 'learning_logs:new_topic' %}">Add a new topic</a>{% endblock content %}
?localhost:8000/new_topic/顯示:
? ? ? ? 19.1.2 添加新條目
? ? ? ? ? ? ? ? 1.用于添加新條目的表單????????????????
# forms.py
from django import formsfrom .models import Topic, Entryclass TopicForm(forms.ModelForm):class Meta:model = Topicfields = ['text']labels = {'text': ''}class EntryForm(forms.ModelForm):class Meta:model = Entryfields = ['text']labels = {'text': ' '}widgets = {'text': forms.Textarea(attrs={'cols': 80})}
?????????????????2.URL模式new_entry
"""定義learining——logs的URL模式。"""
# 為映射視圖,導入path
from django.urls import path
# 從當前文件夾引入view.py
from . import views
# app_name 區分同項目同名文件
app_name = 'learning_logs'# urlpatterns包含learning_logs中請求的頁面
urlpatterns = [# 主頁path('', views.index, name='index'),# 第一個幫助Django正確路由請求,空字符串與基礎URL匹配,第二個實參指定調用函數,第三個指定URL模式名稱指定為index# 顯示所有的主題path('topics/', views.topics, name='topics'),# 特定主題的詳細頁面path('topics/<int:topic_id>/', views.topic, name='topic'),# 用于添加新主題的頁面path('new_topic/', views.new_topic, name='new_topic'),# 用于添加新條目的頁面path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry')
]
? ? ? ? ? ? ? ??3.視圖函數new_entry()?
# view.py
from django.shortcuts import render, redirect# 導入所需數據相關聯的模型
from .models import Topic
from .forms import TopicForm, EntryForm# Create your views here.
def index(request):"""學習筆記的主頁"""# 傳遞兩個實參:對象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)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)def new_topic(request):"""添加新主題"""if request.method != 'POST':# 未提交數據:創建一個新表單form = TopicForm()else:# POST提交的數據:對數據進行處理form = TopicForm(data=request.POST)if form.is_valid():form.save()return redirect('learning_logs:topics')# 顯示空表單后指出表單數據無效context = {'form': form}return render(request, 'learning_logs/new_topic.html', context)def new_entry(request, topic_id):"""在特定主題中添加新條目"""topic = Topic.objects.get(id=topic_id)if request.method != 'POST':# 未提交數據:創建一個空表單form = EntryForm()else:# POST提交的數據:對數據進行處理form = EntryForm(data=request.POST)if form.is_valid():new_entry = form.save(commit=False)new_entry.topic = topicnew_entry.save()return redirect('learning_logs:topic', topic_id=topic_id)# 顯示空表單或支出表單數據無效context = {'topic': topic, 'form': form}return render(request, 'learning_logs/new_entry.html', context)
????????????????4.?模版new_entry
# new_entry.html
{% extends "learning_logs/base.html" %}{% block content %}<p><a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p><p>Add a new entry:</p><form action="{% url 'learning_logs:new_entry' topic.id %}" method='post'>{% csrf_token %}{{ form.as_p }}<button name="submit">Add entry</button> </form>{% endblock content %}
? ? ? ? ? ? ? ? 5.鏈接到頁面new_entry
# topic.html
{% extends 'learning_logs/base.html' %}{% block content %}<p>Topic: {{ topic }}</p><p>Entries:</p><p><a href="{% url 'learning_logs:new_entry' topic.id %}">Add new entry</a></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 %}
?????????????????????localhost:8000/new_entry/3/運行顯示:
?