models.py
class Product(models.Model):
title = models.CharField(max_length=150)
slug = models.SlugField(unique=True)
description = models.CharField(max_length=350)
image = models.ImageField(upload_to='images/')
def __str__(self):
return self.title
У меня есть 500 номеров продуктов в моем файле csv, теперь я хочу загрузить все продукты с файлом csv и сохранить их названия в моей базе данных. как определить мой 'views.py' в restapi?
Я только что попытался с рендерингом на стороне сервера, но это не удалось. было бы здорово, если бы кто-нибудь помог мне понять, что я пытаюсь сделать.
views.py
import csv, io
from .models import Product
def profile_upload(request):
template = "profile_upload.html"
data = Product.objects.all()
prompt = {
'order': 'Order of the CSV should be product_title, sku, slug, image_path, price',
'profiles': data
}
# GET request returns the value of the data with the specified key.
if request.method == "GET":
return render(request, template, prompt)
csv_file = request.FILES['file'] # let's check if it is a csv file
if not csv_file.name.endswith('.csv'):
messages.error(request, 'THIS IS NOT A CSV FILE')
data_set = csv_file.read().decode('UTF-8') # setup a stream which is when we loop through each line we are able to handle a data in a stream
io_string = io.StringIO(data_set)
next(io_string)
for column in csv.reader(io_string, delimiter=',', quotechar="|"):
_, created = Product.objects.update_or_create(
title=column[0],
slug=column[1],
description=column[2],
image=column[3],
)
context = {}
return render(request, template, context)