【问题标题】:How do I get the server name in Django for a complete url?如何在 Django 中获取服务器名称以获得完整的 url?
【发布时间】:2010-10-27 22:31:33
【问题描述】:

我正在使用 django 模板来创建电子邮件。我做这样的事情:

msg_html = render_to_string('email/%s.html' % template_name, context)
msg = EmailMultiAlternatives(subject, msg_text, from_email, to_list)
msg.attach_alternative(msg_html, "text/html")
msg.content_subtype = "html"
msg.send()

我的模板使用命名的 url 模式,如下所示: {% url url_name 参数%}

这很好用,除了它会呈现一个相对 url,比如: /app_name/url_node/参数

通常这就足够了,但由于这是一封电子邮件,我真的需要它是一个完整的 url - 前面有服务器名称,例如: http://localhost:8000/app_name/url_node/parameter.

我该怎么做?如何动态获取服务器名称? (我肯定不想硬编码)。

另一种提问方式:我如何获得 HttpServletRequest.getContextPath() ala Java,而不是在 Django/Python 中?

谢谢

【问题讨论】:

    标签: django-templates


    【解决方案1】:

    使用站点应用程序:

    Site.objects.get_current().domain
    

    直接来自文档的示例:

    from django.contrib.sites.models import Site
    from django.core.mail import send_mail
    
    def register_for_newsletter(request):
        # Check form values, etc., and subscribe the user.
        # ...
    
        current_site = Site.objects.get_current()
        send_mail('Thanks for subscribing to %s alerts' % current_site.name,
            'Thanks for your subscription. We appreciate it.\n\n-The %s team.' % current_site.name,
            'editor@%s' % current_site.domain,
            [user.email])
    
        # ...
    

    【讨论】:

    • 不使用站点怎么样?有没有办法做到这一点?不得不依赖模型是很愚蠢的。
    • 你总是可以在你的设置文件中设置它并用你的 local_settings 文件覆盖它
    猜你喜欢
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 1970-01-01
    • 2016-06-02
    • 2011-05-04
    • 2018-06-23
    • 1970-01-01
    相关资源
    最近更新 更多