python - 使用 ModelForm 在 django 中上传和处理 csv 文件

标签 python django csv

我正在尝试从用户上传的 csv 文件上传和获取数据。我正在使用以下代码。 这是我的 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>

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

代码运行良好。

我无法得到的是,当我在 View 中打印 request.method 时

def uploadcsv(request):
    print request.method

输出是“GET”而不是“POST”。

我的疑问是,

  1. 如果 request.method 是 GET 那么为什么代码没有跳过“try-except” block ,它是如何处理 csv 文件的?
  2. 当 HTML 表单方法设置为“post”时,为什么它显示 request.method 为“GET”?

我找过thisthis (这与我的问题有某种关系)但这些问题没有最终答案。

我还通过输入正确的 URL 尝试附加斜杠重定向,但 request.method 仍然是“GET”。

谁能解释一下这个概念?

我使用的代码来自this来源

最佳答案

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

关于python - 使用 ModelForm 在 django 中上传和处理 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47491586/

相关文章:

django - 如何将 Django 模型的一个字段的值设置为等于其他 Django 模型的其他字段

c# - 为什么 File.WriteAllText() 通过添加逗号来格式化我的数字?

python - 帮助使用带有循环的 Python 数独验证器

python - 是否有内置函数(或其他方法)在元素 <= 限制时迭代列表?

python - scikit-learn 的 DecisionTreeRegressor 是否进行真正的多输出回归?

python - 如何使用 Class 装饰器包装器?

mysql - 左加入 Django 模型查询?

Django-tables2 - 如何在 TemplateColumn 中使用自定义过滤器

python - scrapy外壳: output result to file

PHP CSV 重复值