Uploading and processing a csv file in django using ModelForm

Viewed 9253

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,

  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

2 Answers

Second question.

When requesting pages it always make a GET request: It is possible to see the log when django runserver is running on console:

[01/Jul/2000 18:11:12] "**GET** /some/url/path/ HTTP/1.1" 200 17521

A conditional sentence like

if request.method == "GET":
  print(True) 
else:   
  print(False)

Will always be True, except when something like html form with method="POST" sends a POST request.

[23/Jul/2000 18:05:16] "**POST** /some/url/path/ HTTP/1.1" 200 9221

In this case you must expect a GET request (when requesting the page through browser) and POST request (when click on submit button).

Related