├── .gitignore ├── 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 /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | __pycache__ 3 | db.sqlite3 4 | .DS_Store 5 | -------------------------------------------------------------------------------- /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/jruizvar/django-tutorial/0a88785ae2d69b4a21e2c38770af6130af67ffbe/mysite/__init__.py -------------------------------------------------------------------------------- /mysite/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for mysite project. 3 | 4 | Generated by 'django-admin startproject' using Django 2.0.1. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/2.0/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/2.0/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.0/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = '%ymny-!plsi=7pq)lqqwh-8+(q9(33z-4ut_d4uw(*o2^syadc' 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': [], 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.0/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.0/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.0/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'America/Sao_Paulo' 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.0/howto/static-files/ 120 | 121 | STATIC_URL = '/static/' 122 | -------------------------------------------------------------------------------- /mysite/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import include, path 2 | from django.contrib import admin 3 | 4 | urlpatterns = [ 5 | path('polls/', include('polls.urls')), 6 | path('admin/', admin.site.urls), 7 | ] 8 | -------------------------------------------------------------------------------- /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.0/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/jruizvar/django-tutorial/0a88785ae2d69b4a21e2c38770af6130af67ffbe/polls/__init__.py -------------------------------------------------------------------------------- /polls/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | 3 | from .models import Question 4 | 5 | admin.site.register(Question) 6 | -------------------------------------------------------------------------------- /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.0.1 on 2018-01-28 23:24 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/jruizvar/django-tutorial/0a88785ae2d69b4a21e2c38770af6130af67ffbe/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 | 19 | class Choice(models.Model): 20 | question = models.ForeignKey(Question, on_delete=models.CASCADE) 21 | choice_text = models.CharField(max_length=200) 22 | votes = models.IntegerField(default=0) 23 | 24 | def __str__(self): 25 | return self.choice_text 26 | -------------------------------------------------------------------------------- /polls/static/polls/images/background.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jruizvar/django-tutorial/0a88785ae2d69b4a21e2c38770af6130af67ffbe/polls/static/polls/images/background.gif -------------------------------------------------------------------------------- /polls/static/polls/style.css: -------------------------------------------------------------------------------- 1 | li a { 2 | color: green; 3 | } 4 | 5 | body { 6 | background: white url("images/background.gif") no-repeat right bottom; 7 | } 8 | -------------------------------------------------------------------------------- /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.urls import reverse 4 | from django.utils import timezone 5 | from django.test import TestCase 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 | def test_was_published_recently_with_old_question(self): 22 | """ 23 | was_published_recently() returns False for questions whose pub_date 24 | is older than 1 day. 25 | """ 26 | time = timezone.now() - datetime.timedelta(days=1, seconds=1) 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() returns True for questions whose pub_date 33 | is within the last day. 34 | """ 35 | time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) 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 | Create 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 QuestionIndexViewTests(TestCase): 51 | def test_no_questions(self): 52 | """ 53 | If no questions exist, an appropriate message is 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_past_question(self): 61 | """ 62 | Questions with a pub_date in the past are 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_future_question(self): 73 | """ 74 | Questions with a pub_date in the future aren't 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_future_question_and_past_question(self): 83 | """ 84 | Even if both past and future questions exist, only past questions 85 | are 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_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 QuestionDetailViewTests(TestCase): 109 | def test_future_question(self): 110 | """ 111 | The detail view of a question with a pub_date in the future 112 | returns 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_past_question(self): 120 | """ 121 | The detail view of a question with a pub_date in the past 122 | displays 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 | -------------------------------------------------------------------------------- /polls/urls.py: -------------------------------------------------------------------------------- 1 | from django.urls import path 2 | 3 | from . import views 4 | 5 | app_name = 'polls' 6 | urlpatterns = [ 7 | path('', views.IndexView.as_view(), name='index'), 8 | path('/', views.DetailView.as_view(), name='detail'), 9 | path('/results/', views.ResultsView.as_view(), name='results'), 10 | path('/vote/', views.vote, name='vote'), 11 | ] 12 | -------------------------------------------------------------------------------- /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.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 | # 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 | --------------------------------------------------------------------------------