You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Daphne启动报错:Apps aren't loaded yet及端口占用问题

问题解决指南:Daphne启动错误与端口占用问题

一、解决Daphne启动时的AppRegistryNotReady: Apps aren't loaded yet错误

错误原因

你的asgi.py中存在冗余的初始化代码,且调用顺序错误:get_asgi_application()已经自动完成Django的环境初始化与应用加载流程,额外调用django.setup()会导致应用加载逻辑冲突,触发未就绪错误。

修正后的asgi.py代码

import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from channels.security.websocket import AllowedHostsOriginValidator
import chat.routing

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "messanger.settings")

# 初始化Django ASGI应用,自动完成应用加载
django_asgi_app = get_asgi_application()

application = ProtocolTypeRouter({
    "http": django_asgi_app,
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(chat.routing.websocket_urlpatterns)
        )
    ),
})

额外修正(避免潜在问题)

你的consumer.py存在两处细节错误,建议同步修正:

class ChatConsumer(WebsocketConsumer):
    # ... 保留其他原有方法 ...

    def chat_message(self, event):
        message = event["message"]
        author_id = event["author_id"]
        chat_id = event["chat_id"]
        
        # 安全获取用户,避免用户不存在时抛出异常
        author = User.objects.filter(id=author_id).first()
        author_username = author.username if author else "未知用户"

        self.send(text_data=json.dumps({
            "type": "chat",
            "message": message,
            "chat_id": chat_id,
            "author_id": author_id,
            "author_username": author_username
        }))

    def disconnect(self, close_code):
        channel_layer = get_channel_layer()
        # 修正方法名:group_discard → group_remove(Channels官方标准方法)
        async_to_sync(channel_layer.group_remove)(
            self.room_group_name,
            self.channel_name
        )

二、解决端口占用错误Listen failure: Couldn't listen on 127.0.0.1:8000: [Errno 48] Address already in use

方法1:终止占用端口的进程

  • Mac/Linux:
    1. 查找占用8000端口的进程ID:
      lsof -i :8000
      
    2. 杀掉目标进程(替换<PID>为查到的进程ID):
      kill -9 <PID>
      
  • Windows:
    1. 查找占用8000端口的进程ID:
      netstat -ano | findstr :8000
      
    2. 强制终止进程(替换<PID>为查到的进程ID):
      taskkill /F /PID <PID>
      

方法2:更换端口启动服务器

启动时指定未被占用的端口,例如8002:

# 用Django自带服务器启动
python manage.py runserver 8002

# 用Daphne启动
daphne -p 8002 messanger.asgi:application

内容的提问来源于stack exchange,提问作者Стас Нікулиця

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 00:15:05