When i run the server it shows me a message http://127.0.0.1:8000/. I want to get the url in code. I dont have request object there.
Asked
Active
Viewed 2.4k times
31
-
In which code you want to get the URL? – okm Apr 12 '12 at 08:11
-
Long time ago, but did you found the answer? – Gocht Aug 18 '15 at 19:54
5 Answers
22
request.build_absolute_uri('/')
or you could try
import socket
socket.gethostbyname(socket.gethostname())

Hedde van der Heide
- 21,841
- 13
- 71
- 100
6
If you want to know exactly the IP address that the development server is started with, you can use sys.argv
for this. The Django development server uses the same trick internally to restart the development server with the same arguments
Start development server:
manage.py runserver 127.0.0.1:8000
Get address in code:
if settings.DEBUG:
import sys
print sys.argv[-1]
This prints 127.0.0.1:8000

Wesley
- 2,204
- 15
- 14
-
nice one, I thought this should be possible, couldn't find the restart command :-) – Hedde van der Heide Apr 12 '12 at 08:02
-
The autoreload mechanism is in django.utils.autoreload. In the restart_with_reloader method, it takes its arguments from `sys.argv` – Wesley Apr 12 '12 at 08:53
-
This answer definitely deserves more credit since it isnt dependent on a request being sent. Do you know if this works on a production server? – Bigbob556677 Jul 09 '19 at 14:51
0
import re
import subprocess
def get_ip_machine():
process = subprocess.Popen(['ifconfig'], stdout=subprocess.PIPE)
ip_regex = re.compile('(((1?[0-9]{1,2})|(2[0-4]\d)|(25[0-5]))\.){3}((1?[0-9]{1,2})|(2[0-4]\d)|(25[0-5]))')
return ip_regex.search(process.stdout.read(), re.MULTILINE).group()

Andres
- 4,323
- 7
- 39
- 53