首页 文章

django使用modelname.filevariable.url发送上传文件的电子邮件附件

提问于
浏览
0

我有一个Django库应用程序,其中从一个书籍列表中,客户可以通过电子邮件发送一个特定书籍的pdf文件链接,该链接最初由管理员使用FileField上传 .

现在,电子邮件已成功发送/接收,但pdf文件未附加 .

我也查看了相同的其他stackoverflow引用,但我无法解释正确的解决方案:Django email attachment of file upload

单击电子邮件按钮后,表单将按如下方式提交: Three hidden values are also being submitted on submitting the form. , one of which is the book.file.url

<form method="POST" action ="{% url 'email_book' %}" enctype="multipart/form-data">
       {% csrf_token %}

       # correction made
       <input type="hidden" name="book_title" value="{{ book.id }}">

       <button type="submit" class="btn btn-info"><span class="glyphicon glyphicon-envelope"></span>&nbsp;&nbsp;Email</button>
   </form>

在views.py中,我使用了Django的 EmailMessage clas ,如下所示:

def send_email(request):
       # corrections made, pdf file path is being retrieved
       book = Book.objects.get(pk=int(request.POST.get('id')))
       book_title = book.title
       book_author = book.author
       book_pdf = book.file.path  #inplace of book.file.url

      email_body = "PDF attachment below \n Book: "+book_title+"\n Book Author: "+book_author

try:
    email = EmailMessage(
        'Book request',
        email_body,
        'sender smtp gmail' + '<dolphin2016water@gmail.com>',
        ['madhok.simran8@gmail.com'],
    )

    # this is the where the error occurs
    email.attach_file(book_pdf, 'application/pdf')

    email.send()
except smtplib.SMTPException:
    return render(request, 'catalog/index.html')
return render(request, 'catalog/dashboard.html')

The uploaded files are stored in /media/books_pdf/2018/xyz.pdf And the book.file.url contains the above file path, and yet the pdf file is not getting attached to the email.

所以我是 retrieving the file path dynamically using book.file.url ,但代码是正确的 .

请帮忙,如何检索该书的pdf文件路径/名称 . 谢谢!

UPDATE: Solution found

要检索pdf文件路径,我们必须使用book.file.path而不是book.file.url

1 回答

  • 1

    问题是 attach_file() 方法需要文件系统路径 . 你're not passing a path, you'重新传递了URL .

    您可以更改模板以将路径输出到隐藏字段 - 例如

    <input type="hidden" name="book_pdf" value="{{ book.file.path }}">
    

    但是传递 Bookid 可能会更好,然后从中可以查找所需的所有属性 . 例如:

    传递模板中 Bookid

    <form method="POST" action ="{% url 'email_book' %}" enctype="multipart/form-data">
           {% csrf_token %}
           <input type="hidden" name="book_id" value="{{ book.id }}">
           <button type="submit" class="btn btn-info"><span class="glyphicon glyphicon-envelope"></span>&nbsp;&nbsp;Email</button>
       </form>
    

    修改视图以从 id 中查找 Book

    def send_email(request):
        book = Book.objects.get(pk=int(request.POST.get('id')))
        book_title = book.title
        book_author = book.author
        book_pdf = book.file.path  # Use the path of the book
    

相关问题