django 投票小项目

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django 投票小项目相关的知识,希望对你有一定的参考价值。

创建一个mysite项目

django-admin startproject mysite

创建一个polls应用

django-admin startapp polls

mkdir polls/templates/ 创建模板文件夹

polls.views.py 内容如下

from django.shortcuts import get_object_or_404, render
from django.core.urlresolvers import reverse
from django.views import generic
# Create your views here.
class IndexView(generic.ListView):
    template_name = polls/index.html
    context_object_name = latest_question_list

    def get_queryset(self):
        """Return the last five published questions."""
        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
def vote(request, question_id):
    p = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST[choice])
    except (KeyError, Choice.DoesNotExist):
            # Redisplay the question voting form.
        return render(request, polls/detail.html, {question: p,error_message: "You didn‘t select a choice.",})
    else:
        selected_choice.votes += 1
        selected_choice.save()
    return HttpResponseRedirect(reverse(polls:results, args=(p.id,)))

以上采用的是generic View的方法,还可以用下面的方法

from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from polls.models import Question,Choice
from django.template import RequestContext ,loader
from django.shortcuts import get_object_or_404, render
from django.core.urlresolvers import reverse
# Create your views here.

def detail(request, question_id):
    text = Question.objects.filter(pk=question_id)
    #return HttpResponse("You‘re looking at question %s." % question_id)
    #return HttpResponse(text)
    question = get_object_or_404(Question, pk=question_id)
    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)
    question = get_object_or_404(Question, pk=question_id)
    return render(request, polls/results.html, {question: question})

def vote(request, question_id):
    #return HttpResponse("You‘re voting on question %s." % question_id)
    p = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST[choice])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, polls/detail.html, {question: p,error_message: "You didn‘t select a choice.",})
    else:
        selected_choice.votes += 1
        selected_choice.save()
    return HttpResponseRedirect(reverse(polls:results, args=(p.id,)))


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)
                                                                                                   40,1-4       底端

app02/models.py

from django.db import models
from django.utils import timezone
import datetime
from django.contrib.contenttypes.fields import GenericForeignKey
# Create your models here.
class  Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField(date published)

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1) #判断是否是最近发布的
    was_published_recently.admin_order_field = pub_date‘  #用pub_date字段排序
    was_published_recently.boolean = True   #如果是最近发布的就会显示一个标志出来
    was_published_recently.short_description = Published recently?‘  #描述

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

app02/urls.py

from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns(‘‘,
        url(r^$, views.IndexView.as_view(), name=index),
        url(r^(?P<pk>\d+)/$, views.DetailView.as_view(), name=detail),
        url(r^(?P<pk>\d+)/results/$, views.ResultsView.as_view(), name=results),
        url(r^(?P<question_id>\d+)/vote/$, views.vote, name=vote),

        )

还有另一种方法

from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns(‘‘,
        # ex: /polls/
        #url(r‘^$‘, views.index, name=‘index‘),
        # ex: /polls/5/
        url(r^(?P<question_id>\d+)/$, views.detail, name=detail),
        # ex: /polls/5/results/
        url(r^(?P<question_id>\d+)/results/$, views.results, name=results),
        # ex: /polls/5/vote/
        url(r^(?P<question_id>\d+)/vote/$, views.vote, name=vote),
        (r^pl/$, polls.views.index),
        )
                                                                                                                                                                                                  

 

以上是关于django 投票小项目的主要内容,如果未能解决你的问题,请参考以下文章

Java小项目之:投票系统

带有 Django 频道的网络套接字

利用django创建一个投票网站

利用django创建一个投票网站

微信小程序代码片段

Django快速开发之投票系统