Django实现投票功能

时间: 2023-06-15 07:04:35 浏览: 67
在 Django 中实现投票功能的步骤如下: 1. 创建一个投票应用程序,可以使用 `python manage.py startapp polls` 命令来创建。 2. 在应用程序的 `models.py` 文件中定义投票模型。例如,一个投票模型可以包含问题(question)和选项(choice)两个字段。可以使用以下代码: ```python from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) ``` 3. 在 `settings.py` 文件中将应用程序添加到 `INSTALLED_APPS` 列表中。 4. 在应用程序的 `views.py` 文件中创建视图函数。例如,可以创建一个视图函数来显示所有问题的列表和一个视图函数来显示单个问题和其选项。可以使用以下代码: ```python from django.shortcuts import render, get_object_or_404 from .models import Question def index(request): latest_question_list = Question.objects.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}) ``` 5. 在应用程序的 `urls.py` 文件中创建 URL 模式。例如,可以创建一个 URL 模式来将路径 `/polls/` 映射到 `index` 视图函数,以及一个 URL 模式来将路径 `/polls/<question_id>/` 映射到 `detail` 视图函数。可以使用以下代码: ```python from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), ] ``` 6. 在模板文件中创建 HTML 模板。例如,可以创建一个模板来显示所有问题的列表,并在模板中使用循环和条件语句来显示每个问题的标题和发布日期。可以使用以下代码: ```html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} ``` 7. 在模板文件中创建一个表单,使用户能够为单个问题的选项投票。例如,可以创建一个表单,其中包含一个隐藏字段来存储问题 ID,以及一个单选按钮列表来显示问题的选项。可以使用以下代码: ```html <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> ``` 8. 在应用程序的 `views.py` 文件中创建一个视图函数来处理投票。例如,可以创建一个视图函数来获取用户选择的选项并将其存储到数据库中。可以使用以下代码: ```python from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse from .models import Question, Choice 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() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) ``` 9. 在应用程序的 `urls.py` 文件中创建另一个 URL 模式,将路径 `/polls/<question_id>/results/` 映射到一个视图函数,该视图函数将显示单个问题的投票结果。可以使用以下代码: ```python from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/vote/', views.vote, name='vote'), path('<int:question_id>/results/', views.results, name='results'), ] ``` 10. 在应用程序的 `views.py` 文件中创建一个视图函数来显示单个问题的投票结果。例如,可以创建一个视图函数来获取问题和其所有选项的投票结果,并将其显示在模板中。可以使用以下代码: ```python from django.shortcuts import render, get_object_or_404 from .models import Question def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) ``` 11. 创建一个模板来显示单个问题的投票结果。例如,可以创建一个模板来显示问题的标题和每个选项的投票结果。可以使用以下代码: ```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> ``` 完成上述步骤后,即可在 Django 中实现投票功能。

相关推荐

最新推荐

recommend-type

Python Django实现layui风格+django分页功能的例子

今天小编就为大家分享一篇Python Django实现layui风格+django分页功能的例子,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

django 实现简单的插入视频

主要介绍了django 实现简单的插入视频,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

在django项目中导出数据到excel文件并实现下载的功能

主要介绍了在django项目中导出数据到excel文件并实现下载的功能,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

在django中实现choices字段获取对应字段值

主要介绍了在django中实现choices字段获取对应字段值,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

Django返回HTML文件的实现方法

主要介绍了Django返回HTML文件的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

用 Python 画一个可以动的爱心

好的,我可以帮助您使用Python来绘制一个动态的爱心。您可以使用turtle库来实现。以下是实现代码: ```python import turtle import math # 设置画布和画笔 canvas = turtle.Screen() canvas.bgcolor("black") pencil = turtle.Turtle() pencil.speed(0) pencil.color("red", "pink") pencil.pensize(3) # 定义爱心函数 def draw_love(heart_size, x_offset=0, y_offset=0):
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。