From 5b13fd1d5d46bd757413c39804dda4e9807e44e3 Mon Sep 17 00:00:00 2001 From: Vladislav Kozlov Date: Sat, 5 Apr 2025 22:47:19 -0700 Subject: [PATCH] HW08: init --- .pre-commit-config.yaml | 2 +- homework_08/Dockerfile | 12 ++ homework_08/Makefile | 38 ++++++ homework_08/README.md | 14 ++ homework_08/mysite/__init__.py | 0 homework_08/mysite/manage.py | 22 ++++ homework_08/mysite/mysite/__init__.py | 0 homework_08/mysite/mysite/asgi.py | 16 +++ homework_08/mysite/mysite/settings.py | 124 ++++++++++++++++++ homework_08/mysite/mysite/urls.py | 24 ++++ homework_08/mysite/mysite/wsgi.py | 16 +++ homework_08/mysite/polls/__init__.py | 0 homework_08/mysite/polls/admin.py | 22 ++++ homework_08/mysite/polls/apps.py | 6 + .../mysite/polls/migrations/0001_initial.py | 58 ++++++++ .../mysite/polls/migrations/__init__.py | 0 homework_08/mysite/polls/models.py | 30 +++++ .../polls/static/polls/images/background.png | Bin 0 -> 4435 bytes .../mysite/polls/static/polls/style.css | 7 + .../mysite/polls/templates/polls/detail.html | 21 +++ .../mysite/polls/templates/polls/index.html | 22 ++++ .../mysite/polls/templates/polls/results.html | 18 +++ homework_08/mysite/polls/tests.py | 74 +++++++++++ homework_08/mysite/polls/urls.py | 11 ++ homework_08/mysite/polls/views.py | 58 ++++++++ .../mysite/templates/admin/base_site.html | 11 ++ 26 files changed, 605 insertions(+), 1 deletion(-) create mode 100644 homework_08/Dockerfile create mode 100644 homework_08/Makefile create mode 100644 homework_08/README.md create mode 100644 homework_08/mysite/__init__.py create mode 100755 homework_08/mysite/manage.py create mode 100644 homework_08/mysite/mysite/__init__.py create mode 100644 homework_08/mysite/mysite/asgi.py create mode 100644 homework_08/mysite/mysite/settings.py create mode 100644 homework_08/mysite/mysite/urls.py create mode 100644 homework_08/mysite/mysite/wsgi.py create mode 100644 homework_08/mysite/polls/__init__.py create mode 100644 homework_08/mysite/polls/admin.py create mode 100644 homework_08/mysite/polls/apps.py create mode 100644 homework_08/mysite/polls/migrations/0001_initial.py create mode 100644 homework_08/mysite/polls/migrations/__init__.py create mode 100644 homework_08/mysite/polls/models.py create mode 100644 homework_08/mysite/polls/static/polls/images/background.png create mode 100644 homework_08/mysite/polls/static/polls/style.css create mode 100644 homework_08/mysite/polls/templates/polls/detail.html create mode 100644 homework_08/mysite/polls/templates/polls/index.html create mode 100644 homework_08/mysite/polls/templates/polls/results.html create mode 100644 homework_08/mysite/polls/tests.py create mode 100644 homework_08/mysite/polls/urls.py create mode 100644 homework_08/mysite/polls/views.py create mode 100644 homework_08/mysite/templates/admin/base_site.html diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a1b4d96..7033fd5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -52,7 +52,7 @@ repos: - --max-line-length=120 - --ignore-imports=yes - -d duplicate-code - - -d C0111,W0621,R0913,R1705,W0201,R0903,W0613 + - -d C0111,W0621,R0913,R1705,W0201,R0903,W0613,C0415,C0103 - repo: https://github.com/asottile/pyupgrade diff --git a/homework_08/Dockerfile b/homework_08/Dockerfile new file mode 100644 index 0000000..232c569 --- /dev/null +++ b/homework_08/Dockerfile @@ -0,0 +1,12 @@ +FROM python:3.12 + +ENV PYTHONUNBUFFERED=1 + +RUN mkdir -p /app +WORKDIR /app + +COPY Makefile pyproject.toml poetry.lock +RUN poetry install --no-root +COPY ./mysite . + +ENTRYPOINT [ "python", "/app/mysicte/manage.py", 'runserver' ] diff --git a/homework_08/Makefile b/homework_08/Makefile new file mode 100644 index 0000000..94d688d --- /dev/null +++ b/homework_08/Makefile @@ -0,0 +1,38 @@ +SETTINGS_DIR=settings +PYTHON=python3 +OS_TYPE=Lin + +# Define default server to run +DEV_SETTINGS=settings_dev.py +PROD_SETTINGS=$(SETTINGS_DIR)/settings_prod.py + +# Update project name +PROJECT_DIR=./mysite + +# Define Django commands +dev: + $(PYTHON) $(PROJECT_DIR)/manage.py runserver + +test: + $(PYTHON) $(PROJECT_DIR)/manage.py test polls + +prod: + $(PYTHON) manage.py runserver + +migrate-dev: + $(PYTHON) $(PROJECT_DIR)/manage.py migrate + +migrate-prod: + $(PYTHON) manage.py migrate + +# Help command to display available options +help: + @echo "Django Makefile Commands:" + @echo " dev: Run the server in dev mode" + @echo " test: Run unit tests" + @echo " prod: Run the server in prod mode" + @echo " migrate-dev: Run migrations in dev mode" + @echo " migrate-prod: Run migrations in prod mode" + @echo " help: Display this help message" + +.PHONY: dev test prod migrate-dev migrate-prod help diff --git a/homework_08/README.md b/homework_08/README.md new file mode 100644 index 0000000..d24150c --- /dev/null +++ b/homework_08/README.md @@ -0,0 +1,14 @@ +## Задание +### Django tutorial + +*Задание*: полностью пройти туториал по django https://docs.djangoproject.com/en/5.0/intro/tutorial01/, оформив при этом результирующий проект с соблюдением всех лучших практик, которые обсуждались раннее, а также в парадигме 12 factor app https://12factor.net (это общая статья, как прикладывать к django легко можно найти; критику подходу можно почитать тут https://xenitab.github.io/blog/2022/02/23/12factor/) + +*Цель задания*: получить навык работы с django, а также набить руку в создании сервисов, которые можно было бы назвать production grade/ + +*Критерии успеха*: код в репозитории целиком реализует функционал туториала, проект сруктурирован стандартным образом, настроены проверки линторв, форматтеры и т.д., а сам сервис максимально следует парадигме 12 factor app. + +## Deadline +Задание желательно сдать в течение недели. Код, отправленный на ревью в это время, рассматривается в первом приоритете. Нарушение делайна не карается. Пытаться сдать ДЗ можно до конца курсы. Код, отправленный с опозданием, когда по плану предполагается работа над более актуальным ДЗ, будет рассматриваться в более низком приоритете без гарантий по высокой скорости проверки. + +## Обратная связь +Cтудент коммитит все необходимое в свой github/gitlab репозитарий. Далее необходимо зайти в ЛК, найти занятие, ДЗ по которому выполнялось, нажать “Чат с преподавателем” и отправить ссылку. После этого ревью и общение на тему ДЗ будет происходить в рамках этого чата. diff --git a/homework_08/mysite/__init__.py b/homework_08/mysite/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/homework_08/mysite/manage.py b/homework_08/mysite/manage.py new file mode 100755 index 0000000..8005262 --- /dev/null +++ b/homework_08/mysite/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == "__main__": + main() diff --git a/homework_08/mysite/mysite/__init__.py b/homework_08/mysite/mysite/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/homework_08/mysite/mysite/asgi.py b/homework_08/mysite/mysite/asgi.py new file mode 100644 index 0000000..cebf4c6 --- /dev/null +++ b/homework_08/mysite/mysite/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for mysite project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") + +application = get_asgi_application() diff --git a/homework_08/mysite/mysite/settings.py b/homework_08/mysite/mysite/settings.py new file mode 100644 index 0000000..893dce9 --- /dev/null +++ b/homework_08/mysite/mysite/settings.py @@ -0,0 +1,124 @@ +""" +Django settings for mysite project. + +Generated by 'django-admin startproject' using Django 5.0. + +For more information on this file, see +https://docs.djangoproject.com/en/5.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.0/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = "django-insecure-__er)c+3x%##^yl(%+7^e=!32-4!(04f+utu(#z(+sjzh8w*wh" + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] # type: ignore + + +# Application definition + +INSTALLED_APPS = [ + "polls.apps.PollsConfig", + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", +] + +MIDDLEWARE = [ + "django.middleware.security.SecurityMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.common.CommonMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", +] + +ROOT_URLCONF = "mysite.urls" + +TEMPLATES = [ + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [BASE_DIR / "templates"], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", + ], + }, + }, +] + +WSGI_APPLICATION = "mysite.wsgi.application" + + +# Database +# https://docs.djangoproject.com/en/5.0/ref/settings/#databases + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": BASE_DIR / "db.sqlite3", + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/5.0/topics/i18n/ + +LANGUAGE_CODE = "en-us" + +TIME_ZONE = "America/Chicago" + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/5.0/howto/static-files/ + +STATIC_URL = "static/" + +# Default primary key field type +# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" diff --git a/homework_08/mysite/mysite/urls.py b/homework_08/mysite/mysite/urls.py new file mode 100644 index 0000000..a8aa965 --- /dev/null +++ b/homework_08/mysite/mysite/urls.py @@ -0,0 +1,24 @@ +""" +URL configuration for mysite project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" + +from django.contrib import admin +from django.urls import include, path + +urlpatterns = [ + path("polls/", include("polls.urls")), + path("admin/", admin.site.urls), +] diff --git a/homework_08/mysite/mysite/wsgi.py b/homework_08/mysite/mysite/wsgi.py new file mode 100644 index 0000000..f7d2a95 --- /dev/null +++ b/homework_08/mysite/mysite/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for mysite project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") + +application = get_wsgi_application() diff --git a/homework_08/mysite/polls/__init__.py b/homework_08/mysite/polls/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/homework_08/mysite/polls/admin.py b/homework_08/mysite/polls/admin.py new file mode 100644 index 0000000..846afa4 --- /dev/null +++ b/homework_08/mysite/polls/admin.py @@ -0,0 +1,22 @@ +from django.contrib import admin + +from .models import Choice, Question + + +class ChoiceInline(admin.TabularInline): + model = Choice + extra = 3 + + +class QuestionAdmin(admin.ModelAdmin): + fieldsets = [ + (None, {"fields": ["question_text"]}), + ("Date information", {"fields": ["pub_date"], "classes": ["collapse"]}), + ] + inlines = [ChoiceInline] + list_display = ["question_text", "pub_date", "was_published_recently"] + list_filter = ["pub_date"] + search_fields = ["question_text"] + + +admin.site.register(Question, QuestionAdmin) diff --git a/homework_08/mysite/polls/apps.py b/homework_08/mysite/polls/apps.py new file mode 100644 index 0000000..5184937 --- /dev/null +++ b/homework_08/mysite/polls/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class PollsConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "polls" diff --git a/homework_08/mysite/polls/migrations/0001_initial.py b/homework_08/mysite/polls/migrations/0001_initial.py new file mode 100644 index 0000000..cfe18bd --- /dev/null +++ b/homework_08/mysite/polls/migrations/0001_initial.py @@ -0,0 +1,58 @@ +# Generated by Django 5.0 on 2025-04-04 05:28 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [] # type: ignore + + operations = [ + migrations.CreateModel( + name="Question", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "question_text", + models.CharField(max_length=200, verbose_name="Question"), + ), + ("pub_date", models.DateTimeField(verbose_name="Date published")), + ], + ), + migrations.CreateModel( + name="Choice", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "choise_text", + models.CharField(max_length=200, verbose_name="Choises"), + ), + ("votes", models.IntegerField(default=0, verbose_name="Votes")), + ( + "question", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, to="polls.question" + ), + ), + ], + ), + ] diff --git a/homework_08/mysite/polls/migrations/__init__.py b/homework_08/mysite/polls/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/homework_08/mysite/polls/models.py b/homework_08/mysite/polls/models.py new file mode 100644 index 0000000..f9a7846 --- /dev/null +++ b/homework_08/mysite/polls/models.py @@ -0,0 +1,30 @@ +import datetime + +from django.contrib import admin +from django.db import models +from django.utils import timezone + + +class Question(models.Model): + question_text = models.CharField("Question", max_length=200) + pub_date = models.DateTimeField("Date published") + + def __str__(self) -> str: + return str(self.question_text) + + @admin.display( + boolean=True, + ordering="pub_date", + description="Published recently?", + ) + def was_published_recently(self) -> bool: + return self.pub_date >= timezone.now() - datetime.timedelta(days=1) + + +class Choice(models.Model): + question = models.ForeignKey(Question, on_delete=models.CASCADE) + choise_text = models.CharField("Choises", max_length=200) + votes = models.IntegerField("Votes", default=0) + + def __str__(self): + return str(self.choise_text) diff --git a/homework_08/mysite/polls/static/polls/images/background.png b/homework_08/mysite/polls/static/polls/images/background.png new file mode 100644 index 0000000000000000000000000000000000000000..356d2760e5e23c45b894705d2a2b6b748138f879 GIT binary patch literal 4435 zcmcK8*E<^y7YFdzQhPR5HB?ZsYL6PRH=*dTRTVK>Rm2vvHnI1fr8cpO+Iy?Lwf5E` z-oAgt@8Wzv7w0+W`aCC0S6hYb0pkMz06?austEt*+W(6f?_UBDY^wk0($zFj`rHJ# zzrT0;m)L*aIo1KDf3@|jmio7`JJbSP8UXH%cz6Fg_qQJ#0M^xj=K0L19=Xb?@SW42 zH8XMktqetD-Ww+aA2EP;RREV7!1z{!Lp=ad{cr6bWCQM-NBOq{iNHE$*2Ot5}Q=JB4-cp@5`2@)V6t`ynl?#W!j4D_3a{j7Js>ZmbA~j z`a~b;~`SifypO-ae!X8OD-_tX%Jlwb<)8faqP8xfVI~%gqV#g1JM(gw5nAYsq)ou z5W@z1m)5@!PcY7PTAA>@Sg^eQEAVA8xw!)7ZP0Sig}h{>rMVGaX;vQtKq1NCK7`Ntlz( zz5Ru|=xNIcP%VJ>cNiPGv$I!oT1K_X#+Tr zorJD%)_voRTvoxT2my{f5lxl*_XBp6mIbh44suS_j$?ZLlHw#!4)8p@gQ5m4YzBlr zwIi1N>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?u2FYxF zp_Cw%L*q2n(O;;BtUj*epud(2bc&^z=^8wp_hwJSLyqVS=9r>&F-k+(Si&7DzromL z7ntz|w!dl^GBi?!QKpbyW7%QO9dnYcU<2n321AO+!QT&+Y3TyQMBas?il7fG zHFn9|c;0t?AEl0Cm~C@c*bPJG+RItJNSr%4ke@b|JpG2VXH#l{d5nAyAvVUj4%IH1l`b=FE_pYh#Zmjtu@;!8SAUT|)HXr2 z8$k|r^*Njmt1C%*S}8sLc#&nbaHd%XTrN?uz4ZH+)r?bp8jUH%R^i)q((BwWnP~py zdeW?VPhKyrtjF(tXC|m)4bt8#A$h%hrJv>XuAMSzU)@3uTt42@U>k6Y4xj5e6&W${ zFmTi1<~p7gr0$R$@C80kAulk`^jT_A7(39$H|+Z|{8*f3%8FDAp2n-w>Uw_`v{c~1 z0}C%Q@?5|a1uY5i=-dd5UhU!>XY6sA+D73{zEeuLHzO{Uf;X%rJ8}jm;V&J&KJfO@ yyZn29+qlO9zbb&Zn%TkrGejvq-&RlD$OgGfL1oe*0{^}w05v6T#jh~)fd2uW6_}v_ literal 0 HcmV?d00001 diff --git a/homework_08/mysite/polls/static/polls/style.css b/homework_08/mysite/polls/static/polls/style.css new file mode 100644 index 0000000..85e933c --- /dev/null +++ b/homework_08/mysite/polls/static/polls/style.css @@ -0,0 +1,7 @@ +li a { + color: green; +} + +body { + background: white url("images/background.png") no-repeat; +} diff --git a/homework_08/mysite/polls/templates/polls/detail.html b/homework_08/mysite/polls/templates/polls/detail.html new file mode 100644 index 0000000..813b409 --- /dev/null +++ b/homework_08/mysite/polls/templates/polls/detail.html @@ -0,0 +1,21 @@ + + + + + Detail + + +
+ {% csrf_token %} +
+

