500 error on django channels send message to group

I have the following Django channels consumer but when I try to send data to the stocks group، it returns a 500 error.

Also, I don't get any error logs.

Here is the consumer:

class AuthRequiredConsumer(JsonWebsocketConsumer):

    def connect(self):
        user = self.scope['user']
        print(isinstance(user, AnonymousUser))
        if isinstance(user, AnonymousUser):
            raise DenyConnection("authentication required")
        self.accept()


class ChatConsumer(AuthRequiredConsumer):
    groups = ['stocks']
    channel_layer_alias = "stocks"

    def stocks_data(self, event):
        print(event)
        return self.send_json({'message': event['text']})

    def receive_json(self, content, **kwargs):
        channel_layer = get_channel_layer()
        async_to_sync(channel_layer.group_send)(
            "stocks",
            {
                "type": "stocks.data",
                "text": "Hello there!",
            },
        )

        message = content["message"]

        self.send_json({"message": message})

Also, I use this middle to authenticate users by the token:

@database_sync_to_async
def get_user(token_key):
    try:
        token = Token.objects.get(key=token_key)
        return token. user
    except Token.DoesNotExist:
        return AnonymousUser()


class TokenAuthMiddleware(BaseMiddleware):
    def __init__(self, inner):
        super().__init__(inner)

    async def __call__(self, scope, receive, send):
        try:
            token_key = (dict((x.split('=') for x in scope['query_string'].decode().split("&")))).get('token', None)
        except ValueError:
            print("error")
            token_key = None
        scope['user'] = AnonymousUser() if token_key is None else await get_user(token_key)
        return await super().__call__(scope, receive, send)


TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner))

And here is the routing config:

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": TokenAuthMiddlewareStack(
            URLRouter(
                [
                    re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi())
                ]
            )
        )
        ,
    }
)

I debugged the receive_json method using breakpoints And I saw self.channel_name and self.channel_layer is None!!

Does anyone have an idea what's up with this consumer?

Probably you forgot to set the CHANNEL_LAYERS property at settings file.

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}
Back to Top