Django part3
视图(views)
视图是Django应用程序中的一种“类型”网页,通常用于特定功能并具有特定模板。
在我们的投票应用程序(polls)中,我们将有以下四个视图:
Question “index” page – 显示最近几个问题。
Question “detail” page – 显示问题文本,没有结果,但有一个要投票的表单。
Question “results” page – 显示特定问题的结果。
Vote action – 处理对特定问题中特定选择的投票。
文件结构
polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.http import Http404
from .models import Question
from django.template import loader
# Create your views here.
# Django模板使用 https://docs.djangoproject.com/en/2.2/topics/templates/
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 HttpResponse(template.render(context, request))
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})
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
polls.urls
from django.urls import path
from . import views
app_name = 'polls'
# 增加命名空间,区分url
urlpatterns = [
path('', views.index, name='index'),
# 获取最新的问题,默认作为初始页
path('<int:question_id>/', views.detail, name='detail'),
# 获取某个问题的详情页
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
polls/templates/polls/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>polls</title>
</head>
<body>
{% 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 %}
</body>
</html>
polls/templates/polls/detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>polls 详情页</title>
</head>
<body>
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
</body>
</html>
运行项目
py manage.py runserver
运行截图
点击后
参考博客
Django表单
Django传值
用python专业版创建Django项目
Django创建一个应用项目
Django app2