我是python / django的新手,无法解决问题。要求是上传一个csv文件,以将数据加载到数据库中。
我为需要加载数据的用户提供了一个自定义模型。似乎发生了错误 csv_file = request.FILES ['file']
错误-
MultiValueDictKeyError at /upload-csv/ 'file'
Request Method: POST
Request URL: http://127.0.0.1:8000/upload-csv/
Django Version: 2.2.2
Exception Type: MultiValueDictKeyError
Exception Value:
'file'
Exception Location: D:\djreact\backend\env\lib\site- packages\django\utils\datastructures.py in __getitem__, line 80
Python Executable: D:\djreact\backend\env\Scripts\python.exe
Python Version: 3.7.2
Python Path:
['D:\\djreact\\backend\\src',
'D:\\djreact\\backend\\env\\Scripts\\python37.zip',
'D:\\djreact\\backend\\env\\DLLs',
'D:\\djreact\\backend\\env\\lib',
'D:\\djreact\\backend\\env\\Scripts',
'd:\\python\\python37\\Lib',
'd:\\python\\python37\\DLLs',
'D:\\djreact\\backend\\env',
'D:\\djreact\\backend\\env\\lib\\site-packages']
Server time: Tue, 2 Jul 2019 12:49:52 +0000
View.py-
def user_upload(request):
template="user_upload.html"
prompt = {
'order': 'order of csv should be first_name, last_name, email'
}
if request.method == "GET":
return render(request, template, prompt)
csv_file = request.FILES['file']
data_set = csv_file.read().decode('UTF-8')
io_string = io.StringIO(data_set)
next(io_string)
for column in csv.reader(io_string, delimiter=',', quotechar="|"):
_, created = User.Objects.update_or_create(
first_name = column[0],
last_name = column[1],
email = column[2]
)
return render(request, template)
模板-user_upload.html
{% if messages %} {% for message in messages %}
<div>
<strong>{{message|safe}}</strong>
</div>
{% endfor %} {% else %} {{order}}
<form method="post" encrypt="multipart/form-data">
{% csrf_token %}
<label> Upload a file </label>
<input type="file" name='file'>
</br>
<button type="submit"> Upload</button>
</form>
{% endif %}
型号
class DepUser(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField(max_length=100, unique=True)
emailVerifCode = models.CharField(null = True,blank=True, max_length=30)
答案 0 :(得分:0)
form元素中的属性应为enctype
,而不是encrypt
。
<form method="post" enctype="multipart/form-data">