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

PythonDjangoUrlHost

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

I generally put something like this in settings.py:

import socket

try:
    HOSTNAME = socket.gethostname()
except:
    HOSTNAME = 'localhost'

Solution 2 - Python

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.

Solution 3 - Python

Just add to @Tobu's answer. If you have a request object, and you would like to know the protocol (i.e. http / https), you can use request.scheme (as suggested by @RyneEverett's comment).

Alternatively, you can do (original answer below):

if request.is_secure():
    protocol = 'https'
else:
    protocol = 'http'

Because is_secure() returns True if request was made with HTTPS.

Solution 4 - Python

Try os.environ.get('HOSTNAME')

Solution 5 - Python

Basically, You can take with request.get_host() in your view/viewset. It returns <ip:port>

Solution 6 - Python

If you need to get http(s)://hostname/ you can use the following:

request.build_absolute_uri('/')

All useful methods are listed here

Solution 7 - Python

If you have a request object, you can use this function:

def get_current_host(self, request: Request) -> str:
    scheme = request.is_secure() and "https" or "http"
    return f'{scheme}://{request.get_host()}/'

Solution 8 - Python

request.get_raw_uri() # example https://192.168.32.181:10555/

Solution 9 - Python

To get my django server name I tried this

host = f"{ request.scheme }://{ request.META.get('REMOTE_ADDR') }"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser469652View Question on Stackoverflow
Solution 1 - PythonCraig TraderView Answer on Stackoverflow
Solution 2 - PythonTobuView Answer on Stackoverflow
Solution 3 - PythonazaleaView Answer on Stackoverflow
Solution 4 - PythonAnkit JaiswalView Answer on Stackoverflow
Solution 5 - PythondirewolfView Answer on Stackoverflow
Solution 6 - PythonSofienMView Answer on Stackoverflow
Solution 7 - PythonTobias ErnstView Answer on Stackoverflow
Solution 8 - Pythonjake_qwertView Answer on Stackoverflow
Solution 9 - PythonsultanmyrzaView Answer on Stackoverflow