Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading and processing a csv file in django using ModelForm

Tags:

python

csv

django

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

like image 889
sgauri Avatar asked Nov 25 '17 23:11

sgauri


1 Answers

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.

like image 111
prakash09 Avatar answered Nov 15 '22 19:11

prakash09