Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the server name in Django for a complete url?

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

like image 590
Allen Avatar asked May 21 '09 13:05

Allen


People also ask

How can I get full URL in Django?

Use handy request. build_absolute_uri() method on request, pass it the relative url and it'll give you full one. By default, the absolute URL for request. get_full_path() is returned, but you can pass it a relative URL as the first argument to convert it to an absolute URL.

What is the server name of Django?

Django's primary deployment platform is WSGI, the Python standard for web servers and applications.

What is URL tag in Django?

The URL template tag is a typical type of Tag in the Django Template Language framework. This tag is specifically used to add View URLs in the Template Files. In the HTML Template file, URL tags are used with the Anchor, <a href> attribute of HTML, which handles all the URLs in HTML.


1 Answers

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

    # ...
like image 164
dryobates Avatar answered Oct 19 '22 19:10

dryobates