在Django中上传的csv无法保存

时间:2019-09-28 15:28:12

标签: django csv

该项目的唯一目的是在模板上显示从模板上传的csv。有用。但是,当我重新启动服务器或什至只是刷新页面时,上传的csv数据就会消失。请求处理未通过上下文将任何数据传递到模板。

我的views.py是:

import csv, io
from django.shortcuts import render
from django.contrib import messages
from .models import Table

def data_upload(request):
    template = "home.html"

    if request.method == 'GET':
        return render(request, template)

    csv_file = request.FILES['file']
    if not csv_file.name.endswith('.csv'):
        messages.error(request, 'Please upload a .csv file.')

    data_set = csv_file.read().decode('ISO-8859-1')
    io_string = io.StringIO(data_set)
    next(io_string)
    for column in csv.reader(io_string, delimiter=','):
        _, created = Table.objects.update_or_create(
            page=column[0], 
            keyword=column[1], 
            interval=column[2], 
            email=column[3], 
            notes=column[4], 
            billing=column[5],
        )
    context = {
        'tables': Table.objects.all()
    }
    return render(request, template, context)

模板上传表单为:

<form method="POST" enctype="multipart/form-data" action="">{% csrf_token %}
<div class="file-field input-field">
<div class="btn">
    <span>Upload a CSV FILE</span>
    <input type="file" name="file">
</div>
<div class="file-path-wrapper">
    <input class="file-path validate" type="text">
</div>
<button class="waves-effect waves-light btn teal" type="submit">Upload</button>
    </div>

我知道我在某个地方需要一个.save(),我已经尝试过了,但是它不起作用。

有人吗?

1 个答案:

答案 0 :(得分:2)

正如@Mehran所提到的,您在GET请求期间没有传递“表”上下文。这就是为什么要通过POST而不是GET获取数据的原因。

import csv, io
from django.shortcuts import render
from django.contrib import messages
from .models import Table

def data_upload(request):
    template = "home.html"


    if request.method == 'POST':
        csv_file = request.FILES['file']
        if not csv_file.name.endswith('.csv'):
            messages.error(request, 'Please upload a .csv file.')

        data_set = csv_file.read().decode('ISO-8859-1')
        io_string = io.StringIO(data_set)
        next(io_string)
        for column in csv.reader(io_string, delimiter=','):
            _, created = Table.objects.update_or_create(
                page=column[0], 
                keyword=column[1], 
                interval=column[2], 
                email=column[3], 
                notes=column[4], 
                billing=column[5],
            )
    elif request.method == 'GET':
        # DO something in GET call
        pass
    context = {
        'tables': Table.objects.all()
    }
    return render(request, template, context)