【问题标题】:Django - Import .txt file to populate dataDjango - 导入 .txt 文件以填充数据
【发布时间】:2019-03-10 16:51:00
【问题描述】:

我正在尝试创建一个包含销售人员和客户之间交易数据的 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)

【问题讨论】:

  • 你得到了什么确切的错误?

标签: django


【解决方案1】:

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

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/) 也说

请注意,request.FILES 将仅包含请求方法中的数据 是 POST 并且发布请求的具有属性 enctype="多部分/表单数据"。否则,request.FILES 将为空。

【讨论】:

  • 嗨!实际上,我从 youtube 上的教程中获得了这段代码,它似乎对他的情况很有效,但对我来说 request.file 命令似乎不起作用。在这种情况下,我需要在 forms.py 中创建一个表单吗?
  • 我编辑了我的答案,据我了解,您不需要 forms.py 中的表单,但您需要在模板中添加一些内容以使其正常工作
【解决方案2】:

您的问题不是 100% 清楚,但是您是否发现正在编写 log.csv,但没有创建交易、文档和客户?如果是这样,我认为这是因为您要遍历 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,这可能会使您尝试做的事情更容易一些。

【讨论】:

  • 您好,很抱歉造成混淆,我在log.csv上添加了部分来测试.txt文件是否导入成功。代码应该是这样的:“txtfile =request.FILES['file']”然后直接到“for line in txtfile.readline():”我意识到在 request.file 中没有文件被捕获作为输出csv 为空
猜你喜欢
  • 2022-01-19
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
  • 2014-05-21
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
相关资源
最近更新 更多