6

I have a util method in Python Django project:

def getUserInfo(request):

    user = request.user
    user_dict = model_to_dict(user)
    user_dict.pop("password")
    user_dict.pop("is_superuser")
    user_dict["head_img"] = user.head_img.url # there is `/media/images/users/head_img/blob_NOawLs1`

I want to add my server domain or ip in the front of it, like:

http://www.example.com:8000/media/images/users/head_img/blob_NOawLs1

How to get current server ip( or domain )?


EDIT

I am not going to get the remote ip, I just want to get the server ip. I mean, I write the Django as backend server, when it is running, how can I get the server ip? or domain.

1

3 Answers 3

14

You can get the hostname from the request like this (docs):

request.get_host()

and the remote IP of the client like this (docs):

request.META['REMOTE_ADDR']

To get the server IP is a bit tricky, as shown in this SO answer, which gives this solution:

import socket
# one or both the following will work depending on your scenario
socket.gethostbyname(socket.gethostname())
socket.gethostbyname(socket.getfqdn())
1
  • get_host gets me the local IP rather than the virtual host configured by nginx. Jun 28, 2018 at 10:50
3

https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.HttpRequest.META

There is another option:

import requests server_ip = requests.get("https://httpbin.org/ip").json()['origin']

when django start

0

like:http://127.0.0.1:1024

# formate: {scheme}://{host}
host_addr =  request._current_scheme_host
1
  • 3
    Maybe add some explanation to this answer for this question at the age of two years?
    – Dilettant
    Jan 19, 2020 at 8:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.