<repo_name>DImasBo/shop-django<file_sep>/ecomapp/forms.py
# -*- coding: utf-8 -*-
from django import forms
from django.utils import timezone
from ecomapp.models import Order, Page, Category
from django_summernote.widgets import SummernoteWidget

class PageEditForm(forms.ModelForm):
	class Meta:
		model = Page
		fields = ['description']
		widgets = {
			'description' : SummernoteWidget(),
		}

class CategoryForm(forms.ModelForm):
	class Meta:
		model = Category
		fields = ['name']

class OrderForm(forms.ModelForm):

	class Meta:
		model = Order
		fields = ['second_name','first_name','last_name','phone_number','email','buying_type','address','comments']
		labels = {
			"email": "електрона пошта(необов'ясково, для підписки на вигідні пропозиції)"
		}
<file_sep>/ecomapp/admin.py
from django.contrib import admin
from .models import Category, Product, Cart, CartItem, Product,ProductImage,Reduction ,Order, Page
from django_summernote.admin import SummernoteModelAdmin

def make_paid(modeladmin, request, queryset):
	queryset.update(status='PAID_status')
def make_ip(modeladmin, request, queryset):
	queryset.update(status='IP_status')
def make_aip(modeladmin, request, queryset):
	queryset.update(status='AIP_status')

make_aip.short_description = 'Помітити як Прийнятий в обробку'
make_ip.short_description = 'Помітити як В обробці'
make_paid.short_description = 'Помітити як Оплачено'

# cart = models.ForeignKey(Cart,on_delete=models.CASCADE, verbose_name='Корзина')
class OrderAdmin(admin.ModelAdmin):
#	fields = ('products',('second_name','first_name','last_name'), ('phone_number','email'),'buying_type','address','status','comments')
	list_filter = ['status']
	actions = [make_paid, make_aip, make_ip]

class ProductImageInline(admin.TabularInline):
    model = ProductImage
    extra = 1

class ProductAdmin(SummernoteModelAdmin,admin.ModelAdmin):
    fields = ('title','description','price','category',('count','available'),'slug','album_cover')
    inlines = [ ProductImageInline, ]
    summernote_fields = ('description')

class PageAdmin(SummernoteModelAdmin):
    summernote_fields = ('description')

# Register your models here.
admin.site.register(Page, PageAdmin)
admin.site.register(Category)
# admin.site.register(Cart)
# admin.site.register(CartItem)
admin.site.register(Order, OrderAdmin)
# admin.site.register(Reduction)
admin.site.register(Product,ProductAdmin)
<file_sep>/ecomapp/urls.py
from django.urls import path, include
from ecomapp import views

urlpatterns = [
	path('',views.IndexView.as_view(), name='index'),
#prodicts url
	path('search/',views.SearchView.as_view(), name = 'search'),
	path('product/<str:slug>', views.ProductDetailView.as_view(),name='product_detail_url'),

#pages url
	path('page/<str:slug>', views.PageView.as_view() , name='page_url'),
	#edit	
	path('page_edit/<str:slug>', views.PageEdit.as_view() , name='page_edit_url'),
#orders url
	path('order/', views.CreateOrder.as_view(),name='create_order_url'),
	path('orders/', views.ListOrder.as_view(),name='order_list_url'),
	path('order/show/<int:id>', views.OrderDetailView.as_view(),name='order_detail_url'),
	#add product in order
	path('order/add/product/order=<int:id>', views.add_product_in_order,name='add_product_in_order_url'),
	path('order/add_product/category/<str:slug>', views.OrderCategoryView.as_view(), name='add_order_category_url'),
	path('order/add_product', views.OrderIndexView.as_view(), name='add_order_index_url'),
	path('order/add/cart/', views.OrderCartView.as_view(),name='order_cart_url'),
	path('order/add/save/', views.save_order, name='save_order_url'),
	path('order/add/product/<str:slug>',views.OrderProductDetailView.as_view(),name='order_product_detail_url'),
#	path('order/cart/add/<str:slug>', views.add_to_order_cart,name='add_order_to_cart_url'),
	
	#edit 	
	path('order/remove/<int:id>/<int:item_id>',views.remove_product_order,name='remove_product_order_url'),
	path('order/add/<int:id>/<int:item_id>', views.add_product_order,name='add_product_order_url'),
	path('order/minus/<int:id>/<int:item_id>', views.minus_product_order ,name='minus_product_order_url'),

	path('order_finish/',views.OrderFinish.as_view(), name='order_finish_url'),
#carts url
	path('cart/', views.CartView.as_view(),name='cart_url'),
	#edit	
	path('cart/minus/<str:slug>',views.minus_to_cart,name='minus_to_cart_url'),
	path('cart/add/<str:slug>',views.add_to_cart,name='add_to_cart_url'),
	path('cart/remove/<str:slug>',views.remove_from_view,name='remove_from_view_url'),

#categories url
	path('category/<str:slug>',views.CategoryView.as_view(), name='category_list_url' ),
	#edit	
	path('edit_categories/',views.CategoriesEditView.as_view(),name='edit_categories_url'),
]
<file_sep>/ecomapp/views.py
from django.shortcuts import render
from django.shortcuts import redirect
from django.urls import reverse
from django.views.generic import TemplateView
from ecomapp.models import Category, Product, Cart, CartItem, ProductImage, Order, Page
from django.core.paginator import Paginator

from django.http.response import HttpResponseRedirect
from ecomapp.forms import  OrderForm, PageEditForm, OrderForm, CategoryForm

from django.db.models import Q

from django.contrib.auth.mixins import LoginRequiredMixin 
from django.core.mail import send_mail
from django.conf import settings
from decimal import Decimal
from ecomapp.models import sum_items
# Create your views here.
def get_cart(request):
	try:
		cart_id = request.session['cart_id']
		cart = Cart.objects.get(id=cart_id)
		request.session['total'] = cart.item.count()
	except:
		cart = Cart()
		cart.save()
		cart_id = cart.id
		request.session['cart_id'] = cart_id
		cart = Cart.objects.get(id=cart_id)
	return cart

def delete_order_session(request):
	try:
		del(request.session['order_id'])
	except:
		print('not delete')
	try:
		del(request.session['cart_order_id'])
	except:
		print('not delete cart_order_id')
	try:
		del(request.session['order_total'])
	except:
		print('not delete order_total')
	return request

class BaseView(TemplateView):
	template_name = 'ecomapp/index.html'
	
	def get(self, request):
		request = delete_order_session(request)
		cart = get_cart(request)	
		categories = Category.objects.all() 
		lorem_ipsum = '''Lorem Ipsum - це текст-"риба", що використовується в друкарстві та дизайні. Lorem Ipsum є, фактично, стандартною "рибою" аж з XVI сторіччя, коли невідомий друкар взяв шрифтову гранку та склав на ній підбірку зразків шрифтів. "Риба" не тільки успішно пережила п'ять століть, але й прижилася в електронному верстуванні, залишаючись по суті незмінною. Вона популяризувалась в 60-их роках минулого сторіччя завдяки виданню зразків шрифтів Letraset, які містили уривки з Lorem Ipsum, і вдруге - нещодавно завдяки програмам комп'ютерного верстування на кшталт Aldus Pagemaker, які використовували різні версії Lorem Ipsum.'''
		try:
			description = Page.objects.get(slug='description')
		except:
			description = Page(title='Опис footer' , description= 'Опис про сайт',slug='description')
			description.save()
		
		try:
			about_us = Page.objects.get(slug='about-us')
		except:
			about_us = Page(title='Про нас' , description= lorem_ipsum,slug='about-us')
			about_us.save()
		
		try:
			contacts = Page.objects.get(slug='contacts')
		except:
			contacts = Page(title='Контакти', description= lorem_ipsum,slug='contacts')
			contacts.save()
		
		try:
			buying_type = Page.objects.get(slug='buying-type')
		except:
			buying_type = Page(title='Доставка', description= lorem_ipsum,slug='buying-type')
			buying_type.save()
		

		self.context = {
			'categories': categories,
			'cart':cart,
			'description':description,
			'buying_type':buying_type,
			'about_us':about_us,
			'contacts':contacts,
		}
		return render(request,self.template_name,context=self.context)

