Iterator should return strings, not bytes (the file should be opened in text mode)

Question:

List item

this is my code..

def import_excel(request):

  if request.method == 'POST':
    person_resource = PersonResource()

    dataset  = Dataset()
    new_person = request.FILES['myfile']
    if not new_person.name.endswith('csv'):
      messages.info(request,'Wrong format')
      return render(request,'upload.html')
    
    imported_data = dataset.load(new_person.read(),format='csv')
    for data in imported_data:
      value = Person(
        data[0],
        data[1],
        data[2]
      )
     value.save()
  return render(request,'upload.html')

while importing the csv file to the database getting the error:

iterator should return strings, not bytes (the file should be opened in text mode)

like this

This is my model…

class Person(models.Model):
  name    = models.CharField(max_length=200)
  marks   = models.IntegerField()
  def __str__(self):
    return self.name  

This is the csv file
This is my csv file..

Asked By: swamy patel

||

Answers:

You can read the data of the uploaded file as follows and the problem will be solved.

new_person = request.FILES['myfile'].read().decode("utf-8")

According to the model you don’t have an ID, just make the following changes to log in

for data in imported_data:
  value = Person(
    data[1],
    int(data[2])
  )
 value.save()

But if you want to have an ID in the model, then you must change the model as follows and write the loop as follows (of course, you must have values in the ID column in the CSV file)

class Person(models.Model):
  id      = models.IntegerField(primary_key=True)
  name    = models.CharField(max_length=200)
  marks   = models.IntegerField()
  def __str__(self):
    return self.name

loop try this

for data in imported_data:
  value = Person(
    int(data[0]),
    data[1],
    int(data[2])
  )
 value.save()
Answered By: Amin Zayeromali
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.