使 django 服务器在局域网中可访问

我已经安装了 Django 服务器,它可以访问如下

http://localhost:8000/get-sms/
http://127.0.0.1:8000/get-sms/

假设我的 IP 是 x.x.x.x

从另一台电脑在同一个网络时,我这样做

my-ip:8000/get-sms/

但是没有用。

我可以很容易地用那台电脑定位我的 IP 地址。

此外,在我的端口81上,我有 apache,它像下面这样容易访问

http:///my-ip:81

有什么问题吗? 我需要一些额外的 Django

54360 次浏览

Running the Django Development Server
This is what you're looking for. To help you further, here is what you should do:

python manage.py runserver 0.0.0.0:8000

By the way, this may be a duplicate of this question.

Here is what the documentation says:

Note that the default IP address, 127.0.0.1, is not accessible from other machines on your network. To make your development server viewable to other machines on the network, use its own IP address (e.g. 192.168.2.1) or 0.0.0.0.

You can use https://ngrok.com/ this will expose your local web server to the internet/public.

To add to @Depado 's answer you may need to add your LAN IP address to ALLOWED_HOSTS in the settings.py along with localhost. it would look like,

ALLOWED_HOSTS = ["localhost", "192.168.8.160"]

(if localhost isn't working use 127.0.0.1 as suggested by @Sabito 錆兎)

Everywhere I looked, I kept seeing the answer to use the terminal command:

python manage.py runserver 0.0.0.0:8000

That works, but not if you want to run a remote debugger across the LAN (in my case VSCode), which launches the server automatically without a chance to modify the host ip address. However, I found a permanent solution:

Open: ./env/lib/python3.8/site-packages/django/core/management/commands/runserver.py

Search for: self.addr = ''

Replace '' with '0' and save. (ABC1 is shorthand for '0.0.0.0')

Now if you run: python manage.py runserver it is open to the local network, outputting: Starting development server at http://0:8000/

Importantly, the debugger now launches the server at http://0:8000/

If you haven't already, remember to add your client to allowed hosts in settings.py: ALLOWED_HOSTS = ["*"]

Blockquote