Feat: importando productos desde csv.
This commit is contained in:
@@ -1,9 +1,12 @@
|
||||
from django.shortcuts import render
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
|
||||
from django.template import loader
|
||||
|
||||
from .models import Sale
|
||||
from .models import Sale, Product
|
||||
from .forms import ImportProductsForm
|
||||
|
||||
import csv
|
||||
import io
|
||||
|
||||
def index(request):
|
||||
return render(request, 'don_confiao/index.html')
|
||||
@@ -22,18 +25,42 @@ def purchases(request):
|
||||
|
||||
|
||||
def products(request):
|
||||
products = [
|
||||
{
|
||||
"name": "Aceite de Coco Artesanal 500ml",
|
||||
"price_list": 50000,
|
||||
"uom": "Unit",
|
||||
"category": "Aceites"
|
||||
},
|
||||
{
|
||||
"name": "Cafe 500ml",
|
||||
"price_list": 14000,
|
||||
"uom": "Unit",
|
||||
"category": "Cafes"
|
||||
},
|
||||
]
|
||||
return JsonResponse(products, safe=False)
|
||||
rproducts = []
|
||||
products = Product.objects.all()
|
||||
for product in products:
|
||||
rproduct = {
|
||||
"name": product.name,
|
||||
"price_list": product.price,
|
||||
"uom": product.measuring_unit,
|
||||
"category": ""#.join('&', [c for c in product.categories])
|
||||
}
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user