Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current server ip or domain in Django

Tags:

python

django

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.

like image 288
qg_java_17137 Avatar asked Jan 16 '18 09:01

qg_java_17137


People also ask

How do I find my Django server address?

Now run the program using the command python manage.py runserver and navigate to http://127.0.0.1:8000/user_ip/ this will show the output. It is showing 127.0. 0.1 because I m on the localhost.

How can I get the domain name of my site within a Django template?

In the template, you can use {{ site. domain }} to get the current domain name.

What is HttpResponse in Django?

HttpResponse Methods – Django It is used to instantiate an HttpResponse object with the given page content and content type. HttpResponse.__setitem__(header, value) It is used to set the given header name to the given value.


1 Answers

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())
like image 93
Paolo Stefan Avatar answered Oct 07 '22 10:10

Paolo Stefan