探索Django Tutorial:构建高效Web应用的向导
以下是Django Tutorial中创建一个问卷调查应用的核心函数示例:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Question, Choice
from django.urls import reverse
# 创建问卷
# 定义一个视图,用于显示最新的问题列表
def index(request):
latest_question_list = Question.objects.all().order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
# 显示问题详情
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
# 处理投票
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):
# 用户没有选择,重新显示投票表单
return render(request, 'polls/detail.html', {'question': question, 'error_message': "You didn't select a choice."})
else:
selected_choice.votes += 1
selected_choice.save()
# 使用HttpResponseRedirect确保用户在投票后不会刷新页面
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
# 显示投票结果
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
这段代码提供了创建、显示、处理投票和显示投票结果的功能。它使用了Django的ORM(Object-Relational Mapping)来简化数据库交互,并使用了Django的模板系统来动态生成网页。
评论已关闭