我有一个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> 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 回答
问题是
attach_file()
方法需要文件系统路径 . 你're not passing a path, you'重新传递了URL .您可以更改模板以将路径输出到隐藏字段 - 例如
但是传递
Book
的id
可能会更好,然后从中可以查找所需的所有属性 . 例如:传递模板中
Book
的id
:修改视图以从
id
中查找Book
: