我想从用户那里获取一个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)
urls.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('rowcol/', views.rowcol, name='rowcol'),
]
接下来,在模板中,最好使用{% url ... %}
template标记,并将其设置enctype
为multipart/form-data
:
<form method="post" action="{% url 'rowcol' %}" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="file" accept=".csv">
<button type="submit">Upload text</button>
</form>
最后,在视图函数中,您忘了格式化字符串:
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('')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句