Error 404 while creating page to upload csv file to django model
I am trying to create a page so I can upload csv files to django model-
MODELS.PY
from django.db import models
class March(models.Model):
name = models.CharField(max_length = 60, choices=name_choice)
march = models.CharField(max_length = 60, blank = True)
may = models.CharField(max_length = 60, blank = True)
def __str__(self):
return self.name
VIEWS.PY
import csv, io
from django.contrib import messages
from django.contrib.auth.decorators import permission_required
from django.shortcuts import render
from django.http import HttpResponse
from .forms import CustomerForm, CustomerForm222, CustomerForm45
from . import models
@permission_required('admin.can_add_log_entry')
def contact_upload(request):
template = "contact_upload.html"
prompt = {
'order': 'Order of CSV should be name, march, may'
}
if request.method == "GET":
return render(request, template, prompt)
csv_file = request.FILES['file']
if not csv_file.name.endswith('.csv'):
message.error(request, 'This is not a csv file')
data_set = csv_file.read().decode('UTF-8')
io_string = io.StringIO(data_set)
next(io_string)
for column in csv.reader(io_string, delimiter = ',' , quotechar = "|"):
_, created = Contact.objects.update_or_create(
name=column[0],
march = column[1],
may = column[2]
)
context = {}
return render(request, template, context)
URLS.PY
from django.urls import path
from .views import contact_upload
from . import views
urlpatterns = [
path('', views.index, name="index"),
path('book/<int:book_id>', views.book_by_id, name='book_by_id'),
path('upload-csv/', views.contact_upload, name = "contact_upload"),
]
HTML TEMPLATE:
<form method="post" enctype = "multipart/form-data">
{% csrf_token %}
<label>Upload a File </label>
<input type = "file" name="file">
<p>Only accepts CSV file</p>
<button type = "submit">Upload</button>
</form>
ERROR PAGE:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/upload-csv
Raised by: django.contrib.admin.sites.catch_all_view
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
...
...
The current path, admin/upload-csv, matched the last one.
Interestingly the last line on the error page says it did match a file but still showing 404 error. Not sure what went wrong.
Django urls still confuses me a bit.
What am I missing here? Any help will be appreciated.
Thanks.