Commit 740f0bb0 authored by Давид Ли's avatar Давид Ли

Lesson 56

parents
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="db" uuid="ce5fb2e1-f5b9-4d88-bad6-0006060d4568">
<driver-ref>sqlite.xerial</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
<jdbc-url>jdbc:sqlite:$PROJECT_DIR$/db.sqlite3</jdbc-url>
<working-dir>$ProjectFileDir$</working-dir>
<libraries>
<library>
<url>file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.40.1/org/xerial/sqlite-jdbc/3.40.1.0/sqlite-jdbc-3.40.1.0.jar</url>
</library>
</libraries>
</data-source>
</component>
</project>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredPackages">
<value>
<list size="189">
<item index="0" class="java.lang.String" itemvalue="aiohttp" />
<item index="1" class="java.lang.String" itemvalue="nodeenv" />
<item index="2" class="java.lang.String" itemvalue="identify" />
<item index="3" class="java.lang.String" itemvalue="pre-commit" />
<item index="4" class="java.lang.String" itemvalue="setuptools" />
<item index="5" class="java.lang.String" itemvalue="packaging" />
<item index="6" class="java.lang.String" itemvalue="toml" />
<item index="7" class="java.lang.String" itemvalue="zeep" />
<item index="8" class="java.lang.String" itemvalue="attrs" />
<item index="9" class="java.lang.String" itemvalue="pyyaml" />
<item index="10" class="java.lang.String" itemvalue="filelock" />
<item index="11" class="java.lang.String" itemvalue="platformdirs" />
<item index="12" class="java.lang.String" itemvalue="certifi" />
<item index="13" class="java.lang.String" itemvalue="virtualenv" />
<item index="14" class="java.lang.String" itemvalue="multidict" />
<item index="15" class="java.lang.String" itemvalue="distlib" />
<item index="16" class="java.lang.String" itemvalue="lxml" />
<item index="17" class="java.lang.String" itemvalue="yarl" />
<item index="18" class="java.lang.String" itemvalue="urllib3" />
<item index="19" class="java.lang.String" itemvalue="pytz" />
<item index="20" class="java.lang.String" itemvalue="cfgv" />
<item index="21" class="java.lang.String" itemvalue="httpcore" />
<item index="22" class="java.lang.String" itemvalue="zope-event" />
<item index="23" class="java.lang.String" itemvalue="greenlet" />
<item index="24" class="java.lang.String" itemvalue="zope-interface" />
<item index="25" class="java.lang.String" itemvalue="ruamel-yaml" />
<item index="26" class="java.lang.String" itemvalue="gevent" />
<item index="27" class="java.lang.String" itemvalue="ruamel-yaml-clib" />
<item index="28" class="java.lang.String" itemvalue="remote-procedure" />
<item index="29" class="java.lang.String" itemvalue="django-healthchecks" />
<item index="30" class="java.lang.String" itemvalue="PyYAML" />
<item index="31" class="java.lang.String" itemvalue="defusedxml" />
<item index="32" class="java.lang.String" itemvalue="django-nested-admin" />
<item index="33" class="java.lang.String" itemvalue="pycparser" />
<item index="34" class="java.lang.String" itemvalue="redis" />
<item index="35" class="java.lang.String" itemvalue="coreschema" />
<item index="36" class="java.lang.String" itemvalue="pyasn1-modules" />
<item index="37" class="java.lang.String" itemvalue="django-behaviors" />
<item index="38" class="java.lang.String" itemvalue="sentry-sdk" />
<item index="39" class="java.lang.String" itemvalue="shadiakiki1986-python-ntlm3" />
<item index="40" class="java.lang.String" itemvalue="jsonschema" />
<item index="41" class="java.lang.String" itemvalue="xlrd" />
<item index="42" class="java.lang.String" itemvalue="asgiref" />
<item index="43" class="java.lang.String" itemvalue="reportlab" />
<item index="44" class="java.lang.String" itemvalue="gunicorn" />
<item index="45" class="java.lang.String" itemvalue="click" />
<item index="46" class="java.lang.String" itemvalue="boto3" />
<item index="47" class="java.lang.String" itemvalue="drf-jwt" />
<item index="48" class="java.lang.String" itemvalue="humanize" />
<item index="49" class="java.lang.String" itemvalue="msgpack" />
<item index="50" class="java.lang.String" itemvalue="idna" />
<item index="51" class="java.lang.String" itemvalue="PyJWT" />
<item index="52" class="java.lang.String" itemvalue="rsa" />
<item index="53" class="java.lang.String" itemvalue="django-environ" />
<item index="54" class="java.lang.String" itemvalue="python-crontab" />
<item index="55" class="java.lang.String" itemvalue="cffi" />
<item index="56" class="java.lang.String" itemvalue="djangorestframework-camel-case" />
<item index="57" class="java.lang.String" itemvalue="google-cloud-storage" />
<item index="58" class="java.lang.String" itemvalue="django-storages" />
<item index="59" class="java.lang.String" itemvalue="pyasn1" />
<item index="60" class="java.lang.String" itemvalue="requests" />
<item index="61" class="java.lang.String" itemvalue="drf-yasg" />
<item index="62" class="java.lang.String" itemvalue="pyrsistent" />
<item index="63" class="java.lang.String" itemvalue="celery" />
<item index="64" class="java.lang.String" itemvalue="ruamel.yaml.clib" />
<item index="65" class="java.lang.String" itemvalue="grpcio-status" />
<item index="66" class="java.lang.String" itemvalue="prompt-toolkit" />
<item index="67" class="java.lang.String" itemvalue="djangorestframework" />
<item index="68" class="java.lang.String" itemvalue="django-cors-headers" />
<item index="69" class="java.lang.String" itemvalue="uritemplate" />
<item index="70" class="java.lang.String" itemvalue="drf-recaptcha" />
<item index="71" class="java.lang.String" itemvalue="tornado" />
<item index="72" class="java.lang.String" itemvalue="botocore" />
<item index="73" class="java.lang.String" itemvalue="django-celery-results" />
<item index="74" class="java.lang.String" itemvalue="phonenumbers" />
<item index="75" class="java.lang.String" itemvalue="amqp" />
<item index="76" class="java.lang.String" itemvalue="et-xmlfile" />
<item index="77" class="java.lang.String" itemvalue="flower" />
<item index="78" class="java.lang.String" itemvalue="python-monkey-business" />
<item index="79" class="java.lang.String" itemvalue="Django" />
<item index="80" class="java.lang.String" itemvalue="django-axes" />
<item index="81" class="java.lang.String" itemvalue="cachetools" />
<item index="82" class="java.lang.String" itemvalue="itypes" />
<item index="83" class="java.lang.String" itemvalue="google-api-python-client" />
<item index="84" class="java.lang.String" itemvalue="click-repl" />
<item index="85" class="java.lang.String" itemvalue="inflection" />
<item index="86" class="java.lang.String" itemvalue="Pillow" />
<item index="87" class="java.lang.String" itemvalue="protobuf" />
<item index="88" class="java.lang.String" itemvalue="googleapis-common-protos" />
<item index="89" class="java.lang.String" itemvalue="django-split-settings" />
<item index="90" class="java.lang.String" itemvalue="python-dateutil" />
<item index="91" class="java.lang.String" itemvalue="psycopg2-binary" />
<item index="92" class="java.lang.String" itemvalue="kombu" />
<item index="93" class="java.lang.String" itemvalue="MarkupSafe" />
<item index="94" class="java.lang.String" itemvalue="drf-spectacular" />
<item index="95" class="java.lang.String" itemvalue="pyparsing" />
<item index="96" class="java.lang.String" itemvalue="vine" />
<item index="97" class="java.lang.String" itemvalue="google-api-core" />
<item index="98" class="java.lang.String" itemvalue="django-celery-beat" />
<item index="99" class="java.lang.String" itemvalue="google-crc32c" />
<item index="100" class="java.lang.String" itemvalue="tablib" />
<item index="101" class="java.lang.String" itemvalue="django-import-export" />
<item index="102" class="java.lang.String" itemvalue="cryptography" />
<item index="103" class="java.lang.String" itemvalue="zope.interface" />
<item index="104" class="java.lang.String" itemvalue="whitenoise" />
<item index="105" class="java.lang.String" itemvalue="bcrypt" />
<item index="106" class="java.lang.String" itemvalue="odfpy" />
<item index="107" class="java.lang.String" itemvalue="django-filter" />
<item index="108" class="java.lang.String" itemvalue="charset-normalizer" />
<item index="109" class="java.lang.String" itemvalue="django-smtp-ntlm-backend" />
<item index="110" class="java.lang.String" itemvalue="CacheControl" />
<item index="111" class="java.lang.String" itemvalue="google-cloud-core" />
<item index="112" class="java.lang.String" itemvalue="fcm-django" />
<item index="113" class="java.lang.String" itemvalue="diff-match-patch" />
<item index="114" class="java.lang.String" itemvalue="django-ckeditor" />
<item index="115" class="java.lang.String" itemvalue="firebase-admin" />
<item index="116" class="java.lang.String" itemvalue="httplib2" />
<item index="117" class="java.lang.String" itemvalue="wcwidth" />
<item index="118" class="java.lang.String" itemvalue="click-didyoumean" />
<item index="119" class="java.lang.String" itemvalue="Jinja2" />
<item index="120" class="java.lang.String" itemvalue="sqlparse" />
<item index="121" class="java.lang.String" itemvalue="google-resumable-media" />
<item index="122" class="java.lang.String" itemvalue="google-auth-httplib2" />
<item index="123" class="java.lang.String" itemvalue="django-phonenumber-field" />
<item index="124" class="java.lang.String" itemvalue="zope.event" />
<item index="125" class="java.lang.String" itemvalue="billiard" />
<item index="126" class="java.lang.String" itemvalue="pyotp" />
<item index="127" class="java.lang.String" itemvalue="six" />
<item index="128" class="java.lang.String" itemvalue="ruamel.yaml" />
<item index="129" class="java.lang.String" itemvalue="tzdata" />
<item index="130" class="java.lang.String" itemvalue="xlwt" />
<item index="131" class="java.lang.String" itemvalue="MarkupPy" />
<item index="132" class="java.lang.String" itemvalue="django-admin-list-filter-dropdown" />
<item index="133" class="java.lang.String" itemvalue="prometheus-client" />
<item index="134" class="java.lang.String" itemvalue="jmespath" />
<item index="135" class="java.lang.String" itemvalue="coreapi" />
<item index="136" class="java.lang.String" itemvalue="django-ipware" />
<item index="137" class="java.lang.String" itemvalue="s3transfer" />
<item index="138" class="java.lang.String" itemvalue="pyspnego" />
<item index="139" class="java.lang.String" itemvalue="django-js-asset" />
<item index="140" class="java.lang.String" itemvalue="proto-plus" />
<item index="141" class="java.lang.String" itemvalue="django-timezone-field" />
<item index="142" class="java.lang.String" itemvalue="grpcio" />
<item index="143" class="java.lang.String" itemvalue="click-plugins" />
<item index="144" class="java.lang.String" itemvalue="google-cloud-firestore" />
<item index="145" class="java.lang.String" itemvalue="google-auth" />
<item index="146" class="java.lang.String" itemvalue="openpyxl" />
<item index="147" class="java.lang.String" itemvalue="pytest-coverage" />
<item index="148" class="java.lang.String" itemvalue="alembic" />
<item index="149" class="java.lang.String" itemvalue="pytest-splinter" />
<item index="150" class="java.lang.String" itemvalue="pytest-cover" />
<item index="151" class="java.lang.String" itemvalue="trio-websocket" />
<item index="152" class="java.lang.String" itemvalue="pluggy" />
<item index="153" class="java.lang.String" itemvalue="python-dotenv" />
<item index="154" class="java.lang.String" itemvalue="h11" />
<item index="155" class="java.lang.String" itemvalue="mako" />
<item index="156" class="java.lang.String" itemvalue="sniffio" />
<item index="157" class="java.lang.String" itemvalue="httptools" />
<item index="158" class="java.lang.String" itemvalue="markupsafe" />
<item index="159" class="java.lang.String" itemvalue="trio" />
<item index="160" class="java.lang.String" itemvalue="selenium" />
<item index="161" class="java.lang.String" itemvalue="pytest-cov" />
<item index="162" class="java.lang.String" itemvalue="starlette" />
<item index="163" class="java.lang.String" itemvalue="anyio" />
<item index="164" class="java.lang.String" itemvalue="uvicorn" />
<item index="165" class="java.lang.String" itemvalue="python-jose" />
<item index="166" class="java.lang.String" itemvalue="uvloop" />
<item index="167" class="java.lang.String" itemvalue="outcome" />
<item index="168" class="java.lang.String" itemvalue="passlib" />
<item index="169" class="java.lang.String" itemvalue="websockets" />
<item index="170" class="java.lang.String" itemvalue="coverage" />
<item index="171" class="java.lang.String" itemvalue="watchfiles" />
<item index="172" class="java.lang.String" itemvalue="pydantic" />
<item index="173" class="java.lang.String" itemvalue="pytest-sugar" />
<item index="174" class="java.lang.String" itemvalue="asyncpg" />
<item index="175" class="java.lang.String" itemvalue="pytest" />
<item index="176" class="java.lang.String" itemvalue="iniconfig" />
<item index="177" class="java.lang.String" itemvalue="ecdsa" />
<item index="178" class="java.lang.String" itemvalue="splinter" />
<item index="179" class="java.lang.String" itemvalue="typing-extensions" />
<item index="180" class="java.lang.String" itemvalue="pytest-asyncio" />
<item index="181" class="java.lang.String" itemvalue="sqlalchemy" />
<item index="182" class="java.lang.String" itemvalue="wsproto" />
<item index="183" class="java.lang.String" itemvalue="sortedcontainers" />
<item index="184" class="java.lang.String" itemvalue="termcolor" />
<item index="185" class="java.lang.String" itemvalue="fastapi" />
<item index="186" class="java.lang.String" itemvalue="faker" />
<item index="187" class="java.lang.String" itemvalue="pysocks" />
<item index="188" class="java.lang.String" itemvalue="async-generator" />
</list>
</value>
</option>
</inspection_tool>
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredIdentifiers">
<list>
<option value="type.with_ui" />
<option value="type.without_ui" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="FacetManager">
<facet type="django" name="Django">
<configuration>
<option name="rootFolder" value="$MODULE_DIR$" />
<option name="settingsModule" value="core/settings.py" />
<option name="manageScript" value="$MODULE_DIR$/manage.py" />
<option name="environment" value="&lt;map/&gt;" />
<option name="doNotUseTestRunner" value="false" />
<option name="trackFilePattern" value="migrations" />
</configuration>
</facet>
</component>
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
<component name="TemplatesService">
<option name="TEMPLATE_CONFIGURATION" value="Django" />
<option name="TEMPLATE_FOLDERS">
<list>
<option value="$MODULE_DIR$/templates" />
</list>
</option>
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (lab_52)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/lab_52.iml" filepath="$PROJECT_DIR$/.idea/lab_52.iml" />
</modules>
</component>
</project>
\ No newline at end of file
"""
ASGI config for core 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/4.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
application = get_asgi_application()
"""
Django settings for core project.
Generated by 'django-admin startproject' using Django 4.2.4.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
import os
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/4.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-_@r+qfi=$qp2m@1hhn1vmyhv)9a-hvrenikwmb(4rq)+0hp3dc'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'web'
]
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 = 'core.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 = 'core.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/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/4.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = 'static/'
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, MEDIA_URL)
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
"""
URL configuration for core project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/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
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('web.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
"""
WSGI config for core 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/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
application = get_wsgi_application()
File added
#!/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', 'core.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()
from django.contrib import admin
from web.models import Category, Product
# Register your models here.
admin.site.register(Category)
admin.site.register(Product)
from django.apps import AppConfig
class WebConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'web'
from django import forms
from web.models import Product
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = [
'name', 'description',
'photo', 'category',
'qty', 'price'
]
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2023-08-03 17:18+0600\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
#: views.py:17
msgid "Create"
msgstr "Создать312312"
# Generated by Django 4.2.4 on 2023-08-02 10:33
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('description', models.TextField(max_length=2000, null=True)),
('photo', models.ImageField(upload_to='products')),
('qty', models.IntegerField(validators=[django.core.validators.MinValueValidator(0)])),
('price', models.DecimalField(decimal_places=2, max_digits=7)),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='product', to='web.category')),
],
),
]
# Generated by Django 3.2.19 on 2023-08-03 11:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('web', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Bucket',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('qty', models.PositiveIntegerField()),
('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='bucket', to='web.product')),
],
),
]
from django.core.validators import MinValueValidator
from django.db import models
class Category(models.Model):
name = models.CharField(max_length=100)
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(max_length=2000, null=True)
photo = models.ImageField(upload_to='products')
category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='product')
qty = models.IntegerField(validators=[MinValueValidator(0)])
price = models.DecimalField(max_digits=7, decimal_places=2)
class Bucket(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='bucket')
qty = models.PositiveIntegerField()
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.0.1/css/bootstrap.min.css"
integrity="sha512-Ez0cGzNzHR1tYAv56860NLspgUGuQw16GiOOp/I2LuTmpSK9xDXlgJz3XN4cnpXWDmkNBKXR/VDMTCnAaEooxA=="
crossorigin="anonymous" referrerpolicy="no-referrer"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
crossorigin="anonymous" referrerpolicy="no-referrer"/>
<link rel="stylesheet" href="{% static 'css/styles.css' %}">
<title>Title</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="{% url 'product_list' %}">Products</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse flex-grow-0" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="{% url 'product_create' %}">
Create
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container">
{% block title %}{% endblock %}
{% block content %}{% endblock %}
</div>
{#{% block script %}{% endblock %}#}
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.min.js" integrity="sha512-3dZ9wIrMMij8rOH7X3kLfXAzwtcHpuYpEgQg1OA4QAob1e81H8ntUQmQm3pBudqIoySO5j0tHN4ENzA6+n2r4w==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js" integrity="sha512-VK2zcvntEufaimc+efOYi622VN5ZacdnufnmX7zIhCPmjhKnOi9ZDMtg1/ug5l183f19gG1/cBstPO4D8N/Img==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</body>
</html>
\ No newline at end of file
{% extends 'base.html' %}
{% block content %}
<form action="" method="post">
{% csrf_token %}
{% include 'partial/form.html' %}
</form>
{% endblock %}
{% extends 'base.html' %}
{% block content %}
{% for bucket_obj in qs %}
<table>
<tr>
<td>
{{ bucket_obj.product.name }}
</td>
<td>
{{ bucket_obj.product.price }}
</td>
<td>
{{ bucket_obj.qty }}
</td>
<td>
{{ bucket_obj.total }}
</td>
</tr>
</table>
{% endfor %}
<h3>{{ total }}</h3>
{% endblock %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">{{ error }}</div>
{% endfor %}
{% for field in form.visible_fields %}
{% if field.errors %}
{% for error in field.errors %}
<div class="alert alert-danger">{{ error }}</div>
{% endfor %}
{% endif %}
{{ field.label }}
{{ field }}
{% endfor %}
{% for field in form.hidden_fields %}
{{ field }}
{% endfor %}
{% if button_text %}
<button type="submit" class="btn btn-success">{{ button_text }}</button>
{% endif %}
<div class="d-flex justify-content-center ">
<nav aria-label="...">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?{% if query %}{{ query }}&{% endif %}page={{ page_obj.previous_page_number }}">Previous</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#">Previous</a>
</li>
{% endif %}
{% for num in paginator.page_range %}
<li class="
page-item
{% if page_obj.number == num %}
active
{% else %}
{% endif %}
">
<a class="page-link" href="?{% if query %}{{ query }}&{% endif %}page={{ num }}">
{{ num }}
</a>
</li>
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?{% if query %}{{ query }}&{% endif %}page={{ page_obj.next_page_number }}">Next</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#">Next</a>
</li>
{% endif %}
</ul>
</nav>
</div>
\ No newline at end of file
{% if is_paginated %}
{% include 'partial/pagination.html' %}
{% endif %}
{% for product in products %}
<br>
<hr>
<br>
<h2>{{ product.title }}</h2>
<p>
<a href="{% url 'product_detail' id=product.id %}">
Подробнее
</a>
</p>
<br>
<hr>
<br>
{% endfor %}
{% if is_paginated %}
{% include 'partial/pagination.html' %}
{% endif %}
\ No newline at end of file
[<form action="" method="GET">
<label for="{{ form.search.id_for_label }}"></label>
{{ form.search }}
<button type="submit" class="btn btn-success">Submit</button>
{% for error in form.search.errors %}
<div class="alert alert-danger">{{ error }}</div>
{% endfor %}
</form>
\ No newline at end of file
{% extends 'base.html' %}
{% block content %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'partial/form.html' %}
</form>
{% endblock %}
{% extends 'base.html' %}
{% block content %}
<img src="{{ product.photo.url }}" alt="">
<br>
<h1>{{ product.name }}</h1>
<p>{{ product.description }}</p>
<p>{{ product.qty }}</p>
<p>{{ product.price }}</p>
<p>{{ product.category }}</p>
{% endblock %}
{% extends 'base.html' %}
{% block content %}
{% if is_paginated %}
{% include 'partial/pagination.html' %}
{% endif %}
{% for product in products %}
<br>
<hr>
<br>
<h2>{{ product.name }}</h2>
<p>
<a href="{% url 'product_detail' id=product.id %}">
Подробнее
</a>
</p>
<br>
<hr>
<br>
{% endfor %}
{% if is_paginated %}
{% include 'partial/pagination.html' %}
{% endif %}
{% endblock %}
\ No newline at end of file
from django.template.library import Library
library = Library()
@library.simple_tag
def multiply(a, b):
return a * b
from django.test import TestCase
# Create your tests here.
from django.urls import path
from web import views
urlpatterns = [
path('products/', views.ProductListView.as_view(), name='product_list'),
path('products/create/', views.ProductCreateView.as_view(), name='product_create'),
path('products/<int:id>/detail/', views.ProductDetailView.as_view(), name='product_detail'),
path('products/<int:id>/update/', views.ProductUpdateView.as_view(), name='product_update'),
path('products/<int:id>/delete/', views.ProductDeleteView.as_view(), name='product_delete'),
path('bucket/', views.BucketListView.as_view(), name='bucket_detail'),
path('bucket/create/', views.AddProductToBucketView.as_view(), name='bucket_create')
]
\ No newline at end of file
from typing import Any, Dict
from django import http
from django.http import HttpRequest, HttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse, reverse_lazy
from django.utils import translation
from django.views import generic
from web.forms import ProductForm
from web import models
class ProductCreateView(generic.CreateView):
model = models.Product
template_name = 'product/create_update.html'
form_class = ProductForm
extra_context = {
'button_text': translation.gettext('Create')
}
def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse:
print(translation.gettext('Create'))
return super().dispatch(request, *args, **kwargs)
def get_success_url(self) -> str:
return reverse('product_list')
class ProductUpdateView(generic.UpdateView):
model = models.Product
template_name = 'product/create_update.html'
form_class = ProductForm
pk_url_kwarg = 'id'
context_object_name = 'product'
extra_context = {
'button_text': 'Update'
}
class ProductDetailView(generic.DetailView):
model = models.Product
template_name = 'product/detail.html'
pk_url_kwarg = 'id'
context_object_name = 'product'
class ProductListView(generic.ListView):
model = models.Product
template_name = 'product/list.html'
context_object_name = 'products'
paginate_by = 3
class ProductDeleteView(generic.DeleteView):
model = models.Product
context_object_name = 'products'
pk_url_kwarg = 'id'
class AddProductToBucketView(generic.CreateView):
model = models.Bucket
fields = ['product']
template_name = 'bucket/create.html'
extra_context = {
'button_text': 'Add'
}
success_url = reverse_lazy('product_list')
def post(self, request: HttpRequest, *args: str, **kwargs: Any) -> HttpResponse:
print(request.POST)
self.product = get_object_or_404(models.Product, id=request.POST.get('product'))
form = self.get_form()
if form.is_valid():
product_in_bucket = self.model.objects.filter(product_id=self.product.id).first()
if self.product.qty != 0:
if not product_in_bucket:
form.instance.qty = 1
form.save()
elif product_in_bucket:
product_in_bucket.qty += 1
product_in_bucket.save(update_fields=['qty'])
self.product.qty -= 1
self.product.save()
return redirect(self.success_url)
return self.form_invalid(form)
class BucketListView(generic.ListView):
model = models.Bucket
template_name = 'bucket/detail.html'
context_object_name = 'bucket'
def get_context_data(self, **kwargs: Any) -> Dict[str, Any]:
total_sum = 0
qs = []
for bucket_obj in self.model.objects.select_related('product'):
obj = vars(bucket_obj)
total = bucket_obj.product.price * bucket_obj.qty
obj['total'] = total
obj['product'] = bucket_obj.product
qs.append(obj)
total_sum += total
kwargs['qs'] = qs
return super().get_context_data(total=total_sum, **kwargs)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment