Django导入csv HTML

时间:2014-03-26 17:12:43

标签: python django csv

嗨我目前尝试使用django admin将csv文件导入django项目。我写的代码似乎在python运行时工作,但我不确定如何构建html模板,因为我似乎无法找到任何示例。是否有人能够发布一个例子或指出我正确的方向

我的代码是

表单

class DataInput(forms.Form):
    file = forms.FileField()


def save(self):
    records = csv.reader(self.cleaned_data["file"])
    for line in records:
        parts = Part()
        parts.supplier_id = line[0]
        parts.name = line[1]
        parts.description = line[2]
        parts.save()

视图

def csv_import(request):
    if request.method == "POST":
        form = DataInput(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            success = True
            context = {"form": form, "success": success}
            return render_to_response("imported.html", context,
            context_instance=RequestContext(request))
    else:
        form = DataInput()
        context = {"form": form}
        return render_to_response("imported.html", context,
        context_instance=RequestContext(request))

提前致谢

1 个答案:

答案 0 :(得分:1)

如果您只想使用默认的表单呈现,那么您的上传模板将如下所示:

<!DOCTYPE html>
<html>
    ...

    <form enctype="multipart/form-data" method="post" action=".">
        {{ form }}
    </form>

    ...
</html>

区别部分是enctype="multipart/form-data" lets it handle the file upload field