python - Django : Set url dynamically with <a> element in template

标签 python django

我想知道如何在 Django 中更改此链接:

<a href="http://localhost:8000{% url 'my-token' token=token %}">{{title}}</a>

我想设置http://localhost:8000动态地。如果我在本地工作,则为 http://localhost:8000如果我在我的开发服务器或生产服务器上,它可能是 https://subdomaine.domain.com

我的想法:

我可以创建不同的设置文件:local.py/dev.py/prod.py并在每个内部定义:

#local.py
SITE_URL = "http://localhost:8000"
#dev.py
SITE_URL = "http://dev.domain.com"
#prod.py
SITE_URL = "http://prod.domain.com"

那么我该如何处理我的 <a>链接添加SITE_URL

也许有类似的东西{{ request.META.HTTP_HOST }}

解决方案:

您可以在这里找到使用 Django CBV 生成我的电子邮件的 View :

class HomeView(TemplateView):
    def send_email(self, email, upload, title, token):
        context = {
            'document_link': upload,
            'publication_title': title,
            'token': token,
            'MY_SITE_URL': settings.MY_SITE_URL
        }
        subject = 'my subject'
        message = get_template('emails/message.txt').render(context)
        mail = EmailMultiAlternatives(subject, message, 'toto@test.eu', [email])
        html_message = get_template('emails/message.html').render(context)
        mail.attach_alternative(html_message, "text/html")
        mail.send(fail_silently=False)

还有 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>

<p>Please find below your download link for the free publication:</p>

<br>

<a href="{{ MY_SITE_URL }}{% url 'freepub-token' token=token %}">{{ publication_title }}</a>

<br>

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

<br>

<p>Thank you for your interest to publications.</p>

</body>
</html>

最佳答案

您可以添加自定义 context_processor :

def site(request):
    return {'SITE_URL': settings.SITE_URL}

然后将其添加到您的 CONTEXT_PROCESSOR 设置

 mysite.context_processors.site,

并且标签 {{ SITE_URL }} 将可用。

关于python - Django : Set url dynamically with <a> element in template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53413131/

相关文章:

python - 使用 django_tables2 在 django 中的表中添加 CSS 样式

python - Django Booleanfiedl Checkbox 和 Label 显示为两行

python - Pillow 未加载图像 - 无法识别图像文件

python - 将图像缩减为由一组点定义的路径

python - Django 休息框架 : get_FOO_display in serializer not letting me POST

javascript - 如何使用 Django 后端保护 AJAX 调用?

python - Pandas 检查多行中的重叠日期

python - 使用 python (foursquare API) 解析 json 文件中的较低级别?

python - Python 中链表中的“AttributeError”

python - 是否可以使用实时信号自动更新干草堆弹性中的多个索引