When i try to run
daphne -p 8001 messanger.asgi:application
I get this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
If i run server without daphne, I get this error: Listen failure: Couldn't listen on 127.0.0.1:8000: [Errno 48] Address already in use.
This is my settings .py:
INSTALLED_APPS = [
"channels",
"chat",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
'django_extensions',
]
ASGI_APPLICATION = "messanger.asgi.application"
CHANNEL_LAYERS = {
"default": {
"BACKEND": "channels_redis.core.RedisChannelLayer",
"CONFIG": {
"hosts": [os.environ.get("REDIS_URL", "redis_url")],
},
},
}
This is my asgi.py:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "messanger.settings")
django_asgi_app = get_asgi_application()
django.setup()
application = ProtocolTypeRouter({
# Django's ASGI application to handle traditional HTTP requests
"http": django_asgi_app,
# WebSocket chat handler
"websocket": AllowedHostsOriginValidator(
AuthMiddlewareStack(
URLRouter(chat.routing.websocket_urlpatterns)
)
),
})
This is my consumer.py:
class ChatConsumer(WebsocketConsumer):
def connect(self):
self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
self.room_group_name = "chat_%s" % self.room_name
# Join room group
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_add)(
self.room_group_name, self.channel_name
)
self.accept()
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json["message"]
author_id = text_data_json["a"]
chat_id = text_data_json["chat"]
message_create = Message(content=message, author_id=author_id, chat_id=chat_id)
message_create.save()
print("message:", message, "author_id:", author_id, "chat_id:", chat_id)
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
self.room_group_name,
{
"type": "chat_message",
"message": message,
"author_id": author_id,
"chat_id": chat_id
}
)
def chat_message(self, event):
message = event["message"]
author_id = event["author_id"]
author_username = User.objects.get(id=author_id).username
chat_id = event["chat_id"]
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()
async_to_sync(channel_layer.group_discard)(
self.room_group_name,
self.channel_name
)