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
This diff is collapsed.
<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