我是django的新手。我想在django网页上传文件。当我执行代码时,它会显示以下错误。
NoReverseMatch at /index/
Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
请帮我打开表上的csv结果,不保存db上的csv_file,如果有错误则更正我的代码
主要urls.py
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^',include('myapp.urls',namespace='myapp')),
)
if settings.DEBUG:
urlpatterns+=static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
myapp.urls
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^index/', views.upload_csv,name='upload_csv'),
]
views.py
from django.shortcuts import render
from django.conf import settings
from django.http import HttpResponseRedirect
from django.contrib import messages
import csv
from django.core.urlresolvers import reverse
import logging
def upload_csv(request):
data = {}
if "GET" == request.method:
return render(request, "myapp/index.html", data)
# if not GET, then proceed
try:
csv_file = request.FILES["csv_file"]
if not csv_file.name.endswith('.csv'):
c=messages.error(request,'File is not CSV type')
return HttpResponseRedirect(reverse("myapp:index",{"c":c}))
#if file is too large, return
if csv_file.multiple_chunks():
messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),))
return HttpResponseRedirect(reverse("myapp:index"))
file_data = csv_file.read().decode("utf-8")
rows=[]
lines = file_data.split("\n")
for line in lines:
fields = line.split(",")
data_dict = {}
data_dict["GSTIN/UIN"] = fields[0]
data_dict["INV NO"] = fields[1]
data_dict["INV-DATE"] = fields[2]
data_dict["Taxable value"] = fields[3]
try:
form = EventsForm(data_dict)
if form.is_valid():
form.save()
else:
logging.getLogger("error_logger").error(form.errors.as_json())
except Exception as e:
logging.getLogger("error_logger").error(repr(e))
pass
rows.append(line)
except Exception as e:
logging.getLogger("error_logger").error("Unable to upload file. "+repr(e))
messages.error(request,"Unable to upload file. "+repr(e))
variables={}
variables['lines'] = rows
return HttpResponseRedirect(reverse("myapp:index",variables))
#return render(request,"myapp/index.html",variables)
HTML
<!doctype>
<html>
<body>
<div class="container" style="margin-top:90px;">
<form action="{% url 'myapp:index' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="row">
<label for="fileupload" class="btn btn-primary col-md-2 col-sm-4 uploadBtn" >Upload GSTR 2A</label><br>
<input type="file" class="fileupload" id="fileupload" required="True">
</div>
</div>
</form>
<table>
{% for line in lines %}
<tr><td>{{ line.0 }}</td><td>{{ line.1 }}</td></tr>
{% endfor %}
</table>
</body>
</html>
答案 0 :(得分:2)
您的网址格式名称和网址标记不匹配。在使用upload_csv
,
url(r'^index/', views.upload_csv,name='upload_csv'),
但是在您使用index
的网址标记中。
{% url 'myapp:index' %}
更改您的代码,使其匹配。