class ListOrder(LoginRequiredMixin,BaseView):

	template_name = 'ecomapp/orders.html'
	login_url = '/admin/'
	redirect_field_name = 'redirect_to'
	def get(self, request):
		super().get(request)
		orders = Order.objects.all()
		self.context['orders'] = orders
		return render(request, self.template_name, context=self.context )

class OrderDetailView(LoginRequiredMixin,BaseView):
	login_url = '/admin/'
	redirect_field_name = 'redirect_to'
	template_name = 'ecomapp/order_detail.html'
	def get(self, request,id):
		super().get(request)
		order = Order.objects.get(id=id)
		self.context['form'] = OrderForm(instance = order)
		self.context['order'] = order
		return render(request,self.template_name,context=self.context)

	def post(self, request, id):
		super().get(request)
		order = Order.objects.get(id=id)
		bound_form = OrderForm(request.POST, instance=order)
		self.context['form'] = bound_form
		self.context['order'] = order
		if bound_form.is_valid():
			form = bound_form.save()
		return render(request,self.template_name,context=self.context)

class PageView(BaseView):

	template_name = 'ecomapp/page.html'

	def get(self,request,slug):
		super().get(request)
		self.context['page'] = Page.objects.get(slug=slug)
		return render(request, self.template_name, context=self.context)

class PageEdit(LoginRequiredMixin,BaseView):
	template_name = 'ecomapp/page_edit.html'
	login_url = '/admin/'
	redirect_field_name = 'redirect_to'
	def get(self, request,slug):
		super().get(request)
		page = Page.objects.get(slug=slug)
		self.context['form'] = PageEditForm(instance = page)
		self.context['page'] = page
		return render(request,self.template_name,context=self.context)

	def post(self,request,slug):
		super().get(request)
		self.context['page'] = Page.objects.get(slug=slug)
		bound_form = PageEditForm(request.POST, instance=self.context['page'])
		self.context['form'] = bound_form
		if bound_form.is_valid():
			form = bound_form.save()
			return redirect(reverse('page_url', kwargs={'slug':form.slug}))
		return render(request,self.template_name,context=self.context)

class IndexView(BaseView):

	def get(self,request):
		super().get(request)
		products = Product.objects.filter(available=True)
		#масив для вюшки з категорією на головній і її продуктами
		categories_index = []
		for category in self.context['categories']:
			p = products.filter(category=category)
			if len(p) > 0:
				c = {
					'name':category.name,
					'url':category.get_absolute_url(),
					'products':p[:3]
				}
				categories_index.append(c)
		self.context['categories_index'] = categories_index
		return render(request,self.template_name,context=self.context)

class SearchView(BaseView):

	template_name = 'ecomapp/product_list.html'
	def get(self,request):
		super().get(request)
		search_query = request.GET.get('search', '')
		if search_query == '':
			return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
		self.context['category'] = Category()
		self.context['category'].name = 'Пошук: ' + search_query
		products = Product.objects.filter(Q(title__icontains=search_query) | Q(description__icontains=search_query) )
		paginator = Paginator(products, 9)
		page_number = request.GET.get('page', 1)
		page = paginator.get_page(page_number)
		self.context['page'] = page
		return render(request,self.template_name,context=self.context)

