DEV Community

codewitgabi
codewitgabi

Posted on

How to view a django project across other devices from your local computer

By default, django projects are run on the localhost which cannot be accessed from other devices. In this tutorial, I will show you how to do that as quickly as possible.

Go to your project's settings.py file and set ALLOWED_HOSTS = ["your_ip_address"]

It should look like this.

# settings py

ALLOWED_HOST = ["192.167.333.54"] # better
CSRF_TRUSTED_ORIGINS = ["http://192.167.333.54"]
Enter fullscreen mode Exit fullscreen mode

After that, go to your command prompt on Windows or terminal on Linux and start the server in this manner.

# Terminal

$ python manage.py runserver 0.0.0.0:8000
Enter fullscreen mode Exit fullscreen mode

You can now see your django website when you go to that ipaddress on the client's computer.

Note that the computer to access the site must be connected to your network for it to work.

Making it dynamic

Whenever you start a new internet connection, your ip address changes and so you have to keep going to settings.py file to change the ALLOWED_HOST and CSRF_TRUSTED_ORIGINS. Here, I'll make it dynamic so that once your ip address changes, it is automatically updated in settings.py.

To begin, create a file named ip_address.py in your project's folder. Inside it, add the following code.

# ip_address.py

import socket

def get_ip_address():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        return s.getsockname()[0]
    except OSError:
        return socket.gethostbyname(socket.gethostname())
Enter fullscreen mode Exit fullscreen mode

In your settings.py, add this code

# settings.py

from .ip_address import get_ip_address

ALLOWED_HOSTS = [get_ip_address()]
CSRF_TRUSTED_ORIGINS = [f"http://{get_ip_address()}"]

sys.stdout.write(f"http://{get_ip_address()}\n") # get the ip address from the command line.

Enter fullscreen mode Exit fullscreen mode

Top comments (0)