djangourlsatchmo

How to construct a full URL in django


I need to get django to send an email which contains a URL like this

http://www.mysite.org/history/

Where 'history' is obtained like so:

history_url = urlresolvers.reverse('satchmo_order_history')

history_url is a parameter that I pass on to the function that sends the email, and it correctly produces '/history/'. But how do I get the first part? (http://www.mysite.org)

Edit 1

Is there anything wrong or unportable about doing it like this? :

history = urlresolvers.reverse('satchmo_order_history')
domain = Site.objects.get_current().domain
history_url = 'http://' + domain + history

Solution

  • If you have access to an HttpRequest instance, you can use HttpRequest.build_absolute_uri(location):

    absolute_uri = request.build_absolute_uri(relative_uri)
    

    In alternative, you can get it using the sites framework:

    import urlparse
    from django.contrib.sites.models import Site
    
    domain = Site.objects.get_current().domain
    absolute_uri = urlparse.urljoin('http://{}'.format(domain), relative_uri)
    

    Re: Edit1

    I tend to use urlparse.join, because it's in the standard library and it's technically the most Pythonic way to combine URIs, but I think that your approach is fine too.