django - Django : Error 'str' object has no attribute 'get' when populating model with csv file

标签 django file error-handling

我试图用这样的csv文件填充模型:

if form.is_valid():
        #form.save()
        print("form1 valid")
        csvfile = request.FILES['myfilebase']
        print(csvfile)
        try: 
            f=open(csvfile,"rt")
            #print(csvfile)
            my_data = csv.reader(f)
            for row in my_data:
                print(row)
        except:
            msg = "Cannot open file - is it CSV?"
            print("not opened")
            return msg

    else:
        print("not valide form")

但我收到此错误:

'str' object has no attribute 'get'



这个问题在csvfile变量中,因为当我用完整路径替换csvfile时,我的代码可以正常工作。我想从FileField获取文件名时会丢失某些内容
编辑这里是我的看法:
def clientsBase(request):
    form = formFile(request.POST, request.FILES)
    #csvfile = request.POST['myfilebase']
    #print(csvfile)
    print("entrer en clientsBase")
    if form.is_valid():
        #form.save()
        print("form1 valid")
        csvfile = request.FILES['myfilebase']
        print(csvfile)
        try: 
            f=open(csvfile,"rt")
            #print(csvfile)
            my_data = csv.reader(f)
            for row in my_data:
                print(row)
        except:
            msg = "Cannot open file - is it CSV?"
            print("not opened")
            return msg

    else:
        print("not valide form")
    return redirect('/veentes/')

任何帮助我该如何处理此错误。非常感谢

最佳答案

您不会显示所有代码,但是大概是在 View 中。 View 总是需要返回一个HttpResponse。您正在返回一个字符串,味精。

关于django - Django : Error 'str' object has no attribute 'get' when populating model with csv file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49979669/

相关文章:

php - set_error_handler() 不适用于 fatal error

python - 如果 try 语句在 python 中成功,则运行代码

c - 使用 C switch 语句进行错误处理

django - 在我的 django 应用程序中导入 pymongo 时出错

java - ObjectOutputStream/ObjectInputStream的文件操作问题

python - 从 Django 模板访问 JSON 属性

mysql - 在加载数据INFILE中设置

python - 不更改文本文件 Python 的奇怪值更改

基于 Django 类的通用 View 和 ModelForms

python - 如何让夹层侧边栏自动填充博客文章