一、让用户可以输入信息
创建forms.py
创建基于表单的页面的方法几乎与前面创建网页一样:定义一个 URL ,编写一个视图函数并编写一个模板。一个主要差别是,需要导入包含表单 的模块forms.py 。
from django import forms from .models import Topic,Entry class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['text'] labels = {'text': ''} class EntryForm(forms.ModelForm): class Meta: model = Entry fields = ['text'] labels = {'text': ''} widgets = {'text': forms.Textarea(attrs={'cols': 80})}
将其添加到
learning_logs/urls.py中:
"""定义learning_logs的URL模式""" from django.urls import path #从当前的urls.py模块所在的文件夹中导入视图 from . import views #变量urlpatterns是一个列表,包含可在应用程序learning_logs中请求的网页 app_name = 'learning_logs' urlpatterns = [ #主页 #第一个是正则表达式,r让Python将接下来的字符串视为原始字符串,引号正则表达式始于和终于何处 #第二个实参指定了要调用的视图函数 #第三个实参将这个URL模式的名称指定为index path(r'',views.index,name='index'), # 显示所有的主题 path(r'topics/', views.topics, name='topics'), # 特定主题的详细页面 path(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic'), # 用于添加新主题的网页 path(r'^new_topic/$', views.new_topic, name='new_topic'), # 用于添加新条目的页面 path(r'^new_entry/(?P<topic_id>\d+)/$', views.new_entry, name='new_entry'), # 用于编辑条目的页面 path(r'^edit_entry/(?P<entry_id>\d+)/$', views.edit_entry,name='edit_entry'), ]
增加视图函数
learning_logs/views.py
from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from .models import Topic, Entry from .forms import TopicForm, EntryForm # 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) 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(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('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 = topic new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) def edit_entry(request, entry_id): """编辑既有条目""" entry = Entry.objects.get(id=entry_id) topic = entry.topic if request.method != 'POST': # 初次请求,使用当前条目填充表单 form = EntryForm(instance=entry) else: # POST提交的数据,对数据进行处理 form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic.id])) context = {'entry': entry, 'topic': topic, 'form': form} return render(request, 'learning_logs/edit_entry.html', context)
二、创建模板
新增三个模板
edit_entry.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% extends "learning_logs/base.html" %} {% block content %} <p><a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p> <p>Edit entry:</p> <form action="{% url 'learning_logs:edit_entry' entry.id %}" method='post'> {% csrf_token %} {{ form.as_p }} <button name="submit">save changes</button> </form> {% endblock content %} </body> </html>
new_entry.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% 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 %} </body> </html>
new_topic.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% 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 %} </body> </html>
在页面topics 中添加它们的链接:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Topics</title> </head> <body> {% 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 %} </body> </html>
在页面topic中添加它们的链接:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% 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> <p> <a href="{% url 'learning_logs:edit_entry' entry.id %}">edit entry</a> </p> </li> {% empty %} <li> There are no entries for this topic yet. </li> {% endfor %} {% endblock content %} </ul> </body> </html>
三、运行效果
点击Topics
点击Add a new topic,可以增加Topic
返回结果:
点击Chess
再点击增加new nentry,输入信息,点击添加
返回结果:
点击edit entry,修改内容
如图:输入修改的信息,点击save changes 保存修改
返回结果: