我正在尝试从用户上传的 csv 文件上传和获取数据。我正在使用以下代码。 这是我的 html 表单 (upload_csv1.html):
<form action="{% url 'myapp:upload_csv' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="csv_file1">
<input type="submit" value="Upload">
</form>
这是 views.py:
def uploadcsv(request):
data = {}
if "GET" == request.method:
return render(request, "myapp/upload_csv1.html", data)
# if not GET, then proceed
try:
csv_file = request.FILES["csv_file1"]
if not csv_file.name.endswith('.csv'):
messages.error(request,'File is not CSV type')
return HttpResponseRedirect(reverse("myapp:upload_csv"))
#if file is too large, return
if csv_file.multiple_chunks():
messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),))
return HttpResponseRedirect(reverse("myapp:upload_csv"))
file_data = csv_file.read().decode("utf-8")
lines = file_data.split("\n")
#loop over the lines and save them in db. If error , store as string and then display
for line in lines:
fields = line.split(",")
data_dict = {}
data_dict["sku"] = fields[0]
data_dict["item_name"] = fields[1]
try:
form = PalazzoForm(data_dict)
if form.is_valid():
form.save()
else:
logging.getLogger("error_logger").error(form.errors.as_json())
except Exception as e:
logging.getLogger("error_logger").error(form.errors.as_json())
pass
except Exception as e:
logging.getLogger("error_logger").error("Unable to upload file. "+repr(e))
messages.error(request,"Unable to upload file. "+repr(e))
return HttpResponseRedirect(reverse("myapp:upload_csv"))
代码运行良好。
我无法得到的是,当我在 View 中打印 request.method 时
def uploadcsv(request):
print request.method
输出是“GET”而不是“POST”。
我的疑问是,
- 如果 request.method 是 GET 那么为什么代码没有跳过“try-except” block ,它是如何处理 csv 文件的?
- 当 HTML 表单方法设置为“post”时,为什么它显示 request.method 为“GET”?
我找过this和 this (这与我的问题有某种关系)但这些问题没有最终答案。
我还通过输入正确的 URL 尝试附加斜杠重定向,但 request.method 仍然是“GET”。
谁能解释一下这个概念?
我使用的代码来自this来源
最佳答案
您的代码运行良好。您可以尝试使用 pdb 对其进行调试。 您可能在加载页面时打印方法类型,而不是上传 .csv 文件。
关于python - 使用 ModelForm 在 django 中上传和处理 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47491586/