i dont to develop a search system in which we are going to import data from csv file which is local file in our computer, i want to import the csv file in django to store it's value in dictionary. but i am not able to import the data in django.
here is code and image,
and this is view.py file code in which i add csv
from unicodedata import name
from django.shortcuts import redirect, render
from django.http import HttpResponse
from django.template import context
import csv
def index(request):
context = {'name':'xyz'}
file = open("railway_stations.csv")
csvreader = csv.reader(file)
rows = []
d = dict()
for row in csvreader:
rows.append(row)
for r in rows:
d.update({r[0]:r[1]})
print(r[0])
print(d["Prescot"])
file.close()
return render(request, 'home.html',context)
and my railway_stations.csv file is in following image \
please please suggest me who to do it. (who to import csv to view.py file)
i just try simple import csv to import the csv, i am expecting how to import the csv file in a view.py file so that i am render all the data in html file.also i do it in python in fine way but now i am facing difficulty in django
or you can also suggest me good way to import csv file and show all the data in html or in browser.
CodePudding user response:
Add your file to static folder and in the view file put that :
from unicodedata import name
from django.shortcuts import redirect, render
from django.http import HttpResponse
from django.template import context
//add this line
from django.templatetags.static import static
import csv
def index(request):
context = {'name':'xyz'}
file = open(static('railway_stations.csv'))
csvreader = csv.reader(file)
rows = []
d = dict()
for row in csvreader:
rows.append(row)
for r in rows:
d.update({r[0]:r[1]})
print(r[0])
print(d["Prescot"])
file.close()
return render(request, 'home.html',context)
CodePudding user response:
You can import csv file in django by using the static folder.
first you have to create the folder in your app (where manage.py is located)
and add it path to the setting.py
how you can check this setting is working or not in your browser like
and paste your csv file inside your static folder
as you can see my folder
now add csv file directory path to view.py
file
the modified code is look like this
from unicodedata import name
from django.shortcuts import redirect, render
from django.http import HttpResponse
from django.template import context
import csv
def index(request):
context = {'name':'xyz'}
file = open("static/railway_stations.csv")
csvreader = csv.reader(file)
rows = []
d = dict()
for row in csvreader:
rows.append(row)
for r in rows:
d.update({r[0]:r[1]})
print(r[0])
print(d["Prescot"])
file.close()
return render(request, 'home.html',context)
now run the server and then you can not finde any error.
csv value is printed in my console as you can see in this image
that it's, it is working fine for me