Maddie Graham
Maddie Graham

Reputation: 2177

The CSV script in Django does not see the path of the file - [Errno 2] No such file or directory

Why is my Python/Django script unable to read the file path? How can I correctly get the path from a saved file?

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

Views.py

if form.is_valid():
    cd = form.cleaned_data
    if cd['file']:
        obj = FileUpload()
        obj.file = cd['file']
        obj.save()
        with open(obj.file.url) as f:
            reader = csv.reader(f)
            for row in reader:
                _, created = UserEmail.objects.get_or_create(
                    owner=obj_instance,
                    email=row[0],
                    middle_name=row[2],
                )

Path is correct and if I open http://127.0.0.1:8000/media/file_hll8NoJ.csv local all works fine (I can see my csv file)

Upvotes: 1

Views: 79

Answers (1)

Davide Pizzolato
Davide Pizzolato

Reputation: 715

You are accessing the url of the file, this is correct if you use it on the client side and in general if you reach the resource from internet.

But, in this case you are accessing the file from the server side an you should use obj.file.path instead of obj.file.url

Source: Django FieldFile Documentation

Upvotes: 1

Related Questions