FileNotFound Error although /media/sched/schedule.csv exists

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/profile/

Django Version: 5.1.6
Python Version: 3.12.3
Installed Applications:
['crispy_forms',
 'crispy_bootstrap4',
 'employee.apps.EmployeeConfig',
 'post.apps.PostConfig',
 'schedule.apps.ScheduleConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "/home/ronak/Projects/django/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/home/ronak/Projects/django/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/ronak/Projects/django/lib/python3.12/site-packages/django/contrib/auth/decorators.py", line 60, in _view_wrapper
    return view_func(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/ronak/Projects/webapp/employee/views.py", line 33, in profile
    with open(filename) as csvfile:
         ^^^^^^^^^^^^^^

Exception Type: FileNotFoundError at /profile/
Exception Value: [Errno 2] No such file or directory: '/media/sched/schedule.csv'

my settings

STATIC_URL = 'static/'

# my settings

STATICFILES_DIRS = [
    os.path.join(BASE_DIR,  'static')
]

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

Welcome @nnehal !

Side Note: When posting code here, enclose the code between lines of three
backtick - ` characters. This means you’ll have a line of ```, then your code,
then another line of ```. This forces the forum software to keep your code
properly formatted. (I have taken the liberty of correcting your original posts.
Please remember to do this in the future.)

I think we’re going to need to see the view that is throwing this error.

Superficially, it looks like you’re trying to process this file internally, which means the path to be used is the real path of the file on the file system and not a url.

1 Like
@login_required
def profile(request):
    # csv file name
    filename = UploadDocument.objects.last().File.url

    # initializing the titles and rows list
    # fields = []
    # rows = []
    name = User.username
    schedule = []
    # reading csv file
    with open(filename) as csvfile:
        # creating a csv reader object
        csvreader = csv.reader(csvfile)

        # extracting field names through first row
        fields = next(csvreader)

        # extracting each data row one by one

        for row in csvreader:
            for i in range(len(row)):
                if(name == row[i].strip().title()):
                    time = row[0]
                    match(i):
                        case 1:
                            schedule.append(time + " Monday")
                        case 2:
                            schedule.append(time + " Tuesday")
                        case 3:
                            schedule.append(time + " Wednesday")
                        case 4:
                            schedule.append(time + " Thursday")
                        case 5:
                            schedule.append(time + " Friday")
                        case 6:
                            schedule.append(time + " Saturday")
                        case 7:
                            schedule.append(time + " Sunday")
                        case _:
                            print("Go HOME!!\n")

            

    context = {
        "schedule": schedule
    }
    return render(request, "employee/profile.html", context)

First of all please take my respect for your valuable comments on this forum. I’ve read and learned from them and it’s an honor to get advice from you. THANK YOU.
I’m new to django and coding too although I’ve recently finished my CS degree. So, please disregard or correct me for silly things in my code.
Here I was trying to reuse a code that takes filename and employee name and prints their schedule from a csv file. Previously I’ve learned from your comment about the API’s for accessing the database. I’ve used URL here to retrieve the last uploaded file and get the file location.

You use the url attribute to get a URL to be sent to a browser for the browser to retrieve the file. It’s not needed when you’re retrieving the file in a view.

Accessing the field from the model gives you an instance of a FieldFile. You would call the open method on the field to access the data within the file.

See the docs at Model field reference | Django documentation | Django for all the relevant details. You’ll want to read that section carefully - handling files internally in Django is not the same as processing files in a typical Python program. There are just enough differences to potentially cause confusion.

1 Like
    target = UploadDocument.objects.last().File
    # reading csv file
    with target.open(mode='r') as csvfile:
        csvreader = csv.reader(csvfile)

got it working thank you @KenWhitesell for showing the right way.