DJANGORESTAPI: как добавить продукты с помощью CSV-файла - PullRequest
0 голосов
/ 18 февраля 2020

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)

1 Ответ

0 голосов
/ 18 февраля 2020

views.py

import csv, io
from .models import Product

def profile_upload(request):  
    template = "profile_upload.html"
    data = Profile.objects.all()
    prompt = {
        'order': 'Order of the CSV should be product_title, sku, slug, image_path, price',
        'profiles': data    
              }
    csv_file = ''
    # GET request returns the value of the data with the specified key.
    if request.method == "GET":
        csv_file = request.FILES['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)

https://medium.com/@simathapa111 / как загрузить файл csv-in-django -3a0d6295f624

попробуйте отформатировать CSV в этом блоге или используйте разделитель, который у вас есть на CSV

...