74 lines
2.1 KiB
Python
74 lines
2.1 KiB
Python
from django.shortcuts import render
|
|
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
|
|
from django.template import loader
|
|
|
|
from .models import Sale, Product, ProductCategory
|
|
from .forms import ImportProductsForm
|
|
|
|
import csv
|
|
import io
|
|
|
|
def index(request):
|
|
return render(request, 'don_confiao/index.html')
|
|
|
|
|
|
def buy(request):
|
|
return HttpResponse("Nombre: ....")
|
|
|
|
|
|
def purchases(request):
|
|
purchases = Sale.objects.all()
|
|
context = {
|
|
"purchases": purchases,
|
|
}
|
|
return render(request, 'don_confiao/purchases.html', context)
|
|
|
|
|
|
def products(request):
|
|
rproducts = []
|
|
products = Product.objects.all()
|
|
for product in products:
|
|
rproduct = {
|
|
"name": product.name,
|
|
"price_list": product.price,
|
|
"uom": product.measuring_unit,
|
|
"categories": [c.name for c in product.categories.all()]
|
|
}
|
|
rproducts.append(rproduct)
|
|
|
|
return JsonResponse(rproducts, safe=False)
|
|
|
|
def products_index(request):
|
|
return render(request, 'don_confiao/products_index.html')
|
|
|
|
def import_products(request):
|
|
if request.method == "POST":
|
|
form = ImportProductsForm(request.POST, request.FILES)
|
|
if form.is_valid():
|
|
handle_import_products_file(request.FILES["csv_file"])
|
|
return HttpResponseRedirect("productos_index")
|
|
else:
|
|
form = ImportProductsForm()
|
|
return render(
|
|
request,
|
|
"don_confiao/import_products.html",
|
|
{'form': form}
|
|
)
|
|
|
|
def handle_import_products_file(csv_file):
|
|
data = io.StringIO(csv_file.read().decode('utf-8'))
|
|
reader = csv.DictReader(data, quotechar='"')
|
|
for row in reader:
|
|
product = Product()
|
|
product.name = row['producto']
|
|
product.price = row['precio']
|
|
product.measuring_unit = row['unidad']
|
|
product.save()
|
|
|
|
categories = [n.strip for n in row["categorias"].split("&")]
|
|
for category in categories:
|
|
category_model, _ = ProductCategory.objects.get_or_create(
|
|
name=category
|
|
)
|
|
product.categories.add(category_model)
|