class CategoryView(BaseView):

	template_name = 'ecomapp/product_list.html'
	def get(self,request,slug):
		super().get(request)		
		self.context['category'] = self.context['categories'].get(slug=slug)
		self.context['category'].name = 'Категорія: ' + self.context['category'].name 
		products = Product.objects.filter(category=self.context['category'])
		paginator = Paginator(products, 9)
		page_number = request.GET.get('page', 1)
		page = paginator.get_page(page_number)
		self.context['page'] = page
		self.context['is_paginated'] = page.has_other_pages()

		if page.has_previous():
			self.context['prev_url'] = '?page={}'.format(page.previous_page_number())
		else:
			self.context['prev_url'] = False

		if page.has_next():
			self.context['next_url'] = '?page={}'.format(page.next_page_number())
		else:
			self.context['next_url'] = False
		return render(request, self.template_name ,context=self.context)

class CategoriesEditView(LoginRequiredMixin,BaseView):
	template_name = 'ecomapp/edit_categories.html'
	login_url = '/admin/'
	redirect_field_name = 'redirect_to'

	def get(self,request):
		super().get(request)
		self.context['form'] = CategoryForm()
		return render(request,self.template_name,context=self.context)

	def post(self,request):
		super().get(request)
		self.context['form'] = CategoryForm()
		bound_form = CategoryForm(request.POST)
		if bound_form.is_valid():
			form = bound_form.save()
			self.context['categories'] = Category.objects.all()
			return render(request,self.template_name,context=self.context)			
		return render(request,self.template_name,context=self.context)		

class ProductDetailView(BaseView):

	template_name = 'ecomapp/product_detail.html'
	def get(self,request,slug):
		super().get(request)		
		self.context['product'] = Product.objects.get(slug=slug)
		product_album = ProductImage.objects.filter(product=self.context['product'])
		if len(product_album) > 0:
			self.context['product_album'] = product_album 
		return render(request, self.template_name ,context=self.context)

#order views
def remove_product_order(request,id, item_id):
	order = Order.objects.get(id=id)
	order.remove_product_order(item_id)
	return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

def add_product_order(request,id, item_id):
	order = Order.objects.get(id=id)
	order.add_product_order(item_id)
	return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

def minus_product_order(request,id, item_id):
	order = Order.objects.get(id=id)
	order.minus_product_order(item_id)
	return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

def get_cart_order(request):
	try:
		cart_order_id = request.session['cart_order_id']
		cart = Cart.objects.get(id=cart_order_id)
		request.session['order_total'] = cart.item.count()
	except:
		cart = Cart()
		cart.cart_total = Order.objects.get(id=request.session['order_id']).total
		cart.save()
		cart_order_id = cart.id
		request.session['cart_order_id'] = cart_order_id
		cart = Cart.objects.get(id=cart_order_id)
	return cart

class OrderProductDetailView(LoginRequiredMixin,TemplateView):
	template_name = 'ecomapp/order_product_detail.html'
	login_url = '/admin/'
	redirect_field_name = 'redirect_to'
	def get(self,request,slug):
		product = Product.objects.get(slug=slug)
		cart_order = get_cart_order(request)
		context = {
		'product' :product ,
		'cart_order':cart_order,
		'product_album' : ProductImage.objects.filter(product=product),
		'categories':  Category.objects.all()
		}
		return render(request, self.template_name ,context=context)

class OrderIndexView(LoginRequiredMixin,TemplateView):
	template_name = "ecomapp/order_index.html"
	login_url = '/admin/'
	redirect_field_name = 'redirect_to'
	def get(self,request):
		cart_order = get_cart_order(request)
		search_query = request.GET.get('search', '')
		if search_query != '':
			title = 'Пошук'
			products = Product.objects.filter(Q(title__icontains=search_query) | Q(description__icontains=search_query) )
		else:
			title = 'всі продукти.'
			products = Product.objects.all()
		context = {
			'cart_order' : cart_order,
			'categories' : Category.objects.all(),
			'products' : products,
			'title': title
		}
		return render(request, self.template_name ,context=context)

