0

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

i have '500' numbers of products in my csv file, now i want to upload all the products with csv file and store these name in my database.my concern is how to define my 'views.py' in restapi ?

i just tried with server side rendering, but it failed. it would be great if anyone can help me figure out what I am trying to do.

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)

Satyajit Barik
  • 65
  • 1
  • 2
  • 9

1 Answers1

0

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/how-to-upload-a-csv-file-in-django-3a0d6295f624

try format your csv to this blog or use separator you have on the csv

Fahim Ahmed
  • 141
  • 11
  • i was following this [link](https://medium.com/@simathapa111/how-to-upload-a-csv-file-in-django-3a0d6295f624) , but i am getting the issue here that 'UnboundLocalError at /upload/ local variable 'csv_file' referenced before assignment' – Satyajit Barik Feb 18 '20 at 08:58
  • it's showing me error at: 'MultiValueDictKeyError at /upload/ 'file'' – Satyajit Barik Feb 18 '20 at 09:05
  • https://stackoverflow.com/a/5895670/5277295 you will get `MultiValueDictKeyError` when the key you set in your view doesn't match with what you sent from frontend – Fahim Ahmed Feb 18 '20 at 09:08