Home > Net >  File handling in django
File handling in django

Time:04-17

I am trying to access the csv file which i passed in my form and saved in media directory. I am able to access the file if i manually enter the path(localhost://8000/media/1.csv) but it throws an error saying "No such file or directory" when accessing from open function.

def home(request):
print("Rendering Home...")
if request.method == "POST":
    uploaded_file = request.FILES['csvFile']
    fs = FileSystemStorage()
    name = fs.save(uploaded_file.name,uploaded_file)
    url = fs.url(name)
    csv_fp = open(f'{url}', 'r')  //ERROR:"No such file or dir media/1.csv"
    reader = csv.DictReader(csv_fp)
    headers = [col for col in reader.fieldnames]
    out = [row for row in reader]
    return render(request, 'home.html', {'data' : out, 'headers' : headers})
return  render(request,"home.html")

enter image description here

CodePudding user response:

have you tried .path instead of .name

file = open(filename.path' 'rb').read()

CodePudding user response:

The problem was the path being given to open function

csv_fp = default_storage.open(os.path.join(settings.MEDIA_ROOT, name), 'r')

simply did the trick :)

  • Related