class OrderCategoryView(LoginRequiredMixin,TemplateView):
	template_name = "ecomapp/order_index.html"
	context = {}
	login_url = '/admin/'
	redirect_field_name = 'redirect_to'
	def get(self,request, slug):
		cart_order = get_cart_order(request)
		self.context['cart_order'] = cart_order
		self.context['categories'] = Category.objects.all()
		category = self.context['categories'].filter(slug=slug)
		self.context['products'] = Product.objects.filter(category=category)
		return render(request, self.template_name ,context=self.context)


class OrderCartView(LoginRequiredMixin,TemplateView):
	template_name = "ecomapp/order_cart.html"
	context = {}
	login_url = '/admin/'
	redirect_field_name = 'redirect_to'
	def get(self, request):
		cart_order = get_cart_order(request)
		self.context['cart_order'] = cart_order
		self.context['categories'] = Category.objects.all()
		return render(request, self.template_name ,context=self.context)

def add_product_in_order(request,id):
	order = Order.objects.get(id=id)
	request.session['order_id'] = id
	cart = get_cart_order(request)
	for item in cart.item.all():
		cart.item.remove(item)
	for item in order.products.all():
		cart.item.add(item.id)
	cart.save()
	return redirect(reverse('add_order_index_url'))

def save_order(request):
	cart_order = get_cart_order(request)
	id = request.session['order_id']
	order = Order.objects.get(id=id)
	if order.products.count() > 0:
		for item in order.products.all():
			cart_order.item.remove(item)
	for item in cart_order.item.all():
		order.products.add(item)
	order.set_sum(cart_order.cart_total)
	request = delete_order_session(request)
	return redirect(reverse('order_detail_url',kwargs={'id':id}))

class CreateOrder(BaseView):
	template_name = 'ecomapp/order.html'
	
	def send_order(self, order):
		email = settings.EMAIL_HOST_USER
		message = '''Клієт {} {} {} оформив замовлення.<br>
Перетелефонуйте для уточнення деталей.
Сума: {}<br>
Номер: {}<br>c
<a href="https://svetlyachokshop.com{}">переглянути </a>'''.format(order.second_name, order.first_name, order.last_name, order.total, order.phone_number, order.get_absolute_url())
		tema = 'Замовлення !!!'
		try:
			send_mail(tema, message, email, [email] ,html_message=message, fail_silently=False)
		except:
			print('email error!!!!!!!!!!!!!!!!!!!!!!!!!')

	def get(self,request):
		super().get(request)
		self.context['form'] = OrderForm()
		return render(request, self.template_name, context=self.context )

	def post(self,request):
		super().get(request)
		bound_form = OrderForm(request.POST)
		if bound_form.is_valid():
			form = bound_form.save(commit=False)
			form.total = self.context['cart'].cart_total
			form.products_add(self.context['cart'])
			try:
				self.send_order(form)
			except:
				print("not network") 	
			return redirect(reverse('order_finish_url'))
		self.context['form'] = bound_form 
		return render(request, self.template_name, context=self.context )

class OrderFinish(BaseView):

	template_name = 'ecomapp/order_finish.html'
# cart views
class CartView(BaseView):

	template_name = 'ecomapp/cart.html'

def add_to_cart(request, slug):
	try:
		if request.session['order_id']:
			cart = get_cart_order(request)
	except:
		cart = get_cart(request)
	
	flug = False
	product = Product.objects.get(slug=slug)
	els = list(cart.item.all())
	for item in els:
		if item.product == product:
			item.add_qty()
			flug = True
			cart.set_sum(sum_items(els))
			break
	if flug==False:
		cart.add_to_cart(slug)
	return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

