user469652
user469652

Reputation: 51241

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

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?

Upvotes: 72

Views: 77264

Answers (9)

Sofien
Sofien

Reputation: 1680

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

request.build_absolute_uri('/')

All useful methods are listed here

Upvotes: 14

sultanmyrza
sultanmyrza

Reputation: 5392

To get my django server name I tried this

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

Upvotes: -1

jake_qwert
jake_qwert

Reputation: 9

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

Upvotes: 0

Tobias Ernst
Tobias Ernst

Reputation: 4634

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()}/'

Upvotes: 5

direwolf
direwolf

Reputation: 85

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

Upvotes: 3

azalea
azalea

Reputation: 12610

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.

Upvotes: 9

Ankit Jaiswal
Ankit Jaiswal

Reputation: 23427

Try os.environ.get('HOSTNAME')

Upvotes: 6

Tobu
Tobu

Reputation: 25426

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.

Upvotes: 89

Craig Trader
Craig Trader

Reputation: 15679

I generally put something like this in settings.py:

import socket

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

Upvotes: 112

Related Questions