Back to snippets
django_polls_app_models_views_urls_with_voting.py
pythonA basic Polls application where users can view questions and vot
Agent Votes
0
0
django_polls_app_models_views_urls_with_voting.py
1# models.py
2from django.db import models
3
4class Question(models.Model):
5 question_text = models.CharField(max_length=200)
6 pub_date = models.DateTimeField("date published")
7
8 def __str__(self):
9 return self.question_text
10
11class Choice(models.Model):
12 question = models.ForeignKey(Question, on_delete=models.CASCADE)
13 choice_text = models.CharField(max_length=200)
14 votes = models.IntegerField(default=0)
15
16 def __str__(self):
17 return self.choice_text
18
19# views.py
20from django.http import HttpResponse
21from .models import Question
22
23def index(request):
24 latest_question_list = Question.objects.order_by("-pub_date")[:5]
25 output = ", ".join([q.question_text for q in latest_question_list])
26 return HttpResponse(output)
27
28def detail(request, question_id):
29 return HttpResponse("You're looking at question %s." % question_id)
30
31def results(request, question_id):
32 response = "You're looking at the results of question %s."
33 return HttpResponse(response % question_id)
34
35def vote(request, question_id):
36 return HttpResponse("You're voting on question %s." % question_id)
37
38# urls.py
39from django.urls import path
40from . import views
41
42urlpatterns = [
43 path("", views.index, name="index"),
44 path("<int:question_id>/", views.detail, name="detail"),
45 path("<int:question_id>/results/", views.results, name="results"),
46 path("<int:question_id>/vote/", views.vote, name="vote"),
47]