def minus_to_cart(request, slug):
	try:
		if request.session['order_id']:
			cart = get_cart_order(request)
	except:
		cart = get_cart(request)
	product = Product.objects.get(slug=slug)
	els = list(cart.item.all())
	for item in els:
		if item.product ==  product:
			item.minus_qty()
			cart.set_sum(sum_items(els))
			break
	return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))

def remove_from_view(request, slug):
	try:
		if request.session['order_id']:
			cart = get_cart_order(request)
	except:
		cart = get_cart(request)
	cart.remove_product_cart(slug)
	return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
<file_sep>/ecomapp/models.py
from django.db import models

from django.shortcuts import reverse

from django.utils.text import slugify
from transliterate import translit

from django.core.validators import MaxValueValidator, MinValueValidator

from decimal import Decimal
# Create your models here.

class Category(models.Model):
	name = models.CharField(max_length=50, verbose_name = 'Назва')
	slug = models.SlugField(blank=True,verbose_name="Ключове слово(не обов'ясково)")

	def __str__(self):
		return self.name

	def get_absolute_url(self):
		return reverse('category_list_url',kwargs={'slug':self.slug})

	def save(self, *args, **kwargs):
		if not self.slug and self.name:
			slug = slugify(translit(self.name,'uk', reversed=True))
			self.slug = slug
		super().save( *args, **kwargs)

	class Meta:
		verbose_name = 'Категорію'
		verbose_name_plural = 'Категорії'
		ordering = ['name']
		
class Page(models.Model):

	title = models.CharField(max_length=100, verbose_name='Заголовок')
	description = models.TextField(verbose_name='Опис')
	slug = models.SlugField(verbose_name="Ключове слово")

	def __str__(self):
		return self.title

	def get_absolute_url(self):
		return reverse('page_url', kwargs={'slug':self.slug})

	def get_edit_url(self):
		return reverse('page_edit_url', kwargs={'slug':self.slug})

	class Meta:
		verbose_name_plural = 'Сторінки сайта'
		verbose_name = 'Сторінку сайта'

def image_folder(instance, filename):
	filename = instance.slug + '.' + filename.split('.')[1]
	return "{0}/{1}".format(instance.slug,filename)

def image_folder_cover(instance, filename):
	filename = instance.slug + '_cover.' + filename.split('.')[-1]
	return "{0}/{1}".format(instance.slug,filename)

def image_folder_album(instance, filename):
	filename = instance.product.slug + '.' + filename.split('.')[-1]
	return "{0}/{1}".format(instance.product.slug, filename)

class Product(models.Model):

	title = models.CharField(max_length=50, verbose_name='Заголовок')
	description = models.TextField( verbose_name='Опис')
	price = models.DecimalField(max_digits=9, decimal_places=2,  verbose_name='Ціна')
	category = models.ForeignKey(Category,on_delete=models.CASCADE, verbose_name='Категорія')
	count = models.PositiveIntegerField(default=1,  verbose_name='Кількість товару')
	slug = models.SlugField(blank=True,  verbose_name="Ключове слово(не обов'ясково)")
	available = models.BooleanField(default=True, verbose_name='В наявності')
	date = models.DateTimeField(auto_now_add=True)
	album_cover = models.ImageField(upload_to=image_folder_cover, verbose_name='Фото обкладинки')

	def get_absolute_url(self):
		return reverse('product_detail_url',kwargs={'slug':self.slug})

	def get_add_order_url(self):
		return reverse('order_product_detail_url',kwargs={'slug':self.slug})

	def delete(self, *args, **kwargs):
		self.album_cover.delete(save=False)
		super().delete(args, kwargs)

	def save(self, *args, **kwargs):
		if not self.slug and self.title:
			slug = slugify(translit(self.title,'uk', reversed=True))
			self.slug = slug
		super().save( *args, **kwargs)

	def get_add_to_cart_url(self):
		return reverse('add_to_cart_url',kwargs={'slug':self.slug})

	def get_add_to_cart_order_url(self):
		return reverse('add_to_cart_url',kwargs={'slug':self.slug})

	def __str__(self):
		return self.title

	class Meta:
		verbose_name = 'Продукт'
		verbose_name_plural = 'Продукти'
		ordering = ['-date']

