1 让用户输入数据
1.1添加新主题:定义URL,编写视图函数并编写一个模板,导入包含表单form.py
1.用于添加主题的表单
使用ModelForm,创建forms.py,存储在models.py目录
from django import forms
from .models import Topic
class TopicForm(forms.ModelForm):
class Meta:
# 根据Topic创建表单
model = Topic
# 只包含字段text
fields = ['text']
# 不为字段text生成标签
labels = {'text': ''}
2.URL模式new_topic
添加到learning_logs/urls.py
#将请求交给视图函数new_topic
path('new_topic/',views.new_topic, name='new_topic'),
3.视图函数new_topic() 4.GET请求和POST请求
def new_topic(request):
'''添加新主题'''
# 确定请求方式如果不是POST,返回空表单
if request.method != 'POST':
# 创建实例,空列表
form = TopicForm()
else:
# POST提交的数据:对数据进行处理
# request.POST存储用户输入的数据
form = TopicForm(data=request.POST)
# 判断字段是否有效
if form.is_valid():
form.save()
# 保存后,使用redirect()将用户浏览器重定向到页面topics
# 在页面topics中将在主题列表中看到他刚输入的主题
return redirect('learning_logs:topics')
# 显示空表单或指出表单数据无效
context = {'form': form}
return render(request, 'learning_logs/new_topic.html', context)
5.模板new_topic 创建新模板new_topic.html
{% extends "learning_logs/base.html" %}
{% block content %}
Add a new topic:
#定义一个表单,实参action告诉服务器将提交的表单数据发送到哪里
#这里将它发回给视图函数new_topic(),POST请求提交数据
{% endblock content%}
6.链接到页面new_topic
topics.html
1.2添加新条目
1.用于添加新条目的表单
forms.py
from .models import Topic, Entry
~~~~~~
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ['text']
labels = {'text': ''}
#小部件widget是HTML表单元素,Textarea定制字段text输入小部件,宽度设置80列
widgets = {'text': forms.Textarea(attrs={'cols': 80})}
2.URL模式new_entry
path('new_entry/
匹配时,Django将请求和主题ID发送给函数new_entry()
3.视图函数views.py
from .forms import TopicForm, EntryForm
def new_entity(request, topic_id):
'''在特定主题中添加新条目'''
topic = Topic.objects.get(id=topic_id)
if request.method != 'POST':
form = EntryForm()
else:
form = EntryForm(data=request.POST)
if form.is_valid():
new_entry = form.save(commit=False)
new_entry.topic = topic
new_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
{% extends "learning_logs/base.html" %}
{% block content %}
Add a new entry:
{% endblock content %}
5.链接到页面new_entry
topic.html
Topic:{{ topic }}
Entries:
1.3编辑条目
1.URL模式edit_entry
urls.py
path('edit_entry/
2.视图函数edit_entry()
views.py
from .models import Topic, Entry # 导入所需数据相关联的模型
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:
form = EntryForm(instance=entry, data=request.POST)
if form.is_valid():
form.save()
return redirect('learning_logs:topic', topic_id=topic_id)
context = {'entry': entry, 'topic': topic, 'form': form}
return render(request, 'learning_logs/edit_entry.html', context)
3.模板edit_entry
{% extends "learning_logs/base.html" %}
{% block content %}
Edit entry:
{% endblock content %}
4.链接到页面edit_entry
topic.html
{{ entry.date_added|date:'M d, Y H:i' }}
{{ entry.text|linebreaks }}
放在日期和文本后面