0

I am trying to send a 2 pdf files as attachment,1 generated by xhtml2pdf and another which is already present in the app directory of my django project, based on a condition. I am able to send the generated file and 1 file but getting error " File does not exist" for the other condition, even when both the files are in the same location. I am a newbie here, what am i doing wrong? where and how do i need to store the files to be attached ?

my views code for email-

        patienthist = get_object_or_404(PatientHist, pk=email_id)  # stores values (Y,N)

        pdf = Render.render('eradicate/dietplan.html', context)
        msg = EmailMessage("Your Diet Plan", "Attached is your diet plan!", to=[email_id])
        msg.content_subtype = "html"
        msg.attach('my_pdf.pdf', pdf, 'application/pdf') # attaching generated pdf

        if patienthist.foodhabit == 'N':
            msg.attach_file('eradicate/LCHF Eradicate Diabetes.pdf') # doest not get attached
        else:
            msg.attach_file('eradicate/LFV Eradicate Diabetes.pdf')  # gets attached to email

        msg.send()

error i am getting-

FileNotFoundError at /eradicate/test@gmail.com/dietplan/

[Errno 2] No such file or directory: 'eradicate\\LCHF Eradicate Diabetes.pdf'

Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python37\lib\pathlib.py in _opener, line 1058

note: its adding an extra backslash after the app name eradicate, why does this happen?

my 2 files are stored in the django app directory, same level as that of views, models, admins etc.

MRM
  • 37
  • 2
  • 8
  • Have you named the file correctly in the directory? – kshitij86 Jun 09 '20 at 12:35
  • yes, i have double checked and verified. Is it correct way to store the files like that? or am i supposed to be creating a separate folder like we do for templates? – MRM Jun 09 '20 at 13:32
  • Then, it could be a logical error with your condition ```if patienthist.foodhabit == 'N':``` Try attaching the file without this, and you can locate if this condition is failing somewhere in you code. – kshitij86 Jun 09 '20 at 13:36
  • I just tried to remove my condition and upload just the 1 file. it still gave the same error. – MRM Jun 09 '20 at 13:43
  • 1
    Thanks @Kshitij, there was an extra space in the file name before pdf i was trying to upload, now chaged it and its working. mistake on my part – MRM Jun 09 '20 at 14:09
  • Glad you found the error. – kshitij86 Jun 09 '20 at 14:11

0 Answers0