I am trying to upload and fetch the data from csv file uploaded by user. I am using the following code. This is my html form (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>
This is 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"))
And the code is working fine.
What I am not able to get is that when I am printing request.method in views
def uploadcsv(request):
print request.method
the output is "GET" instead of "POST".
My doubt is,
I have looked for this and this (which is somehow related to my question) but there is no final answer on these questions.
I have also tried the append slash redirect by typing the proper URL but the request.method remains "GET".
Can anyone clarify the concept of this?
The code I am using is from this source
Your code is running fine. You can try debugging it with pdb. You may be printing the method type at the time of loading the page, instead of uploading the .csv file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With