Reputation: 443
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.
Upvotes: 33
Views: 25892
Reputation: 2932
With Django docs here, You can use:
domain = request.get_host()
# domain = 'localhost:8000'
Upvotes: 21
Reputation: 4501
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()
Upvotes: 0
Reputation: 22449
request.build_absolute_uri('/')
or you could try
import socket
socket.gethostbyname(socket.gethostname())
Upvotes: 22
Reputation: 2264
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
Upvotes: 7