首页 > 解决方案 > Django:在电子邮件中添加下载链接

问题描述

我正在尝试在我的电子邮件中添加下载链接,以便下载存储在媒体目录中的 pdf 文件。我没有克服在我的电子邮件内容中创建此 url 链接。

这是我views.py的 post 功能:

def post(self, request, *args, **kwargs):
    form = self.form_class()
    document_choice = request.POST.getlist('DocumentChoice')

    if request.method == 'POST':
        form = self.form_class(request.POST)

        for checkbox in document_choice:
            document_edqm_id = Document.objects.get(id=checkbox).edqm_id
            email = request.POST['email']

            plain = email + document_edqm_id + str(datetime.now())
            token = hashlib.sha1(plain.encode('utf-8')).hexdigest()

            Download.objects.create(email=email, pub_id=checkbox, token=token)

            document_link = Document.objects.get(id=checkbox).upload
            print(document_link)

            context = {'document_link': document_link}

            if form.is_valid():
                message = get_template('app/message.txt').render(context)
                html_message = get_template('app/message.html').render(context)
                subject = 'yoto'

                mail = EmailMultiAlternatives(subject, message, 'app@tec.eu', [email])
                mail.attach_alternative(html_message, "text/html")
                mail.send(fail_silently=False)
                print('Email envoyé à ' + email)
            else:
                print('form invalid')
    return HttpResponseRedirect(self.get_success_url())

还有我的 message.txt 和 message.html 文件:

#message.txt

== This E-mail is automatically generated, please do not reply to it ==


    {{ document_link }}

You can use this link as much as you like. It will expire in 0 days.

#message.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>

<p>== This E-mail is automatically generated, please do not reply to it ==</p>

<br>


<a href="http://localhost:8000/media/{{ document_link}}">Download</a>

<br>

<p>You can use this link as much as you like. It will expire in 0 days.</p>

<br>

</body>
</html>

结果 :

我克服了将文件显示到新标签中,但我想下载这个

问题 :

到目前为止,我如何添加下载文件链接而不是在新选项卡中显示文件?

谢谢

标签: djangodjango-templatesdjango-views

解决方案


推荐阅读