0

Before explaining my problem in detail, here are my codes.

models.py

class SimilarStore(models.Model):
    store = models.ForeignKey(Store)

    domain = models.CharField(max_length=100, blank=True)
    score = models.IntegerField(blank=True)
    rank = models.IntegerField(blank=True)

    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateTimeField(auto_now=True)

forms.py

class SimilarStoreForm(forms.ModelForm):
    similarstore_csv = forms.FileField()

    class Meta:
        model = SimilarStore
        fields = ('store', 'similarstore_csv')

    def save(self, commit=False, *args, **kwargs):
        form_input = SimilarStoreForm()

        self.store = self.cleaned_data['store']
        csv_file = self.cleaned_data['similarstore_csv']

        for line in csv_file:
            self.domain = line[0]
            self.score = line[1]
            self.rank = line[2]
            form_input.save()

data.csv

roolee.com,100,125225
piperandscoot.com,29.3,222166
calledtosurf.com,23.8,361542
cladandcloth.com,17.9,208670
neeseesdresses.com,9.6,251016
...

I'm trying to upload data.csv to DB. I need each column data in the file to go into domain, score, rank in SimilarStore model. This is what I'm trying to do with the above codes.

However, when I upload the file and submit it, an error shows up, saying

expected str, bytes or os.PathLike object, not InMemoryUploadedFile

I've done some research about it, but nothing worked for my case. Can anyone figure out anything wrong?

Jay P.
  • 2,420
  • 6
  • 36
  • 71

2 Answers2

2

csv_file is already a file; you don't need to open it. Just pass it straight to csv.reader().

reader = csv.reader(csv_file)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • 2
    That fixed the error, but it throws another error, `iterator should return strings, not bytes (did you open the file in text mode?)`. So, I searched about it and people say I need to try with another reading way like `r`, `rt`, or somthing like that, or set encoding. But, they need to be done in `open()`. Should I use `open()` again? – Jay P. Jun 14 '18 at 19:14
  • By the way, updated the `save()` part on the original past based on your first answer! – Jay P. Jun 14 '18 at 19:16
0

When the file to read is already open, we have a problem, because of the fact that by removing the open line, we will obtain the following error.

iterator should return strings, not bytes (did you open the file in text mode?)

I had the same error, and, to avoid it, I made(CSVfile is my CSV file which is already open):

decoded_file = CSVfile.read().decode('utf-8').splitlines()
reader = csv.reader(decoded_file, delimiter=delimitation)

Then, with that, I can pass into my CSVfile csv file by the loop:

for row in reader:
Gabriel
  • 67
  • 9