1

I am hoping to have a user upload a file (a CSV) then access it in my views.py in order to use my own code to read it. However, I keep getting the error:

[Errno 2] No such file or directory: 'D:/media/data.csv'

For reference, my project is stored under the following directory on my PC:

D:\Python\[PROJECT_NAME]

Here is what my settings.py looks like:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

and my views.py:

import os
from django.conf import settings

def create_chart(request):
    ...
    file = File.objects.get(id=4)
    file_ = open(os.path.join(settings.MEDIA_ROOT, file.file.url))

If I go into my admin, I can click on an entry and access the file. However when trying to get it in views.py it is a no go. I am absolutely befuddled by this issue and any help would be appreciated.

ng150716
  • 2,195
  • 5
  • 40
  • 61
  • Is this what you want? https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development and this? https://stackoverflow.com/questions/25119987/how-to-access-uploaded-files-in-django – KhoPhi May 25 '17 at 23:01
  • Not quite, I can successfully access my static files such as CSS and images. But I cant access user uploaded files that go to the `media` folder. – ng150716 May 26 '17 at 00:26

1 Answers1

1

This is because the file.file.url refers to the web address where the file can be accessed, and not where the file can be found in a server's file system.

Instead, you can access the file contents through django's built-in FieldFile API.

# Inside your views.py file

def create_chart(request):
    file = File.objects.get(id=4)
    content = file.read()
    # you can also use open() to specify the mode
    file_obj = file.open(mode='rb')
    # and you can read the file line by line
    for line in file_obj:
        process_line(line)
damon
  • 14,485
  • 14
  • 56
  • 75