我正在尝试从用户上传的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"))
代码工作正常。
我无法获得的是当我在视图中打印request.method时
def uploadcsv(request):
print request.method
输出为“ GET ”而非“ POST ”。
我怀疑是,
答案 0 :(得分:1)
您的代码运行正常。您可以尝试使用pdb进行调试。 您可能在加载页面时打印方法类型,而不是上载.csv文件。
答案 1 :(得分:0)
第二个问题。
在请求页面时,它总是发出GET请求: 在控制台上运行django runserver时,可能会看到日志:
[01/Jul/2000 18:11:12] "**GET** /some/url/path/ HTTP/1.1" 200 17521
像
这样的条件语句if request.method == "GET":
print(True)
else:
print(False)
将始终为True,除非带有诸如带有method =“ POST”的html形式的POST请求发送。
[23/Jul/2000 18:05:16] "**POST** /some/url/path/ HTTP/1.1" 200 9221
在这种情况下,您必须期待GET请求(通过浏览器请求页面时)和POST请求(单击提交按钮时)。