我想知道如何在 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/