小编sga*_*uri的帖子

使用ModelForm在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>
Run Code Online (Sandbox Code Playgroud)

这是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 …
Run Code Online (Sandbox Code Playgroud)

python csv django

6
推荐指数
1
解决办法
5942
查看次数

标签 统计

csv ×1

django ×1

python ×1