I would like to run a Django server locally using a local IP.
I have localhost
mapped here:
$ head -n 1 /etc/hosts
127.0.0.1 localhost
I have this chunk of code in my settings.py
:
import os
ALLOWED_HOSTS = ['HERE.IS.MY.IP', 'localhost', '127.0.0.1']
print "ALLOWED_HOSTS: {}".format(ALLOWED_HOSTS)
In my mysql database I have this site table:
mysql> select * from django_site;
+----+--------------------+----------------+
| id | domain | name |
+----+--------------------+----------------+
| 1 | example.com | example.com |
| 5 | HERE.IS.MY.IP:8000 | projectsdb |
| 8 | 127.0.0.1:8000 | projectsdb |
| 9 | localhost:8000 | projectsdb |
+----+--------------------+----------------+
I run the server locally on 127.0.0.1
:
$ python manage.py runserver 8000
ALLOWED_HOSTS: ['HERE.IS.MY.IP', 'localhost', '127.0.0.1']
Performing system checks...
# ...
Django version 1.10.5, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
If I go to this address http://HERE.IS.MY.IP:8000
it works. But of course I'd like to open it using a local IP such as http://localhost:8000
or http://127.0.0.1:8000
. But this does not work. What am I missing?
Ok I solved it, silly me. I thought I was trying to access the server's page locally, but I wasn't. The server is running on a specific machine, and I was trying to access it locally from another machine (my laptop).
Explanations: The server runs on HERE.IS.MY.IP:8000
, only locally because I only gave the port 8000:
$ python manage.py runserver 8000
I am trying to access the server from the web browser on my laptop, so the IP used is different than HERE.IS.MY.IP
. If I want to access the page on http://HERE.IS.MY.IP:8000
from my laptop I have no other choice than to allow the server access to external machines by running the server like this:
$ python manage.py runserver 0.0.0.0:8000
or
$ python manage.py runserver HERE.IS.MY.IP:8000
and then to access it on my laptop's browser with the full IP (unless I map it on /etc/hosts
) on http://HERE.IS.MY.IP:8000
Now if I want to access the page locally only
from the server side, I have to run
$ python manage.py runserver 8000
, open a browser from the said server and then I can contact the pages http://HERE.IS.MY.IP:8000
, http://127.0.0.1:8000
and http://localhost:8000
successfully.
So my mistake here was that I was accessing the server's page not from the server's browser itself but from another machine's.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.