{{ question.question_text }}

+ {% if error_message %}

{{ error_message }}

{% endif %} + {% for choice in question.choice_set.all %} + +
+ {% endfor %} +
+ +
+ + diff --git a/homework_08/mysite/polls/templates/polls/index.html b/homework_08/mysite/polls/templates/polls/index.html new file mode 100644 index 0000000..7a12ead --- /dev/null +++ b/homework_08/mysite/polls/templates/polls/index.html @@ -0,0 +1,22 @@ + + + + + + Polls + + + {% load static %} + + + {% if latest_question_list %} + + {% else %} +

No polls are available.

+ {% endif %} + + diff --git a/homework_08/mysite/polls/templates/polls/results.html b/homework_08/mysite/polls/templates/polls/results.html new file mode 100644 index 0000000..5ee9a82 --- /dev/null +++ b/homework_08/mysite/polls/templates/polls/results.html @@ -0,0 +1,18 @@ + + + + + Result + + +

{{ question.question_text }}

+ +
    + {% for choice in question.choice_set.all %} +
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  • + {% endfor %} +
+ + Vote again? + + diff --git a/homework_08/mysite/polls/tests.py b/homework_08/mysite/polls/tests.py new file mode 100644 index 0000000..fcdf02c --- /dev/null +++ b/homework_08/mysite/polls/tests.py @@ -0,0 +1,74 @@ +import datetime + +from django.test import TestCase +from django.urls import reverse +from django.utils import timezone + +from .models import Question + + +def create_question(question_text, days): + """ + Create a question with the given `question_text` and published the + given number of `days` offset to now (negative for questions published + in the past, positive for questions that have yet to be published). + """ + time = timezone.now() + datetime.timedelta(days=days) + # pylint: disable=E1101 + return Question.objects.create(question_text=question_text, pub_date=time) + + +class QuestionIndexViewTests(TestCase): + def test_no_questions(self): + """ + If no questions exist, an appropriate message is displayed. + """ + response = self.client.get(reverse("polls:index")) + self.assertEqual(response.status_code, 200) + self.assertContains(response, "No polls are available.") + self.assertQuerySetEqual(response.context["latest_question_list"], []) + + def test_past_question(self): + """ + The detail view of a question with a pub_date in the past + displays the question's text. + """ + past_question = create_question(question_text="Past Question.", days=-5) + url = reverse("polls:detail", args=(past_question.id,)) + response = self.client.get(url) + self.assertContains(response, past_question.question_text) + + def test_future_question(self): + """ + The detail view of a question with a pub_date in the future + returns a 404 not found. + """ + future_question = create_question(question_text="Future question.", days=5) + url = reverse("polls:detail", args=(future_question.id,)) + response = self.client.get(url) + self.assertEqual(response.status_code, 404) + + def test_future_question_and_past_question(self): + """ + Even if both past and future questions exist, only past questions + are displayed. + """ + question = create_question(question_text="Past question.", days=-30) + create_question(question_text="Future question.", days=30) + response = self.client.get(reverse("polls:index")) + self.assertQuerySetEqual( + response.context["latest_question_list"], + [question], + ) + + def test_two_past_questions(self): + """ + The questions index page may display multiple questions. + """ + question1 = create_question(question_text="Past question 1.", days=-30) + question2 = create_question(question_text="Past question 2.", days=-5) + response = self.client.get(reverse("polls:index")) + self.assertQuerySetEqual( + response.context["latest_question_list"], + [question2, question1], + ) diff --git a/homework_08/mysite/polls/urls.py b/homework_08/mysite/polls/urls.py new file mode 100644 index 0000000..45ebddd --- /dev/null +++ b/homework_08/mysite/polls/urls.py @@ -0,0 +1,11 @@ +from django.urls import path + +from . import views + +app_name = "polls" +urlpatterns = [ + path("", views.IndexView.as_view(), name="index"), + path("/", views.DetailView.as_view(), name="detail"), + path("/results/", views.ResultsView.as_view(), name="results"), + path("/vote/", views.vote, name="vote"), +] diff --git a/homework_08/mysite/polls/views.py b/homework_08/mysite/polls/views.py new file mode 100644 index 0000000..ce62101 --- /dev/null +++ b/homework_08/mysite/polls/views.py @@ -0,0 +1,58 @@ +from django.db.models import F +from django.http import HttpResponseRedirect +from django.shortcuts import get_object_or_404, render +from django.urls import reverse +from django.utils import timezone +from django.views import generic + +from .models import Choice, Question + + +class IndexView(generic.ListView): + template_name = "polls/index.html" + context_object_name = "latest_question_list" + + def get_queryset(self): + """ + Return the last five published questions (not including those set to be + published in the future). + """ + # pylint: disable=E1101 + return Question.objects.filter(pub_date__lte=timezone.now()).order_by( + "-pub_date" + )[:5] + + +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) + try: + selected_choice = question.choice_set.get(pk=request.POST["choice"]) + # pylint: disable=E1101 + except (KeyError, Choice.DoesNotExist): + # Redisplay the question voting form. + return render( + request, + "polls/detail.html", + { + "question": question, + "error_message": "You didn't select a choice.", + }, + ) + else: + selected_choice.votes = F("votes") + 1 + selected_choice.save() + # Always return an HttpResponseRedirect after successfully dealing + # with POST data. This prevents data from being posted twice if a + # user hits the Back button. + return HttpResponseRedirect(reverse("polls:results", args=(question.id,))) diff --git a/homework_08/mysite/templates/admin/base_site.html b/homework_08/mysite/templates/admin/base_site.html new file mode 100644 index 0000000..783b5e0 --- /dev/null +++ b/homework_08/mysite/templates/admin/base_site.html @@ -0,0 +1,11 @@ +{% extends "admin/base.html" %} + +{% block title %}{% if subtitle %}{{ subtitle }} | {% endif %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} + +{% block branding %} + +{% if user.is_anonymous %} + {% include "admin/color_theme_toggle.html" %} +{% endif %} +{% endblock %} +{% block nav-global %}{% endblock %}