python - 如何在 django web 应用程序中显示 csv 文件的行数和列数

标签 python html django django-forms django-templates

我想从用户那里获取一个 csv 文件,然后只想向用户显示该文件中的行数和列数

testapp.html:

<form method="POST" action="rowcol">
{% csrf_token %}
<input type="file" name="file" accept=".csv">

<button type="submit">Upload text</button>
</form>

views.py:

from django.shortcuts import render
from django.shortcuts import HttpResponse
import numpy as np
import pandas as pd

def testapp(request):
    return render(request, 'testapp.html', {})

def rowcol(request):
    if request.method == 'POST':
        file = request.POST["file"]
        dataset=pd.read_csv('file')
        count_row = dataset.shape[0]
        count_col = dataset.shape[1]
        ans=("<H1>%d,%d</H1>",count_row,count_col)
        return HttpResponse(ans)

url.py:

from django.urls import path
from testapp import views

urlpatterns = [
    path('', views.testapp, name='testapp'),
    path('', views.rowcol, name='rowcol'),
]

外部文件夹中的urls.py:

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('testapp.urls')),
]

最佳答案

这里有一些问题。首先,您的 path(..) 彼此冲突。您需要为第二条路径提供不同的路径。例如:

# testapp/urls.py

from django.urls import path
from testapp import views

urlpatterns = [
    path('', views.testapp, name='testapp'),
    path(<b>'rowcol/'</b>, views.rowcol, name='rowcol'),
]

接下来在模板中,最好使用 {% url ... %} 模板标记,并将 enctype 设置为 multipart/form-data:

<form method="post" action="<b>{% url 'rowcol' %}</b>" <b>enctype="multipart/form-data"></b>
    {% csrf_token %}
    <input type="file" name="file" accept=".csv">
    <button type="submit">Upload text</button>
</form>

最后在你的 View 函数中,你忘记格式化字符串:

def rowcol(request):
    if request.method == 'POST':
        file = request.FILES['file']
        dataset=pd.read_csv(file)
        count_row, count_col = dataset.shape
        ans='<H1>%d,%d</H1>' % (count_row,count_col)
        return HttpResponse(ans)
    return HttpResponse('')

关于python - 如何在 django web 应用程序中显示 csv 文件的行数和列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58270778/

相关文章:

Python:搜索已排序的元组列表

Python VLC 不会播放音频?

php - 单击 PHP 时显示数组值

html - 如何使用 DNN 上的编辑器添加 HTML/CSS?如何在不依赖模块的情况下添加标记?

python - django:自定义包含标签错误,错误信息:无效的 block 标签

python - Django 在变量末尾添加新行,而 Flask 没有

python - 从 csv 文件中删除换行符

html - CSS3 border-image 不重复

python - Django + Apache + Windows WSGIDaemonProcess 替代方案

python - 如何优化此 Django View 的 SQL?