Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions homework_08/Dockerfile
Original file line number Diff line number Diff line change
@@ -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' ]
38 changes: 38 additions & 0 deletions homework_08/Makefile
Original file line number Diff line number Diff line change
@@ -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
14 changes: 14 additions & 0 deletions homework_08/README.md
Original file line number Diff line number Diff line change
@@ -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 репозитарий. Далее необходимо зайти в ЛК, найти занятие, ДЗ по которому выполнялось, нажать “Чат с преподавателем” и отправить ссылку. После этого ревью и общение на тему ДЗ будет происходить в рамках этого чата.
Empty file added homework_08/mysite/__init__.py
Empty file.
22 changes: 22 additions & 0 deletions homework_08/mysite/manage.py
Original file line number Diff line number Diff line change
@@ -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()
Empty file.
16 changes: 16 additions & 0 deletions homework_08/mysite/mysite/asgi.py
Original file line number Diff line number Diff line change
@@ -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()
124 changes: 124 additions & 0 deletions homework_08/mysite/mysite/settings.py
Original file line number Diff line number Diff line change
@@ -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"
24 changes: 24 additions & 0 deletions homework_08/mysite/mysite/urls.py
Original file line number Diff line number Diff line change
@@ -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),
]
16 changes: 16 additions & 0 deletions homework_08/mysite/mysite/wsgi.py
Original file line number Diff line number Diff line change
@@ -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()
Empty file.
22 changes: 22 additions & 0 deletions homework_08/mysite/polls/admin.py
Original file line number Diff line number Diff line change
@@ -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)
6 changes: 6 additions & 0 deletions homework_08/mysite/polls/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class PollsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "polls"
58 changes: 58 additions & 0 deletions homework_08/mysite/polls/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -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"
),
),
],
),
]
Empty file.
Loading