31

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.

Mark Waugh
  • 423
  • 1
  • 5
  • 10

5 Answers5

22
request.build_absolute_uri('/')

or you could try

import socket
socket.gethostbyname(socket.gethostname())
Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100
19

With Django docs here, You can use:

domain = request.get_host()
# domain = 'localhost:8000'
micfan
  • 800
  • 8
  • 12
Rustem
  • 2,884
  • 1
  • 17
  • 32
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
1
import socket
host = socket.gethostname()
Adriaan Tijsseling
  • 2,025
  • 1
  • 18
  • 23
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