第十九章 用户交互
一、添加新主题
创建基于表单的页面的方法几乎与前面创建网页一样:定义URL;编写一个视图函数并编写模板,一个主要差别是,需要导入包含表单的模块。
from django import forms
from .models import Topic,Entry
#新增主题form
class TopicForm(forms.ModelForm):
class Meta:
model = Topic
fields = ['text']
labels = {'text':''}
#新增条目form
class EntryForm(forms.ModelForm):
class Meta:
model = Entry
fields = ['text']
labels = {'text':''}
widgets = {'text':forms.Textarea(attrs={'cols':80})}
最简单的ModelForm版本只包含一个内嵌的Meta类,它告诉Django根所哪个模型创建表单,以及在表单中包含哪些字段。
视图函数
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from .forms import TopicForm,EntryForm
def new_topic(request):
if request.method != 'POST':
form = TopicForm()
else:
form = TopicForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('learning_logs/topics.html'))
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:
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)
GET:从服务器读取数据的页面,POST:用户提交表单信息;is_valid():核对是否填写了所有必不可少的字段,且输入的数据与要求的字段类型是否一致;save():将表单数据写入数据库,
commit=False
让Django创建一个新条目,reverse():把实参转换成URL,列表args,包含URL中的所有实参;HttpResponseRedirect():将浏览器重定向
创建新增主题模板
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Add New Topic:</p>
<form action="{% url 'learning_logs:new_topic' %}" method='post'>
{% csrf_token %}
{{ form.as_p}}
<button name="submit">add topic</button>
</form>
</ul>
{% endblock content%}
{% csrf_token %}:防止攻击者利用表单来获得对服务器未经过授权的访问(这种攻击被称跨站请求) ;{{ form.as_p}}:让Django自动创建显示表单的全部字段,
as_p
让Django以段落格式渲染所有表单元素
二、编辑条目
def edit_entry(request,entry_id):
entry = Entry.objects.get(id=entry_id)
if request.method != 'POST':
form = EntryForm(instance=entry)
else:
form = EntryForm(instance=entry,data=request.POST)
if form.is_valid():
form.save(commit=False)
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)
instance=entry:创建一个表单,并使用既有对象中的数据 填充;POST时,
instance=entry
和data=request.POST
使Django根据即有对像创建表单实例,并根所request.POST
中的相关数据进行修改
编辑模板
{% 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>
</ul>
{% endblock content%}
三、建立应用程users
1、建立应用:
python manage.py startapp users
2、在settings.py增加users
3、在learning_log下urls.py增加
path(r'^users/',include(('users.urls','users'),namespace='users')),
4、在users目录下建立urls.py
from django.conf.urls import url
from django.contrib.auth.views import login
from . import views
urlpatterns = [
#匹配 http://localhost:8000/users/login/
url(r'^login/$',login,{'template_name':'users/login.html'}),name='login'),
]
URL中users让Django在users/urls.py中查找,login将请求发送给默认视图login,{'template_name':'users/login.html'})告诉Django去哪里查找模板
5、建立login.html模板
在目录users\templates\users
下新建login.html
{% extends "learning_logs/base.html" %}
{% block content %}
{% if form.errors %}
<p>Your name and password didn't match.Please try again</p>
{% endif %}
<form method="post" action="{% url 'users:login' %}">
{% csrf_token %}
{{ form.as_p}}
<button name="submit">login</button>
<input type="hidden" name="next" value="{% url 'learning_logs:index' %}" />
</form>
{% endblock content %}
login.html
继承base.html
,一个应用程序中的模板可继承另一个应用程序中的模板。
form.errors:表示表单是否有错误
<input type="hidden" name="next" value="{% url 'learning_logs:index' %}" />
:表示登录成功后要跳转的网页
6、登出logout, 在ulrs.py
中加入url(r'^logout/$', views.logout_view, name='logout'),
,在view.py
中加入
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth import logout
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse('learning_logs:index'))
7、注册页面,在urls.py
中加url(r'^resgister/$',views.resgister,name='resgister'),
,在view.py
增加resgister()
def resgister(request):
if request.method != 'POST':
form = UserCreationForm()
else:
form = UserCreationForm(request.POST)
if form.is_valid():
new_user = form.save()
authenticated_user = authenticate(username=new_user.username,
password=request.POST['password1'])
login(requst,authenticated_user)
return HttpResponseRedirect(reverse('learning_logs:index'))
context = {'form':form}
return render(request,'user/resgister.html',context)
authenticate()*:接收用户名和密码,返一个通过身份验证的对象authenticated_user
login():接收requst
和authenticated_user
,为新用户创建有效会话
8、注册模板resgister.html
{% extends "learning_logs/base.html" %}
{% block content%}
<form method='post' action="{% url 'users:register' %}">
{% csrf_token %}
{{form.as_p}}
<button name='submit'>register</button>
<input type="hidden" name="next" value="{% url 'learning_logs:index'%}" />
</form>
{% endblock content %}
9、让用户拥有自己的数据
装饰器(decorator)是放在函数定义前面的指令,Python在函数运行前,根据它来修改函数的行为。
@login_required:只允许已登录的用户访问。
10、将数据与用户关联
查看用户
python manage.py shell
>>>from django.contrib.auth.models import User
>>>User.objects.all()
<QuerySet [<User:admin>,<User:jimmy>]>
迁移数据库
python manage.py makemigration learning_logs
You are trying to add a non-nullable field 'owner' to topic without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
- Provide a one-off default now (will be set on all existing rows)
提供默认值
- Quit, and let me add a default in models.py
退出在Model中添加默认值
Select an option: 1
Please enter the default value now, as valid Python The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now()
>>>1
Migrations for 'learning_logs':
0003_topic_owner.py:
Add field owner to topic
应用迁移python manage.py migrate
你可重置数据库而不是迁移,但是这样做,会丢失所有数据。如果需要一个全新的数据库,可以使用命令python manage.py flush重建数据库结构。
10、限制用户行为
#views.py
#def topics(request):
#只显示当前用户主题
topics = Topic.objects.filter(owner=request.user).order_by('date_added')
#def topic(request,topic_id):
#保护用主题,因为任何已登录的用户都可以输入URL(http://localhost:8000/topics/1/)地址来访问页面
if topic.owner != request.user:
raise Http404
#保护编辑条目页面
#def edit_entry(request,entry_id):
if topic.owner != request.user:
raise Http404