Uploading and processing a csv file in django using ModelForm

2024/10/5 21:25:59

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, returnif 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 displayfor 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())                    passexcept 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,

  1. if the request.method is GET then why the code is not skipping the "try-except" block and how is it processing the csv file?
  2. when the HTML form method is set as "post", why is it showing request.method as "GET" ?

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

Answer

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.

https://en.xdnf.cn/q/70442.html

Related Q&A

Plotting Multiple Lines in iPython/pandas Produces Multiple Plots

I am trying to get my head around matplotlibs state machine model, but I am running into an error when trying to plot multiple lines on a single plot. From what I understand, the following code should…

libclang: add compiler system include path (Python in Windows)

Following this question and Andrews suggestions, I am trying to have liblang add the compiler system include paths (in Windows) in order for my Python codeimport clang.cindexdef parse_decl(node):refere…

Pako not able to deflate gzip files generated in python

Im generating gzip files from python using the following code: (using python 3)file = gzip.open(output.json.gzip, wb)dataToWrite = json.dumps(data).encode(utf-8)file.write(dataToWrite)file.close()Howev…

Best way to have a python script copy itself?

I am using python for scientific applications. I run simulations with various parameters, my script outputs the data to an appropriate directory for that parameter set. Later I use that data. However s…

How to convert dictionary to matrix in python?

I have a dictionary like this:{device1 : (news1, news2, ...), device2 : (news 2, news 4, ...)...}How to convert them into a 2-D 0-1 matrix in python? Looks like this:news1 news2 news3 news4 device1 …

Ubuntu 16.04 - Why I cannot install libtiff4-dev?

Following this tutorial, I am trying to install the OpenCV 3 with Python on Ubuntu 16.04.At the step of entering $ sudo apt-get install libjpeg8-dev libtiff4-dev libjasper-dev libpng12-devI got this me…

Histogram update in a for loop with matplotlib.pylab

I am trying to update in for loop a histogram data. but I dont know how to make it. I tried with set_data but it is not working. here is the code:plt.ion() ax=plt.subplot(111) [n,X, V]=ax.hist(range(MA…

How to remove a section from an ini file using Python ConfigParser?

I am attempting to remove a [section] from an ini file using Pythons ConfigParser library.>>> import os >>> import ConfigParser >>> os.system("cat a.ini") [a] b = c…

why does this script not work with threading python

so ive been trying to ifnd a way to access task manager. Ive tried a few methods including the wmi module and the windows tasklist but neither suit my need. wmi is way too slow and tasklist becomes to…

django-admin command not working in Mac OS

I started Django in Mac OS and after installing Django using pip, I tried to initiated a new project using the command django-admin startproject mysite. I get the error -bash: django-admin: command not…