23

I'm using django templates to create an e-mail. I do something like this:

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()

My template uses named url patterns like so: {% url url_name parameter %}

Which works fine, except it will render a relative url, like: /app_name/url_node/parameter

Usually that is enough, but since this is an e-mail I really need it to be a full url - with the server name prepended, like: http://localhost:8000/app_name/url_node/parameter.

How can I do this? How do I dynamically get the server name? (I don't want to hardcode it for sure).

Another way of asking: how do I get HttpServletRequest.getContextPath() ala Java, but instead in Django/Python?

thanks

Allen
  • 285
  • 1
  • 2
  • 9

1 Answers1

19

Use sites application:

Site.objects.get_current().domain

Example direct from documentation:

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])

    # ...
karthikr
  • 97,368
  • 26
  • 197
  • 188
dryobates
  • 324
  • 3
  • 4
  • 7
    How about WITHOUT using Sites? Is there a way to do this? It's pretty silly to have to rely on a model. – JamesD Feb 12 '12 at 04:02
  • 2
    You could always set it in your settings file and over-ride it with your local_settings file – super9 Mar 13 '12 at 04:53
  • 4
    See http://stackoverflow.com/questions/2345708/how-can-i-get-the-full-absolute-url-with-domain-in-django – glarrain Dec 07 '12 at 19:14