简体   繁体   English

使用ModelForm在django中上载和处理csv文件

[英]Uploading and processing a csv file in django using ModelForm

I am trying to upload and fetch the data from csv file uploaded by user. 我正在尝试从用户上传的csv文件上传和获取数据。 I am using the following code. 我使用以下代码。 This is my html form (upload_csv1.html): 这是我的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>

This is views.py: 这是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 我无法获得的是当我在视图中打印request.method时

def uploadcsv(request):
    print request.method

the output is " GET " instead of " POST ". 输出是“ GET ”而不是“ 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? 如果request.method是GET那么为什么代码没有跳过“try-except”块,它是如何处理csv文件的呢?
  2. when the HTML form method is set as " post ", why is it showing request.method as " GET " ? 当HTML表单方法设置为“ post ”时,为什么它将request.method显示为“ 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". 我还尝试通过键入正确的URL来追加斜线重定向,但request.method仍为“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. 您可以尝试使用pdb进行调试。 You may be printing the method type at the time of loading the page, instead of uploading the .csv file. 您可能在加载页面时打印方法类型,而不是上载.csv文件。

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: 在请求页面时,它总是发出GET请求:当django runserver在控制台上运行时,可以看到日志:

[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. 将永远为True,除非类似html form with method =“POST”之类的东西发送POST请求。

[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). 在这种情况下,您必须期望GET请求(通过浏览器请求页面时)和POST请求(单击提交按钮时)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM