9 django admin站点
D:workspace_pythonmysite>python manage.py createsuperuser
Username (leave blank to use 'administrator'): admin
Email address: loveyou.for.ever@163.com
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Password:yue123456
Password (again):
Superuser created successfully.
重启开发服务器
Python manage.py runserver
http://127.0.0.1/admin
在admin中注册投票应用
Polls/admin.py添加如下内容:
from polls import models
admin.site.register(models.Question)
admin.site.register(models.Choice)
10 编写更多的视图
Poll/views.py,添加如下内容:
'''
问卷详情
'''
def detail(request, question_id):
return HttpResponse('You are looking at question %s.'
% question_id)
'''
某个问卷的投票和调查结果
'''
def results(request, question_id):
response = ('You are looking at the results of question %s.')
return HttpResponse(response % question_id)
'''
投票动作页面
'''
def vote(request, question_id):
return HttpResponse('You ar voting on question %s.'
% question_id)
Polls/urls.py,添加如下内容:
url(r'^(?P<question_id>[0-9]+)/$',views.detail,name='detail'),
url(r'^(?P<question_id>[0-9]+)/results/$',views.results,name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'),
修改polls/views.py视图
'''
首页
'''
def index(request):
latest_question_list=Question.objects.order_by('-pub_date')[:5]
output=', '.join([q.question_text
for q in
latest_question_list])
return HttpResponse(output)
在polls目录下创建templates/polls目录,新建index.html,添加如下内容:
{% if latest_question_list
%}
<ul>
{% for question
in latest_question_list
%}
<li>
<a
href="/polls/{{
question.id
}}/">
{{ question.question_text
}}
</a>
</li>
{% endfor %}
</ul>
{% else %}
<p> No polls are available.
</p>
{% endif %}
修改视图页面
'''
首页
'''
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return render(request,
'polls/index.html', context)
# return HttpResponse(template.render(context, request))
10 添加404 错误页面
修改polls/views.py
'''
问卷详情
'''
def detail(request, question_id):
#方式一:
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request,
'polls/detail.html', {'question': question})
#方式二:
#question = get_object_or_404(Question, pk=question_id)
#return render(request, 'polls/detail.html', {'question': question})
11 使用模板系统
polls/templates/polls/detail.html
<h1>{{
question.question_text
}}</h1>
<ul>
{% for choice
in question.choice_set.all
%}
<li>{{
choice.choice_text
}}</li>
{% endfor %}</ul>
<h1>{{
question.question_text
}}</h1>
<ul>
{% for choice
in question.choice_set.all
%}
<li>{{
choice.choice_text
}}</li>
{% endfor %}
</ul>
12删除模板中硬编码的urls
polls/templates/polls/detail.html
{% if latest_question_list
%}
<ul>
{% for question
in latest_question_list
%}
<li>
{#硬编码#}
<a
href="/polls/{{
question.id
}}/">
{{ question.question_text
}}
</a>
{#可以使用urls.py中定认的别名 #}
<a
href="{%
url 'detail'
question.id
%}">
{{ question.question_text
}}
</a>
</li>
{% endfor %}
</ul>
{% else %}
<p> No polls are available.
</p>
{% endif %}
13 url names的命名空间
Urls.py中添加
app_name='polls'
页面中可以使用
{#可以使用urls.py中定认的命名空间 #}
<a
href="{%
url 'polls:detail'
question.id
%}">
{{ question.question_text
}}
</a>
14 简单的form表单
<h1>{{
question.question_text
}}</h1>
{% if error_message
%}
<p>
<strong>{{
error_message }}</strong>
</p>
{% endif %}
<form
action="{%
url 'polls:vote'
question.id
%}"
method="post">
{% csrf_token %}
{% for choice
in question.choice_set.all
%}
<input
type="radio"
name="choice"
id="choice{{
forloop.counter
}}"
value="{{
choice.id
}}"/>
<label
for="choice{{
forloop.counter
}}">{{
choice.choice_text
}}</label><br/>
{% endfor %}
<input
type="submit"
value="Vote"/>
</form>
修改views.py中的vote业务方法
'''
投票动作页面
'''
def vote(request, question_id):
#错误信息页面
question = get_object_or_404(Question,
pk=question_id)
try:
#取得投票信息
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# 发生choice未找到异常时,重新返回表单页面,并给出提示信息
return
render(request, 'polls/detail.html', {'question': question,'error_message':
"You didn't select a choice.",})
else:
selected_choice.votes += 1#修改投票数
selected_choice.save()#保存至数据库
#
成功处理数据后,自动跳转到结果页面,防止用户连续多次提交。
return
HttpResponseRedirect(reverse('polls:results',
args=(question.id,)))
修改results业务方法
'''
某个问卷的投票和调查结果
'''
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request,
'polls/results.html', {'question': question})
在polls/templates/polls/results.html
<h1>{{
question.question_text
}}</h1>
<ul>
{% for choice
in question.choice_set.all
%}
<li>
{{ choice.choice_text
}} -- {{ choice.votes
}} vote{{ choice.votes|pluralize
}}
</li>
{% endfor %}
</ul>
<a
href="{%
url 'polls:detail'
question.id
%}">Vote again?</a>
15 使用泛型视图
Polls/urls.p文件内容如下:
from django.conf.urls
import url
from . import
views
app_name = 'polls'
urlpatterns = [
#url(r'^$', views.index, name='index'),
#url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
#url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
#使用泛型模板
url(r'^$', views.IndexView.as_view(),
name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(),
name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$', views.ResultsView.as_view(),
name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote,
name='vote'),
]
'''
泛型视图
'''
'''
首页
'''
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name =
'latest_question_list'
#最近的5个调查问卷
def
get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
'''
问卷详情
'''
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
'''
某个问卷的投票和调查结果
'''
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'