├── mysite ├── __init__.py ├── urls.py ├── wsgi.py └── settings.py ├── polls ├── __init__.py ├── migrations │ ├── __init__.py │ └── 0001_initial.py ├── static │ └── polls │ │ ├── images │ │ └── background.gif │ │ └── style.css ├── apps.py ├── templates │ └── polls │ │ ├── results.html │ │ ├── index.html │ │ └── detail.html ├── urls.py ├── admin.py ├── models.py ├── views.py └── tests.py ├── .gitignore ├── templates └── admin │ └── base_site.html ├── manage.py └── README.md /mysite/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /polls/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /polls/migrations/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | db.sqlite3 2 | *.pyc 3 | -------------------------------------------------------------------------------- /polls/static/polls/images/background.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdamien/django-tutorial/HEAD/polls/static/polls/images/background.gif -------------------------------------------------------------------------------- /polls/apps.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | 3 | from django.apps import AppConfig 4 | 5 | 6 | class PollsConfig(AppConfig): 7 | name = 'polls' 8 | -------------------------------------------------------------------------------- /polls/static/polls/style.css: -------------------------------------------------------------------------------- 1 | li a { 2 | color: green; 3 | } 4 | 5 | body { 6 | background: white url("images/background.gif") repeat right bottom; 7 | } 8 | -------------------------------------------------------------------------------- /mysite/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import include, url 2 | from django.contrib import admin 3 | 4 | urlpatterns = [ 5 | url(r'^polls/', include('polls.urls')), 6 | url(r'^admin/', admin.site.urls), 7 | ] 8 | -------------------------------------------------------------------------------- /polls/templates/polls/results.html: -------------------------------------------------------------------------------- 1 |

{{ question.question_text }}

