I had the same problem. Wrote this:
def get_web_server_base_url(request, settings_override_name=None):
# Allow the value in the settings file to override any computed
value.
url = None
if settings_override_name:
url = getattr(settings, settings_override_name, None)
if not url:
protocol = request.is_secure() and 'https' or 'http'
host = request.get_host()
url = "{0}://{1}".format(protocol, host)
return url
I didn't know about Site or RequestSite at the time. Perhaps I
could
have used them, but:
1. I wanted the protocol (http, or https) to be correct also. Would
RequestSite have done that for me?
2. I wanted to be able to override the hostname with the primary
name of the server (via an entry in settings.py) even if the
request
was sent to a secondary name or the IP address of the server.
I suppose Site would have allowed this, via storing the name in
the DB, but that seems like more work than a settings.py file,
especially since I already have convenient mechanism to manage
different settings.py files when deployed on different servers.
Thoughts?