首页 文章

Django - 导入.txt文件以填充数据

提问于
浏览
1

我正在尝试创建一个Django Web应用程序,其中包含销售人员和客户之间的交易数据 . 数据源是.txt文件,我想知道是否有更有效的方法导入所有数据而无需从管理页面手动添加它们 .

我有一个允许文件上传的表单的html模板,但我似乎无法通过request.file获取该文件

CSV-Upload.html

{% load static %}

{% block content %}
<form method="post" enctype="multipart/form-data">
   {% csrf_token %}
   <input type="file" name="file">
   <button type="submit">Upload</button>
</form>

{% endblock %}

views.py

@permission_required('admin.can_add_log_entry')
    def data_upload(request):
    template="CSV_upload.html"

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

txtfile = request.FILES['file']
stripped = (line.strip() for line in txtfile)
lines = (line.split(",") for line in stripped if line)
with open('log.csv', 'w') as out_file:
    writer = csv.writer(out_file)
    writer.writerows(lines)

for line in txtfile.readline():
    row = line.split(',')
    _, created = Transaction.objects.create(
        TrxnNo=row[0],
        DocRef=row[1],
        AcCrIsMinus1=row[2],
        CxNo=row[3],
        AcCurWTaxAmt=row[8],
        HomeWTaxAmt=row[9],
        ProjNo=row[10],
        LocNo=row[11],
        SalesNo=row[12],
    )
    _, created = Document.objects.update_or_create(
        DocRef=row[1],
        DocDate=row[0],
    )
    _, created = Customer.objects.update_or_create(
        CxNo=row[3],
        CxName=row[4],
        Postal=row[5],
        CxContact=row[6],
        AcCur=row[7]
    )
    _, created = Project.objects.update_or_create(
        ProjNo=row[10],
    )
    _, created = Location.objects.update_or_create(
        LocNo=row[11],
    )
    _, created = SalesPerson.objects.update_or_create(
        SalesNo=row[12],
        SalesName=row[13],
        SalesContact=row[14]
    )
context = {}
return render(request, template, context)

2 回答

  • 0

    你的问题并不是100%清楚,但是你发现 log.csv 正在写,但交易,文件和客户都没有't being created? If so, I think it',因为你在两次迭代 txtfile .

    你在这里阅读整个文件:

    stripped = (line.strip() for line in txtfile)
    

    txtfile 有一个内部位置,这是您在文件中所处的位置 . 在遍历文件中的所有行之后,位置位于文件的末尾 . 所以当你试图再次浏览文件时......

    for line in txtfile.readline():
    

    ...你已经在文件的末尾了,所以 readline 没有更多的线要给 .

    您可以使用 txtile.seek(0) 将位置设置回文件的开头 .

    记录在https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects

    FWIW,你可能想看看Python's built-in CSV module,这可能会让你想要做的事情变得更容易一些 .

  • 0

    我不是专家,但我认为你的结构非常奇怪你的观点应该是这样的 .

    def data_upload(request):
        if request.method == 'POST':
            from = Yourform(request.POST, request.FILES)
            if form.is_valid():
               your_file = request.FILES['file']
               # do your things with the file
               return HttpResponse("it worked") 
        else:
            form = YourForm()
        return render(request,'template.html', {'form': form})
    

    文档(https://docs.djangoproject.com/en/2.1/topics/http/file-uploads/)也说

    请注意,如果请求方法是POST,则request.FILES将仅包含数据,并且发布请求的请求具有属性enctype =“multipart / form-data” . 否则,request.FILES将为空 .

相关问题