我有一个Django库应用程序,其中客户可以从书籍列表中通过电子邮件发送特定书籍的pdf文件链接,该链接最初是由管理员使用FileField上传的。
现在,电子邮件已成功发送/接收,但是pdf文件未附加。
我也已经研究了其他的stackoverflow参考,但是我无法解释正确的解决方案: Django email attachment of file upload
单击电子邮件按钮后,将按以下方式提交表单: 在提交表单时,还将提交三个隐藏的值。 ,其中之一就是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分类,如下所示:
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')
上传的文件存储在/media/books_pdf/2018/xyz.pdf 并且book.file.url包含上面的文件路径,但是pdf文件未附加到电子邮件中。
所以我使用book.file.url 动态检索文件路径,但是代码正确。
请帮助,我该如何检索该书的pdf文件路径/名称。 谢谢!
更新:找到解决方案
要检索pdf文件路径,我们必须使用book.file.path而不是book.file.url
答案 0 :(得分:1)
问题是r2c
方法需要文件系统路径。您没有传递路径,而是通过URL。
您可以更改模板以将路径输出到隐藏字段中,例如
c2r
但是最好传递attach_file()
中的<input type="hidden" name="book_pdf" value="{{ book.file.path }}">
,然后从中查找所需的所有属性。例如:
在模板中传递id
中的Book
:
id
修改视图以从Book
中查找 <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> Email</button>
</form>
:
Book