使用ModelForm在django中上载和处理csv文件 [英] Uploading and processing a csv file in django using ModelForm

查看:226
本文介绍了使用ModelForm在django中上载和处理csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从用户上传的csv文件中上传并获取数据.我正在使用以下代码. 这是我的html表格(upload_csv1.html):

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>

这是views.py:

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"))

代码运行正常.

我无法获得的是在视图中打印request.method时

What I am not able to get is that when I am printing request.method in views

def uploadcsv(request):
    print request.method

输出为" GET ",而不是" POST ".

the output is "GET" instead of "POST".

我的疑问是,

  1. 如果request.method是 GET ,那么为什么代码没有跳过"try-except"块以及它如何处理csv文件?
  2. 当HTML表单方法设置为"发布"时,为什么将request.method显示为" GET "?
  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.

我也尝试通过键入正确的URL尝试追加斜杠重定向,但是request.method仍然是"GET".

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?

我使用的代码来自

推荐答案

您的代码运行良好.您可以尝试使用pdb对其进行调试. 您可能在加载页面时打印方法类型,而不是上载.csv文件.

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.

这篇关于使用ModelForm在django中上载和处理csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