class Reduction(models.Model):

	title = models.CharField(max_length = 100)
	reduction = models.PositiveSmallIntegerField(default = 1, validators=[
            MaxValueValidator(100),
            MinValueValidator(1)
        ])
	description = models.TextField()
	product = models.ManyToManyField(Product)
	image = models.ImageField(upload_to=image_folder, blank=True, null=True)

	date = models.DateTimeField(auto_now_add = True)

	def __str__(self):
		return "{0}% | {1}".format(str(self.reduction), self.title)

	class Meta:
		verbose_name = 'Знишку'
		verbose_name_plural = 'Знишки'
		ordering = ['-date']

class ProductImage(models.Model):
	
	product = models.ForeignKey(Product, related_name='images',on_delete=models.CASCADE)
	images = models.ImageField(upload_to=image_folder_album )

	def __str__(self):
		return self.images.url

	def delete(self, *args, **kwargs):
		self.images.delete(save=False)
		super().delete(*args,**kwargs)

	class Meta:
		verbose_name = 'фото'
		verbose_name_plural = 'фото'

class CartItem(models.Model):

	product = models.ForeignKey(Product,on_delete=models.CASCADE,verbose_name='Продукт')
	qty = models.PositiveIntegerField(default=1,verbose_name='Назва')
	item_total = models.DecimalField(max_digits=9,decimal_places=2,default=0,blank=True,verbose_name="Сума(необов'язково, рахує самостійно)")

	def __str__(self):
		return "{0} Cart item for product {1}".format(self.id,self.product.title)

	def minus_qty(self):
		if self.qty > 1:
			self.qty -= 1
			self.item_total = self.qty * self.product.price
		self.save()
	
	
	def add_qty(self):
		if self.qty + 1 <= self.product.count:
			self.qty += 1
			self.item_total = self.qty * self.product.price
		self.save()

	def save(self, *args, **kwargs):
		if not self.item_total:
			self.item_total = self.qty * self.product.price 
		super().save( *args, **kwargs)

def sum_items(elements,save = True):
	total_price = Decimal(0.00)
	for item in elements:
		total_price = total_price + item.item_total
	return total_price

class Cart(models.Model):

	item = models.ManyToManyField(CartItem, blank=True)
	cart_total = models.DecimalField(max_digits=9,decimal_places=2,default=0)

	def __str__(self):
		return str(self.id)

	def add_to_cart(self,slug):
		product = Product.objects.get(slug=slug)
		new_item = CartItem.objects.get_or_create(product=product,item_total=product.price)[0]
		els = list(self.item.all())
		if new_item not in els:
			self.item.add(new_item)
			els.append(new_item)
#		print(els)
		self.set_sum(sum_items(els))


	def remove_product_cart(self,slug):
		product = Product.objects.get(slug=slug)
		els = list(self.item.all())
		for item in els:
			if item.product == product:
				self.item.remove(item)
				item.delete()
				els.remove(item)
#		print(els)
		self.set_sum(sum_items(els))

	def get_qty(self):
		return str(self.item.count())

	def set_sum(self,sum, save=True):
		self.cart_total = sum
		if save:
			self.save()

class Order(models.Model):
# Accepted in processing = AIP_status, 'Прийнятий в обробку'
# In processing = IP_status, 'В обробці'
# Paid = PAID_status, 'Оплачено'

	ORDER_STATUS_CHOICES = (
		('AIP_status', 'Прийнятий в обробку'),
		('IP_status', 'В обробці'),
		('PAID_status', 'Оплачено'),
	)

	DELIVERY_STATUS = (
		('nova_poshta', 'Нова пошта'),
		('ukr_poshta', 'Укр-пошта'),
	)
	# cart = models.ForeignKey(Cart,on_delete=models.CASCADE, verbose_name='Корзина')
	products = models.ManyToManyField(CartItem, verbose_name='Товари')
	total = models.DecimalField(max_digits=9, decimal_places=2, default = 0, verbose_name="Сума(необов'язково, рахує самостійно)",blank=True)
	second_name = models.CharField(max_length=200, verbose_name='Прізвище')
	first_name = models.CharField(max_length=200, verbose_name='Імя')
	last_name = models.CharField(max_length=200, verbose_name='Побатькові')
	phone_number = models.CharField(max_length=9, verbose_name='Номер телефону +380')
	email = models.EmailField(blank = True, verbose_name='Електрона пошта')
	buying_type = models.CharField(max_length=40,choices=DELIVERY_STATUS, verbose_name='Спосіб доставки')
	address = models.CharField(max_length=255, verbose_name='адреса')
	status = models.CharField(max_length=100, choices=ORDER_STATUS_CHOICES,default='AIP_status', verbose_name='Статус')
	comments = models.TextField(blank = True, verbose_name='Коментарь')
	date = models.DateTimeField(auto_now_add=True)


	def get_admin_url(self):
		return reverse('order_detail_url',kwargs={'id':self.id})
	    
	def save(self, *args, **kwargs):
		super().save( *args, **kwargs)
		for item in self.products.all():
			if item.product.count - item.qty < 1:
				item.product.count = 0
				item.product.available = False
			else:
				item.product.count -= item.qty
			item.product.save()

	def add_product_order(self,item_id):
		C_item = CartItem.objects.get(id=item_id)
		els = list(self.products.all())
		for item in els:
			if item == C_item:
				item.add_qty()
				break
		self.set_sum(sum_items(els))

	def minus_product_order(self,item_id):
		C_item = CartItem.objects.get(id=item_id)
		els = list(self.products.all())
		for item in self.products.all():
			if item == C_item:
				item.minus_qty()
				break
		self.set_sum(sum_items(els))
	
	def delete(self, *args, **kwargs):
		for item in self.products.all():
			item.delete()
		super().delete(*args, **kwargs)

	def remove_product_order(self,item_id):
		C_item = CartItem.objects.get(id=item_id)
		els = list(self.products.all())
		for item in els:
			if item == C_item:
				self.products.remove(item)
				els.remove(item)
				break
		C_item.delete()
		self.set_sum(sum_items(els))

	def products_add(self,cart):
		self.save()
		for item in cart.item.all():
			new_item = CartItem(product=item.product,qty=item.qty,item_total=item.item_total)
			new_item.save()
			item.delete()
			self.products.add(new_item.id)
		self.save()
		cart.delete()

	def set_sum(self, sum,save = True):
		self.total = sum
		if save:
			self.save()

	def __str__(self):
		return "{} /ДАТА: {} /ПІБ: {} {} {}".format(str(self.id), str(self.date.strftime("%d-%B-%Y")), self.second_name,self.first_name, self.last_name)

	def get_absolute_url(self):
		return reverse('order_detail_url',kwargs={'id':self.id})

	def get_add_product_in_order(self):
		return reverse('add_product_in_order_url',kwargs={'id':self.id})

	class Meta:
		ordering = ['-date']
		verbose_name = 'Замовлення'
		verbose_name_plural = 'Замовлення'<file_sep>/requirements.txt
certifi==2019.6.16
chardet==3.0.4
Django==2.2.3
django-crispy-forms==1.7.2
django-storages==1.7.1
django-summernote==0.8.11.4
dropbox==9.4.0
gunicorn==19.9.0
idna==2.8
Pillow==5.1.0
psycopg2==2.8.3
pytz==2019.1
requests==2.22.0
six==1.12.0
sqlparse==0.3.0
transliterate==1.10.2
urllib3==1.25.3