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")

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

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

    def receive_json(self, content, **kwargs):
        channel_layer = get_channel_layer()
                "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:

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

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

    async def __call__(self, scope, receive, send):
            token_key = (dict((x.split('=') for x in scope['query_string'].decode().split("&")))).get('token', None)
        except ValueError:
            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(
                    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.

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