在民意测验应用程序中添加问题功能-Django

时间:2019-06-08 02:14:45

标签: python django

我已经从Django Documentation创建了民意测验应用程序,但我想为其添加更多功能 -不仅管理员,而且每个没有注册的用户都应具有添加问题的功能 -在添加问题时,应该有一个有效的日期,可以投票给它,否则应该显示“投票已关闭”,并应重定向到结果页面。

这是我的项目投票:

poll
|_ __init__.py
|_ settings.py
|_ urls.py
|_ wsgi.py
polls
|_ static
|_ templates
   |_ polls
      |_ contains base.html, index.html, detail.html, results.html
|_ __init__.py
|_ admin.py
|_ models.py
|_ apps.py
|_ views.py
|_ urls.py
|_ tests.py
  • admin.py文件:
from django.contrib import admin
from .models import Question, Choice

class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 4

class QuestionAdmin(admin.ModelAdmin):
    list_display = ('topic', 'question_text', 'pub_date', 'date_valid')
    list_filter = ['pub_date']
    search_fields = ['topic']
    fieldsets = [
        (None, {'fields': ['topic', 'question_text']}),
        ('Date Information', {'fields': ['pub_date', 'date_valid'], 'classes': ['collapse']}),
    ]
    inlines = [ChoiceInline]

admin.site.register(Question, QuestionAdmin)
  • models.py文件:
from django.db import models
import datetime
from django.utils import timezone
from django.urls import reverse

class Question(models.Model):
    topic = models.CharField(max_length=200)
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    date_valid = models.DateField('validity date')

    def __str__(self):
        return self.topic

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=30) <= self.pub_date <= now

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

    def __str__(self):
        return self.choice_text
  • views.py文件:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from .models import Question, Choice
from django.utils import timezone
from django.views import generic
import datetime
from django.views.generic.edit import CreateView
from .models import Question, Choice

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:10]

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):
    question = get_object_or_404(Question, pk=question_id)
    if 1==0: #question.date_valid<=timezone.now():
        return render(request, 'polls/results.html question.id', {'error_message': "The Question is no longer available for voting."})
    else:
        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 didnt select any choice."})
        else:
            selected_choice.votes+=1
            selected_choice.save()
            return HttpResponseRedirect(reverse('polls:results',args=(question.id,))
  • urls.py(投票):
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('polls/', include('polls.urls')),
    path('', RedirectView.as_view(url='/polls/', permanent=True)),
]
  • urls.py(民意调查):
from django.urls import path
from . import views

app_name = 'polls'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),    
    path('<int:question_id>/vote/', views.vote, name='vote'),
    path('question/create/', views.QuestionCreate.as_view(), name='question-create'),
]

这是github链接: https://github.com/priyanshu-panwar/Django-Polls-App 任何人都可以拉取请求...

0 个答案:

没有答案