How to use Django to get the name for the host server?


Question

How to use Django to get the name for the host server?

I need the name of the hosting server instead of the client name?

1
47
4/4/2013 1:52:44 PM

Accepted Answer

I generally put something like this in settings.py:

import socket

try:
    HOSTNAME = socket.gethostname()
except:
    HOSTNAME = 'localhost'
74
11/5/2010 4:15:55 AM

If you have a request (e.g., this is inside a view), you can look at request.get_host() which gets you a complete locname (host and port), taking into account reverse proxy headers if any. If you don't have a request, you should configure the hostname somewhere in your settings. Just looking at the system hostname can be ambiguous in a lot of cases, virtual hosts being the most common.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon