├── LICENSE ├── README.md ├── manage.py ├── mysite ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py ├── polls ├── __init__.py ├── admin.py ├── apps.py ├── migrations │ ├── 0001_initial.py │ └── __init__.py ├── models.py ├── static │ └── polls │ │ ├── images │ │ └── background.gif │ │ └── style.css ├── templates │ └── polls │ │ ├── detail.html │ │ ├── index.html │ │ └── results.html ├── tests.py ├── urls.py └── views.py └── templates └── admin └── base_site.html /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 DigitalOcean Community 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django Tutorial Polls App 2 | 3 | This repository contains the complete code for the [Django](https://www.djangoproject.com/) project's [tutorial](https://docs.djangoproject.com/en/2.1/intro/tutorial01/) `polls` app. The code should mirror the code you've written at the end of [Part 7](https://docs.djangoproject.com/en/2.1/intro/tutorial07/). 4 | 5 | The `SECRET_KEY` variable in `mysite/settings.py` has been scrubbed, and instructions for regenerating the key are available in the accompanying DigitalOcean [tutorial](https://www.digitalocean.com/community/tutorials). 6 | 7 | This app is meant to be used as a reference Django app for several DigitalOcean tutorials, and should not be deployed in production. 8 | 9 | ---- 10 | 11 | ### Quickstart 12 | 13 | Polls is a simple Django app to conduct Web-based polls. For each question, visitors can choose between a fixed number of answers. 14 | 15 | 16 | 1. Add `polls` to your `INSTALLED_APPS` setting like this: 17 | 18 | ```python 19 | INSTALLED_APPS = [ 20 | ... 21 | 'polls', 22 | ] 23 | ``` 24 | 25 | 2. Include the polls URLconf in your project `urls.py` like this: 26 | 27 | ```python 28 | path('polls/', include('polls.urls')), 29 | ``` 30 | 31 | 3. Run `python manage.py migrate` to create the polls models. 32 | 33 | 4. Start the development server and visit http://127.0.0.1:8000/admin/ 34 | to create a poll (you'll need the Admin app enabled). 35 | 36 | 5. Visit http://127.0.0.1:8000/polls/ to participate in the poll. -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == '__main__': 6 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError as exc: 10 | raise ImportError( 11 | "Couldn't import Django. Are you sure it's installed and " 12 | "available on your PYTHONPATH environment variable? Did you " 13 | "forget to activate a virtual environment?" 14 | ) from exc 15 | execute_from_command_line(sys.argv) 16 | -------------------------------------------------------------------------------- /mysite/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/do-community/django-polls/61c5b63ec0159b83d1c552f242f4389c80ce61b4/mysite/__init__.py -------------------------------------------------------------------------------- /mysite/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for mysite project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.1. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.1/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'your_secret_key_here' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'polls.apps.PollsConfig', 35 | 'django.contrib.admin', 36 | 'django.contrib.auth', 37 | 'django.contrib.contenttypes', 38 | 'django.contrib.sessions', 39 | 'django.contrib.messages', 40 | 'django.contrib.staticfiles', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'mysite.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [os.path.join(BASE_DIR, 'templates')], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'mysite.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/2.1/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 | }, 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/2.1/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_L10N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/2.1/howto/static-files/ 120 | 121 | STATIC_URL = '/static/' 122 | -------------------------------------------------------------------------------- /mysite/urls.py: -------------------------------------------------------------------------------- 1 | """mysite URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/2.1/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.urls import include, path 14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 | """ 16 | from django.contrib import admin 17 | from django.urls import include, path 18 | 19 | urlpatterns = [ 20 | path('polls/', include('polls.urls')), 21 | path('admin/', admin.site.urls), 22 | ] 23 | -------------------------------------------------------------------------------- /mysite/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for mysite project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /polls/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/do-community/django-polls/61c5b63ec0159b83d1c552f242f4389c80ce61b4/polls/__init__.py -------------------------------------------------------------------------------- /polls/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from .models import Choice, Question 4 | 5 | 6 | class ChoiceInline(admin.TabularInline): 7 | model = Choice 8 | extra = 3 9 | 10 | 11 | class QuestionAdmin(admin.ModelAdmin): 12 | fieldsets = [ 13 | (None, {'fields': ['question_text']}), 14 | ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}), 15 | ] 16 | inlines = [ChoiceInline] 17 | list_display = ('question_text', 'pub_date', 'was_published_recently') 18 | list_filter = ['pub_date'] 19 | search_fields = ['question_text'] 20 | 21 | admin.site.register(Question, QuestionAdmin) 22 | -------------------------------------------------------------------------------- /polls/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class PollsConfig(AppConfig): 5 | name = 'polls' 6 | -------------------------------------------------------------------------------- /polls/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # Generated by Django 2.1 on 2018-08-08 21:45 2 | 3 | from django.db import migrations, models 4 | import django.db.models.deletion 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | initial = True 10 | 11 | dependencies = [ 12 | ] 13 | 14 | operations = [ 15 | migrations.CreateModel( 16 | name='Choice', 17 | fields=[ 18 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 19 | ('choice_text', models.CharField(max_length=200)), 20 | ('votes', models.IntegerField(default=0)), 21 | ], 22 | ), 23 | migrations.CreateModel( 24 | name='Question', 25 | fields=[ 26 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 27 | ('question_text', models.CharField(max_length=200)), 28 | ('pub_date', models.DateTimeField(verbose_name='date published')), 29 | ], 30 | ), 31 | migrations.AddField( 32 | model_name='choice', 33 | name='question', 34 | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question'), 35 | ), 36 | ] 37 | -------------------------------------------------------------------------------- /polls/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/do-community/django-polls/61c5b63ec0159b83d1c552f242f4389c80ce61b4/polls/migrations/__init__.py -------------------------------------------------------------------------------- /polls/models.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | from django.db import models 4 | from django.utils import timezone 5 | 6 | 7 | class Question(models.Model): 8 | question_text = models.CharField(max_length=200) 9 | pub_date = models.DateTimeField('date published') 10 | 11 | def __str__(self): 12 | return self.question_text 13 | 14 | def was_published_recently(self): 15 | now = timezone.now() 16 | return now - datetime.timedelta(days=1) <= self.pub_date <= now 17 | 18 | was_published_recently.admin_order_field = 'pub_date' 19 | was_published_recently.boolean = True 20 | was_published_recently.short_description = 'Published recently?' 21 | 22 | 23 | class Choice(models.Model): 24 | question = models.ForeignKey(Question, on_delete=models.CASCADE) 25 | choice_text = models.CharField(max_length=200) 26 | votes = models.IntegerField(default=0) 27 | 28 | def __str__(self): 29 | return self.choice_text 30 | -------------------------------------------------------------------------------- /polls/static/polls/images/background.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/do-community/django-polls/61c5b63ec0159b83d1c552f242f4389c80ce61b4/polls/static/polls/images/background.gif -------------------------------------------------------------------------------- /polls/static/polls/style.css: -------------------------------------------------------------------------------- 1 | li a { 2 | color: green; 3 | } 4 | body { 5 | background: white url("images/background.gif") no-repeat; 6 | } 7 | -------------------------------------------------------------------------------- /polls/templates/polls/detail.html: -------------------------------------------------------------------------------- 1 |

{{ question.question_text }}

2 | 3 | {% if error_message %}

{{ error_message }}

{% endif %} 4 | 5 |
6 | {% csrf_token %} 7 | {% for choice in question.choice_set.all %} 8 | 9 |
10 | {% endfor %} 11 | 12 |
13 | -------------------------------------------------------------------------------- /polls/templates/polls/index.html: -------------------------------------------------------------------------------- 1 | {% load static %} 2 | 3 | 4 | 5 | {% if latest_question_list %} 6 | 11 | {% else %} 12 |

No polls are available.

13 | {% endif %} 14 | -------------------------------------------------------------------------------- /polls/templates/polls/results.html: -------------------------------------------------------------------------------- 1 |

{{ question.question_text }}

2 | 3 | 8 | 9 | Vote again? 10 | -------------------------------------------------------------------------------- /polls/tests.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | from django.test import TestCase 4 | from django.urls import reverse 5 | from django.utils import timezone 6 | 7 | from .models import Question 8 | 9 | 10 | class QuestionModelTests(TestCase): 11 | 12 | def test_was_published_recently_with_future_question(self): 13 | """ 14 | was_published_recently() returns False for questions whose pub_date 15 | is in the future. 16 | """ 17 | time = timezone.now() + datetime.timedelta(days=30) 18 | future_question = Question(pub_date=time) 19 | self.assertIs(future_question.was_published_recently(), False) 20 | 21 | 22 | def test_was_published_recently_with_old_question(self): 23 | """ 24 | was_published_recently() returns False for questions whose pub_date 25 | is older than 1 day. 26 | """ 27 | time = timezone.now() - datetime.timedelta(days=1, seconds=1) 28 | old_question = Question(pub_date=time) 29 | self.assertIs(old_question.was_published_recently(), False) 30 | 31 | def test_was_published_recently_with_recent_question(self): 32 | """ 33 | was_published_recently() returns True for questions whose pub_date 34 | is within the last day. 35 | """ 36 | time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) 37 | recent_question = Question(pub_date=time) 38 | self.assertIs(recent_question.was_published_recently(), True) 39 | 40 | 41 | def create_question(question_text, days): 42 | """ 43 | Create a question with the given `question_text` and published the 44 | given number of `days` offset to now (negative for questions published 45 | in the past, positive for questions that have yet to be published). 46 | """ 47 | time = timezone.now() + datetime.timedelta(days=days) 48 | return Question.objects.create(question_text=question_text, pub_date=time) 49 | 50 | 51 | class QuestionIndexViewTests(TestCase): 52 | def test_no_questions(self): 53 | """ 54 | If no questions exist, an appropriate message is displayed. 55 | """ 56 | response = self.client.get(reverse('polls:index')) 57 | self.assertEqual(response.status_code, 200) 58 | self.assertContains(response, "No polls are available.") 59 | self.assertQuerysetEqual(response.context['latest_question_list'], []) 60 | 61 | def test_past_question(self): 62 | """ 63 | Questions with a pub_date in the past are displayed on the 64 | index page. 65 | """ 66 | create_question(question_text="Past question.", days=-30) 67 | response = self.client.get(reverse('polls:index')) 68 | self.assertQuerysetEqual( 69 | response.context['latest_question_list'], 70 | [''] 71 | ) 72 | 73 | def test_future_question(self): 74 | """ 75 | Questions with a pub_date in the future aren't displayed on 76 | the index page. 77 | """ 78 | create_question(question_text="Future question.", days=30) 79 | response = self.client.get(reverse('polls:index')) 80 | self.assertContains(response, "No polls are available.") 81 | self.assertQuerysetEqual(response.context['latest_question_list'], []) 82 | 83 | def test_future_question_and_past_question(self): 84 | """ 85 | Even if both past and future questions exist, only past questions 86 | are displayed. 87 | """ 88 | create_question(question_text="Past question.", days=-30) 89 | create_question(question_text="Future question.", days=30) 90 | response = self.client.get(reverse('polls:index')) 91 | self.assertQuerysetEqual( 92 | response.context['latest_question_list'], 93 | [''] 94 | ) 95 | 96 | def test_two_past_questions(self): 97 | """ 98 | The questions index page may display multiple questions. 99 | """ 100 | create_question(question_text="Past question 1.", days=-30) 101 | create_question(question_text="Past question 2.", days=-5) 102 | response = self.client.get(reverse('polls:index')) 103 | self.assertQuerysetEqual( 104 | response.context['latest_question_list'], 105 | ['', ''] 106 | ) 107 | 108 | 109 | class QuestionDetailViewTests(TestCase): 110 | def test_future_question(self): 111 | """ 112 | The detail view of a question with a pub_date in the future 113 | returns a 404 not found. 114 | """ 115 | future_question = create_question(question_text='Future question.', days=5) 116 | url = reverse('polls:detail', args=(future_question.id,)) 117 | response = self.client.get(url) 118 | self.assertEqual(response.status_code, 404) 119 | 120 | def test_past_question(self): 121 | """ 122 | The detail view of a question with a pub_date in the past 123 | displays the question's text. 124 | """ 125 | past_question = create_question(question_text='Past Question.', days=-5) 126 | url = reverse('polls:detail', args=(past_question.id,)) 127 | response = self.client.get(url) 128 | self.assertContains(response, past_question.question_text) 129 | -------------------------------------------------------------------------------- /polls/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from . import views 4 | 5 | 6 | app_name = 'polls' 7 | urlpatterns = [ 8 | path('', views.IndexView.as_view(), name='index'), 9 | path('/', views.DetailView.as_view(), name='detail'), 10 | path('/results/', views.ResultsView.as_view(), name='results'), 11 | path('/vote/', views.vote, name='vote'), 12 | ] 13 | -------------------------------------------------------------------------------- /polls/views.py: -------------------------------------------------------------------------------- 1 | from django.http import HttpResponseRedirect 2 | from django.shortcuts import get_object_or_404, render 3 | from django.urls import reverse 4 | from django.utils import timezone 5 | from django.views import generic 6 | 7 | from .models import Choice, Question 8 | 9 | 10 | class IndexView(generic.ListView): 11 | template_name = 'polls/index.html' 12 | context_object_name = 'latest_question_list' 13 | 14 | def get_queryset(self): 15 | """ 16 | Return the last five published questions (not including those set to be 17 | published in the future). 18 | """ 19 | return Question.objects.filter( 20 | pub_date__lte=timezone.now() 21 | ).order_by('-pub_date')[:5] 22 | 23 | 24 | class DetailView(generic.DetailView): 25 | model = Question 26 | template_name = 'polls/detail.html' 27 | 28 | def get_queryset(self): 29 | """ 30 | Excludes any questions that aren't published yet. 31 | """ 32 | return Question.objects.filter(pub_date__lte=timezone.now()) 33 | 34 | 35 | class ResultsView(generic.DetailView): 36 | model = Question 37 | template_name = 'polls/results.html' 38 | 39 | 40 | def vote(request, question_id): 41 | question = get_object_or_404(Question, pk=question_id) 42 | try: 43 | selected_choice = question.choice_set.get(pk=request.POST['choice']) 44 | except (KeyError, Choice.DoesNotExist): 45 | return render(request, 'polls/detail.html', { 46 | 'question': question, 47 | 'error_message': "You didn't select a choice.", 48 | }) 49 | else: 50 | selected_choice.votes += 1 51 | selected_choice.save() 52 | return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) 53 | -------------------------------------------------------------------------------- /templates/admin/base_site.html: -------------------------------------------------------------------------------- 1 | {% extends "admin/base.html" %} 2 | 3 | {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} 4 | 5 | {% block branding %} 6 |

Polls Administration

7 | {% endblock %} 8 | 9 | {% block nav-global %}{% endblock %} 10 | --------------------------------------------------------------------------------