2 | 3 | 8 | 9 | Vote again? 10 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /polls/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | 3 | from . import views 4 | 5 | app_name = 'polls' 6 | urlpatterns = [ 7 | url(r'^$', views.IndexView.as_view(), name='index'), 8 | url(r'^(?P[0-9]+)/$', views.DetailView.as_view(), name='detail'), 9 | url(r'^(?P[0-9]+)/results/$', views.ResultsView.as_view(), name='results'), 10 | url(r'^(?P[0-9]+)/vote/$', views.vote, name='vote'), 11 | ] 12 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/1.10/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/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/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from .models import Question, Choice 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 | 22 | admin.site.register(Question, QuestionAdmin) 23 | -------------------------------------------------------------------------------- /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: 10 | # The above import may fail for some other reason. Ensure that the 11 | # issue is really that Django is missing to avoid masking other 12 | # exceptions on Python 2. 13 | try: 14 | import django 15 | except ImportError: 16 | raise ImportError( 17 | "Couldn't import Django. Are you sure it's installed and " 18 | "available on your PYTHONPATH environment variable? Did you " 19 | "forget to activate a virtual environment?" 20 | ) 21 | raise 22 | execute_from_command_line(sys.argv) 23 | -------------------------------------------------------------------------------- /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 was_published_recently(self): 12 | now = timezone.now() 13 | return now - datetime.timedelta(days=1) <= self.pub_date <= now 14 | was_published_recently.admin_order_field = 'pub_date' 15 | was_published_recently.boolean = True 16 | was_published_recently.short_description = 'Published recently?' 17 | 18 | def __str__(self): 19 | return self.question_text 20 | 21 | 22 | class Choice(models.Model): 23 | question = models.ForeignKey(Question, on_delete=models.CASCADE) 24 | choice_text = models.CharField(max_length=200) 25 | votes = models.IntegerField(default=0) 26 | 27 | def __str__(self): 28 | return self.choice_text 29 | -------------------------------------------------------------------------------- /polls/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.10 on 2016-09-04 10:06 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | import django.db.models.deletion 7 | 8 | 9 | class Migration(migrations.Migration): 10 | 11 | initial = True 12 | 13 | dependencies = [ 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='Choice', 19 | fields=[ 20 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 21 | ('choice_text', models.CharField(max_length=200)), 22 | ('votes', models.IntegerField(default=0)), 23 | ], 24 | ), 25 | migrations.CreateModel( 26 | name='Question', 27 | fields=[ 28 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 29 | ('question_text', models.CharField(max_length=200)), 30 | ('pub_date', models.DateTimeField(verbose_name=b'date published')), 31 | ], 32 | ), 33 | migrations.AddField( 34 | model_name='choice', 35 | name='question', 36 | field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question'), 37 | ), 38 | ] 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Django 1.10 Tutorial - Poll app 2 | 3 | Resulting app from the [Django 1.10 tutorial](https://docs.djangoproject.com/en/1.10/intro/tutorial01/). 4 | 5 | Each step is available via the tags: 6 | 7 | - [step 1](https://github.com/mdamien/django-tutorial/tree/tutorial01) ([commit](https://github.com/mdamien/django-tutorial/commit/tutorial01)) 8 | - [step 2](https://github.com/mdamien/django-tutorial/tree/tutorial02) ([commit](https://github.com/mdamien/django-tutorial/commit/tutorial02)) 9 | - [step 3](https://github.com/mdamien/django-tutorial/tree/tutorial03) ([commit](https://github.com/mdamien/django-tutorial/commit/tutorial03)) 10 | - [step 4](https://github.com/mdamien/django-tutorial/tree/tutorial04) ([commit](https://github.com/mdamien/django-tutorial/commit/tutorial04)) 11 | - [step 5](https://github.com/mdamien/django-tutorial/tree/tutorial05) ([commit](https://github.com/mdamien/django-tutorial/commit/tutorial05)) 12 | - [step 6](https://github.com/mdamien/django-tutorial/tree/tutorial06) ([commit](https://github.com/mdamien/django-tutorial/commit/tutorial06)) 13 | - [step 7](https://github.com/mdamien/django-tutorial/tree/tutorial07) ([commit](https://github.com/mdamien/django-tutorial/commit/tutorial07)) 14 | 15 | #### Notes 16 | 17 | - There exist [another repo doing that](https://github.com/Chive/django-poll-app) but it's not up-to-date 18 | - I decided not to add python 2 support in step 2 19 | - I added the `Choice` model to the admin directly in step 2 20 | - I used `repeat` instead of `no-repeat` for the background in step 6, looks better 21 | -------------------------------------------------------------------------------- /polls/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import get_object_or_404, render 2 | from django.http import HttpResponseRedirect 3 | from django.urls import reverse 4 | from django.views import generic 5 | from django.utils import timezone 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 | # Redisplay the question voting form. 46 | return render(request, 'polls/detail.html', { 47 | 'question': question, 48 | 'error_message': "You didn't select a choice.", 49 | }) 50 | else: 51 | selected_choice.votes += 1 52 | selected_choice.save() 53 | # Always return an HttpResponseRedirect after successfully dealing 54 | # with POST data. This prevents data from being posted twice if a 55 | # user hits the Back button. 56 | return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) 57 | -------------------------------------------------------------------------------- /mysite/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for mysite project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.10. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.10/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.10/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/1.10/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'iruhl47piy2vx37=cvuc^$mj*7ft3t+9l*g7%!gqvv)0^8l7)=' 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/1.10/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/1.10/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/1.10/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/1.10/howto/static-files/ 120 | 121 | STATIC_URL = '/static/' 122 | -------------------------------------------------------------------------------- /polls/tests.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | from django.utils import timezone 4 | from django.urls import reverse 5 | from django.test import TestCase 6 | 7 | from .models import Question 8 | 9 | 10 | class QuestionMethodTests(TestCase): 11 | 12 | def test_was_published_recently_with_future_question(self): 13 | """ 14 | was_published_recently() should return False for questions whose 15 | pub_date 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 | def test_was_published_recently_with_old_question(self): 22 | """ 23 | was_published_recently() should return False for questions whose 24 | pub_date is older than 1 day. 25 | """ 26 | time = timezone.now() - datetime.timedelta(days=30) 27 | old_question = Question(pub_date=time) 28 | self.assertIs(old_question.was_published_recently(), False) 29 | 30 | def test_was_published_recently_with_recent_question(self): 31 | """ 32 | was_published_recently() should return True for questions whose 33 | pub_date is within the last day. 34 | """ 35 | time = timezone.now() - datetime.timedelta(hours=1) 36 | recent_question = Question(pub_date=time) 37 | self.assertIs(recent_question.was_published_recently(), True) 38 | 39 | 40 | def create_question(question_text, days): 41 | """ 42 | Creates a question with the given `question_text` and published the 43 | given number of `days` offset to now (negative for questions published 44 | in the past, positive for questions that have yet to be published). 45 | """ 46 | time = timezone.now() + datetime.timedelta(days=days) 47 | return Question.objects.create(question_text=question_text, pub_date=time) 48 | 49 | 50 | class QuestionViewTests(TestCase): 51 | def test_index_view_with_no_questions(self): 52 | """ 53 | If no questions exist, an appropriate message should be displayed. 54 | """ 55 | response = self.client.get(reverse('polls:index')) 56 | self.assertEqual(response.status_code, 200) 57 | self.assertContains(response, "No polls are available.") 58 | self.assertQuerysetEqual(response.context['latest_question_list'], []) 59 | 60 | def test_index_view_with_a_past_question(self): 61 | """ 62 | Questions with a pub_date in the past should be displayed on the 63 | index page. 64 | """ 65 | create_question(question_text="Past question.", days=-30) 66 | response = self.client.get(reverse('polls:index')) 67 | self.assertQuerysetEqual( 68 | response.context['latest_question_list'], 69 | [''] 70 | ) 71 | 72 | def test_index_view_with_a_future_question(self): 73 | """ 74 | Questions with a pub_date in the future should not be displayed on 75 | the index page. 76 | """ 77 | create_question(question_text="Future question.", days=30) 78 | response = self.client.get(reverse('polls:index')) 79 | self.assertContains(response, "No polls are available.") 80 | self.assertQuerysetEqual(response.context['latest_question_list'], []) 81 | 82 | def test_index_view_with_future_question_and_past_question(self): 83 | """ 84 | Even if both past and future questions exist, only past questions 85 | should be displayed. 86 | """ 87 | create_question(question_text="Past question.", days=-30) 88 | create_question(question_text="Future question.", days=30) 89 | response = self.client.get(reverse('polls:index')) 90 | self.assertQuerysetEqual( 91 | response.context['latest_question_list'], 92 | [''] 93 | ) 94 | 95 | def test_index_view_with_two_past_questions(self): 96 | """ 97 | The questions index page may display multiple questions. 98 | """ 99 | create_question(question_text="Past question 1.", days=-30) 100 | create_question(question_text="Past question 2.", days=-5) 101 | response = self.client.get(reverse('polls:index')) 102 | self.assertQuerysetEqual( 103 | response.context['latest_question_list'], 104 | ['', ''] 105 | ) 106 | 107 | 108 | class QuestionIndexDetailTests(TestCase): 109 | def test_detail_view_with_a_future_question(self): 110 | """ 111 | The detail view of a question with a pub_date in the future should 112 | return a 404 not found. 113 | """ 114 | future_question = create_question(question_text='Future question.', days=5) 115 | url = reverse('polls:detail', args=(future_question.id,)) 116 | response = self.client.get(url) 117 | self.assertEqual(response.status_code, 404) 118 | 119 | def test_detail_view_with_a_past_question(self): 120 | """ 121 | The detail view of a question with a pub_date in the past should 122 | display the question's text. 123 | """ 124 | past_question = create_question(question_text='Past Question.', days=-5) 125 | url = reverse('polls:detail', args=(past_question.id,)) 126 | response = self.client.get(url) 127 | self.assertContains(response, past_question.question_text) 128 | --------------------------------------------------------------------------------