0

Im creating a new thread to ask this question because i have tried every solution i found but non seems to be working for me. I want to output pdf files stored in media sub directory. @Compadre suggested some links that really helped me understand how the file system works in python but so solutions provided in the threads are not working. i want to output files in the following directory structure:

media/QuestionPapers/filename.pdf

view function for outputting the file is:

def Display(request, file_name):


    File_Name = file_name.replace('_', ' ')
    file_path = os.path.join(settings.MEDIA_ROOT, 'QuestionPapers',File_Name)

    with open(file_path,'rb') as pdf:
        response = HttpResponse(pdf.read(), content_type = 'application/pdf')
        response['Content-Disposition'] = 'attachment; filename=some_file.pdf'
    return response

when i do

return HttpResponse(os.path.join(settings.MEDIA_ROOT, 'QuestionPapers',File_Name))

it returns the absolute path to the file i like to out put but i when use the path in my code as shown above i get the is Errors:

[Errno 2] No such file or directory: 'C:\\Users\\majmaj\\projects\\qbank\\Scripts\\QuestionBank\\media\\QuestionPapers\\filename.pdf'

the directory and file does exist because when i do http://127.0.0.1:8000/media/QuestionPapers/myfile.pdf, the file is opened but i don't know why the open() is not working even when the path to the file is correctly

so one should please look into this and tell me what I'm doing wrong, I'm stuck with this issue and its driving me nuts. this is the fifth day and still no solution

Dadep
  • 2,796
  • 5
  • 27
  • 40
jids
  • 51
  • 1
  • 9
  • If you can open it directly via your media URL, what's the point of your view at all? – Daniel Roseman Apr 08 '17 at 21:33
  • This may be of some use: http://stackoverflow.com/questions/16333569/mixed-slashes-with-os-path-join-on-windows ... Namely, the use of a slash for the root directory, and ensuring backslash or forward slash consistency. – JacobIRR Apr 08 '17 at 21:35
  • @ Daniel Roseman I'm testing my media Dir settings to ensure its not the problem that's why i open it directly through media URL. my main goal is to show links to the files so that when i user clicks a link it display the file – jids Apr 08 '17 at 21:42
  • @ JacobIRR thanks for the refereed link, after reading reading the thread i think my path is correct. take a look at the error message above there are no mixed or lost back slashes in the dir paths so i think its correct. why its not working is what i don't understand – jids Apr 08 '17 at 21:57
  • Did you check that the file is in the directory and with the expected name? You *think* that the path is correct. But is really easy to ensure that *is* correct. Check your filesystem to see that the file is there and is readable. – alfonso.kim Apr 09 '17 at 00:48

0 Answers0