0

I am new to django.I want upload the file in django web page.When I'm executing the code it shows the following error.

NoReverseMatch at /index/
Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

Please help me to print the csv results on the table by without saving the csv_file on db and correct my code if there is any error

Main 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>
Alasdair
  • 298,606
  • 55
  • 578
  • 516
Dinesh
  • 33
  • 1
  • 10

1 Answers1

2

Your URL pattern name and URL tag do not match. In the URL pattern you are using upload_csv,

url(r'^index/', views.upload_csv,name='upload_csv'),

but in the URL tag you are using index.

{% url 'myapp:index' %}

Change your code so that they match.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Ok.But I want to print the csv data on UI.But It prints nothing – Dinesh Apr 18 '18 at 10:28
  • 1
    Your question title is "How to solve NoReverseMatch error in django". I've showed you how to fix that. Printing the csv data is a separate issue, so doesn't belong on this question. – Alasdair Apr 18 '18 at 10:29
  • I also mentioned that I want to print the csv file data – Dinesh Apr 18 '18 at 10:39
  • 1
    Yes, but Stack Overflow questions work best when there is a specific problem to solve rather than several unrelated issues. I can see that you've edited the question, but I'm not going to vote to re-open when the title is completely unrelated to the problem. – Alasdair Apr 18 '18 at 10:48