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 0000000..356d276 Binary files /dev/null and b/homework_08/mysite/polls/static/polls/images/background.png differ 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 }}

+ + + + 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 %}