I’m using DjangoRestChannels (based on Django Channels). I made a simple comments page. When new Comment
added by any User
instance consumer sends in to JS and renders on HTML.
Everything works exceps when User
instance gets deleted I’m getting exception django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
Consumers:
class CommentConsumer(ListModelMixin, GenericAsyncAPIConsumer):
queryset = (
Comment.objects.filter(level=0)
.select_related("user", "parent")
.prefetch_related("children")
.order_by("-date_created")
)
serializer_class = CommentSerializer
permission_classes = (AllowAny, )
@action()
async def subscribe_to_comment_activity(self, request_id, **kwargs):
await self.comment_activity.subscribe(request_id=request_id)
@model_observer(Comment)
async def comment_activity(
self,
message: NewCommentSerializer,
observer=None,
subscribing_request_ids=[],
**kwargs
):
await self.send_json(dict(message.data))
@comment_activity.serializer
def comment_activity(self, instance: Comment, action, **kwargs) -> NewCommentSerializer:
"""Returns the comment serializer"""
return NewCommentSerializer(instance)
Model:
class Comment(MPTTModel):
""" The base model represents comment object in db. """
user = models.ForeignKey(CustomUser, related_name="comments", on_delete=models.CASCADE)
parent = TreeForeignKey(
"self",
blank=True,
null=True,
related_name="children",
on_delete=models.SET_NULL
)
date_created = models.DateTimeField(
verbose_name="Created at",
auto_now_add=True,
blank=True,
null=True
)
text = models.TextField(max_length=500)
In terminal exception tracing don’t help me much as among all the exception lines my code was only : await self.send_json(dict(message.data))
in Consumer
method async def comment_activity
.
Any guess regarding this topic? Appreciate any help.