如何在Python或Django中处理错误“预期的str,字节或os.PathLike对象,而不是InMemoryUploadedFile"? [英] How can I handle the error "expected str, bytes or os.PathLike object, not InMemoryUploadedFile' in Python or Django?

查看:78
本文介绍了如何在Python或Django中处理错误“预期的str,字节或os.PathLike对象,而不是InMemoryUploadedFile"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在详细解释我的问题之前,这里是我的代码.

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
...

我正在尝试将 data.csv 上传到数据库.我需要文件中的每个列数据进入 SimilarStore 模型中的 domain score rank .这就是我要处理的上述代码.

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

预期的str,字节或os.PathLike对象,而不是InMemoryUploadedFile

我已经对此进行了一些研究,但对我的情况无济于事.有人能找出任何错误吗?

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

推荐答案

csv_file 已经是文件;您无需打开它.只需将其直接传递给 csv.reader().

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)

这篇关于如何在Python或Django中处理错误“预期的str,字节或os.PathLike对象,而不是InMemoryUploadedFile"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