Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Contains null values during migration
I try to add a new field to my model, allowing to be null or blank. chapter = models.IntegerField(max_length=4, default=None, blank=True, null=True) Make migrations worked fine: python3 manage.py makemigrations But when I try to migrate, I get this error: return self.cursor.execute(sql, params) django.db.utils.IntegrityError: column "chapter" contains null values OK, I understand what the error tries to tell, there are records already...But I allow chapter field to be null. Aren't these 3 enough to set new rows as null? default=None, blank=True, null=True) Truncating database is the easy way, I want to understand how to do such migrations with existing data. What am I missing? -
How to create django app programmatically using call_command
In my project current scenario i am required to create app programmatically. What i have done so far, the steps are listed below. 1 - I have created a test app which is just simple text field crud. 2 - In Testapp model i am using post_save.connect method to run some custom app generation code. def model_created_or_updated(sender, **kwargs): the_instance = kwargs['instance'] if kwargs['created']: app_name = ''.join(the_instance.test_title.lower().split()) generate_app(app_name) generate_app_model(app_name) generate_settings(app_name) create_migration(app_name) post_save.connect(model_created_or_updated, sender=TestApp) 3 - Now the first generate_app method create app (see below), Below function will created the app def generate_app(self): management.call_command('startapp', self) 4 - After that i have generate_app_model, I have programmatically write the newly created app model to add some custom fields in it. def generate_app_model(self): app_name = self try: model_file_ = open(os.path.join(settings.BASE_DIR, app_name + '/models.py'), 'r+') except IOError: print("An error was found. Either path is incorrect or file doesn't exist!") finally: class_name = str(app_name).capitalize() title_field = app_name + '_title' file_field = app_name + '_file' timestamp_field = app_name + '_timestamp' line1 = 'from django.db import models \n\n' line2 = 'class ' + class_name + '(models.Model): \n\n' line3 = '\t' + title_field + ' = models.CharField(max_length=200) \n' line4 = '\t' + file_field + ' = models.FileField(upload_to="uploads/' + app_name + … -
Listing view will not filter based on captured URL value
With a given URL path, there is a variable portion that dictates which model instances are displayed depending on whatever uppercase letter is contained within it. As shown, the letter 'A' is set as the default for the view. However, if any other letter is passed to the path (such as 'B', "C", ...), the QuerySet is not filtered to what should be only those instances whose first letter matches that variable captured value. What can be done so that any letter from A-Z will return the correct QuerySet. As of now, any uppercase letter returns only a QuerySet where each model instances' first letter begins with 'A'. # urls.py from django.contrib import admin from django.urls import path, re_path, include from minerals import views mineral_patterns = ([ re_path("", views.filter_letter_list, name="letter_list"), re_path('(?P<query>([A-Z]))/', views.filter_letter_list, name="letter_list"), ], "minerals") urlpatterns = [ path('admin/', admin.site.urls), path('', include(mineral_patterns)) ] # views.py from random import choice from string import ascii_uppercase from django.shortcuts import render, get_list_or_404 from .models import Mineral # Create your views here. def filter_letter_list(request, query="A"): # import pdb; pdb.set_trace(); minerals = get_list_or_404(Mineral, name__startswith=query) random_mineral = choice(Mineral.objects.all()) return render( request, "minerals/list.html", context={ 'minerals': minerals, 'random_mineral': random_mineral, 'query': query, 'letters': ascii_uppercase } ) -
Django - Where IN with multiple columns
I have a query that needs to fetch from a table that meet two columns requirements exactly. So if I have users table with columns, age and score. SELECT * FROM users where (age, score) IN ((5,6), (9,12), (22,44)..) In my web app I am getting this pairs from an ajax request, and the number could be quite big. How do I construct a query for this in Django? I am working on postgres database -
Date picker is not initializing in django template
In my django template form it having one issue when I submitting the form I just checked the console it showing jquery-3.2.1.min.js:2 Uncaught TypeError: $(...).daterangepicker is not a function at HTMLDocument.<anonymous> (<anonymous>:4:37) at j (jquery-3.2.1.min.js:2) at k (jquery-3.2.1.min.js:2) I can understand the date picker initialising issue ... But its working fine in my local system but issue in the production ..... No idea why its showing like this in production only Here is my code <div class="modal-body"> <form method="post" id="new_form"> </form> </div> <script type="text/javascript" src="{% static 'assets/plugins/moment/moment.min.js' %}"></script> <link rel="stylesheet" href="{% static 'assets/plugins/daterangepicker/daterangepicker.css' %}"/> <script type="text/javascript" src="{% static 'assets/plugins/daterangepicker/daterangepicker.min.js' %}"></script> <script type="text/javascript"> $(document).ready(function() { $('input[name="joining_date"]').daterangepicker({ singleDatePicker: true, showDropdowns: true, joining_date: moment().startOf('hour'), "locale": { "format": "YYYY-MM-DD", "separator": "-" } }); }); -
Python contains and icontains both return case insensitive results
I have a very curious case that I'm not sure I understand. I am filtering data using field__contains but am getting case insensitive results. As an example: Entry Data: { "id": 2, "last_login": null, "is_superuser": false, "username": "slappy", "first_name": "don", "last_name": "sweeney", "email": "don@bruins.com", "is_staff": false, "is_active": true, "date_joined": "2019-12-09T09:07:11.897502Z", "groups": [], "user_permissions": [] } Search: query = { 'email__contains' : 'DON' } data_set = data_set.filter(Q(**query)) return data_set The results return the entry despite the casing clearly being wrong. I checked other filter types and they are working as expected: Search 2: query = { 'username__exact' : 'SLAPPY' } data_set = data_set.filter(Q(**query)) return data_set This search produces no results, as would be expected. Am I missing something here? Would could be the root cause of this? I would expect contains to be case sensitive and icontains to be case insensitive, otherwise why would the two exist? -
role of viewsets in django rest frameowrk when url is mapped to a method
Being new to drf , i am having slight issues in reading the code . In my urls.py of the app i see this . url(r'^ques', populate_health_questions) Now in views.py I see this . class QuestionViewSets(viewsets.ModelViewSet): #import pdb;pdb.set_trace(); queryset = HealthQuestions.objects.all() serializer_class = HealthQuestionsSerializer def get_permissions(self): print("self.action ", self.action) permission_classes = [] if self.action == 'create': import pdb;pdb.set_trace(); permission_classes = [IsAuthenticated, IsAdminUser] elif self.action == 'retrieve': permission_classes = [IsAuthenticated, IsAdminUser] elif self.action == 'update' or self.action == 'partial_update': permission_classes = [IsAuthenticated, IsAdminUser], elif self.action == 'destroy': permission_classes = [IsAuthenticated, IsAdminUser] elif self.action == 'list': permission_classes = [IsAuthenticated] return [permission() for permission in permission_classes] @api_view(['get']) def populate_health_questions(request): #import pdb;pdb.set_trace(); print("HealthQuestions",HealthQuestions.objects.all()) for data in HealthQuestions.objects.all(): print(data.ques) HealthQuestions.objects.all().delete() print("HealthQuestions after deleting",HealthQuestions.objects.all) questions = { "circulatory_issues" :"Heart Conditions or any other Blood or Circulatory Disorders except Hypertension?", "endocrine_issue" : "Other Endocrine Issues such as Hyperthyroidism or Pituitary / Parathyroid / Adrenal Gland Disorders?", } qlist = [] for key,ques in questions.items() : qlist.append({ "key" : key, "ques" : ques }) serializer = HealthQuestionsSerializer(data=qlist, many = True) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now what i understand is that in order to get the ques route working , i look at the … -
What is the "best" way to build a Django Webapp frontend?
Thanks in advance! This is more a "philosophical" question then a direct request for opinions on code, though I would greatly appreciate anyone's input on code examples to look at. I've been a "traditional" developer for as long as I can remember, and now I work professionally as a data scientist. That being said, the one frontier I've never truly touched is web development. For a project I'm working on, I need to build (and in a somewhat expedited timeframe) a good-looking web application that functions somewhat similarly to a Wiki website (using existing codebases like Mediawiki is not an option here, so assume everything has to be built from the ground-up). In trying to do things the "right way", I've set things up as follows: Django models are built that seem to correctly capture the relational structure of data for the webapp, at least as tested by playing with Django's admin portal Django is hooked up to a Postgres database (1) and (2) are running inside Docker containers The most important piece here left, obviously, is the frontend. I've tried to ask several friends and acquaintances for advice, and have been pointed in the Bootstrap direction. From here, I … -
Why isn't my Django REST Framework URL resolving?
I am building an API with Django REST Framework, using: Viewsets Non-standard namespacing HyperlinkedModelSerializer URLPathVersioning I am trying to cut out a lot of what I perceive to be irrelevant aspects of my application as it is large, established, and closed-source. However, if you can think of anything I have missed I will provide additional information. I have configured my HyperlinkedModelSerializer to support my custom-namespaced Viewset. class ItemSerializer(serializers.HyperlinkedModelSerializer): class Meta: fields = ["id", "url", "description", "source_id", "location", "test"] model = models.Item extra_kwargs = { "url": { "view_name": "api:v1:questions:item-detail", "lookup_field": "pk", } } My Viewset: class ItemViewSet(APIMixin, viewsets.ReadOnlyModelViewSet): queryset = models.Item.objects.all() serializer_class = serializers.ItemSerializer # This is largely inconsequential, except for maybe the versioning class. class APIMixin(SerializerExtensionsAPIViewMixin): authentication_classes = [authentication.SessionAuthentication] filter_backends = [ django_filters.DjangoFilterBackend, filters.OrderingFilter, ] ordering_fields = [] pagination_class = pagination.DefaultPageNumberPagination parser_classes = [ parsers.JSONParser, parsers.FormParser, parsers.MultiPartParser, ] permission_classes = [ permissions.IsAuthenticated, permissions.DjangoObjectPermissions, ] versioning_class = versioning.URLPathVersioning Loading a view from the viewset (list or detail) throws the following: Traceback: File "/usr/local/lib/python3.5/dist-packages/rest_framework/reverse.py" in reverse 41. url = scheme.reverse(viewname, args, kwargs, request, format, **extra) File "/usr/local/lib/python3.5/dist-packages/rest_framework/versioning.py" in reverse 88. viewname, args, kwargs, request, format, **extra File "/usr/local/lib/python3.5/dist-packages/rest_framework/versioning.py" in reverse 25. return _reverse(viewname, args, kwargs, request, format, **extra) File "/usr/local/lib/python3.5/dist-packages/rest_framework/reverse.py" in _reverse … -
How can I get parent model object from signal in django
I'm a beginner in python and django. Can you explain to me, how can I get parent model from signal in onetomany relations. For example, I have 2 models: class ModelOne(models.Model): name = models.CharField(max_length=20) class Modeltwo(models.Model): comment = models.CharField(max_length=20) mo = models.ForeignKey(ModelOne) And signal for post_save: @receiver(post_save) def post_save_model(sender,instance,**kwargs): print("Signal: ",instance.objects.all().last()) How can I get related object of ModelOne in post_save_model function when I save ModelTwo? -
using URL passed values, render different outputs in django template
views.py class citydetailview(generic.ListView): model = country def get_queryset(self): city_type = self.kwargs['city_type'] if city_type == 1: mytypes=city1.objects.all() ads=test1_ads.objects.all() context={'ads':ads,'mytypes':mytypes} return context elif city_type == 2: mytypes=city2.objects.all() ads=test2_ads.objects.all() context={'ads':ads,'mytypes':mytypes} return context elif city_type == 3: mytypes=city3.objects.all() ads=test3_ads.objects.all() context={'ads':ads,'mytypes':mytypes} return context return super().get_queryset() I am trying to render the the output from model: country and from the conditional context from query set. And i am trying how to makeup the template for this class view. To do so need your assistance.:) -
Encrypt Django Source Code information is still not there yet?
i have search some information about encrypt the django sourcode like ioncube for php and other. but for django i can't find the information, there are a few question for many years with negative answer. its still not there yet the encryptor for django ? and if its still not there yet, what the solution to protect the source code if we have to put the source code in the local client server. if you have the solution please to tell me how to or what you usually do to protect your source code if you have to put this in your client server, where your client can access and see it too. thanks before, -
How to have a button in Django template to add more form variable? Then how to process the multiple forms in views?
I have 2 questions: How to code a button to be able to add 1 or more duplicate form variable in template? I want to have a product_create page with a Product that may have multiple Color and Thickness. Then how to save the Product with multiple Color and Thickness in views.py to database? Do I need for loop? My 4 related models in models.py: class Product(models.Model): product_id = models.CharField(max_length=6) video = models.URLField(max_length=250, null=True, blank=True) class ColorParent(models.Model): name = models.CharField(max_length=50) class ProductColor(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) color = models.ForeignKey(ColorParent, on_delete=models.CASCADE) class ProductThickness(models.Model, MeasurementUnits): product = models.ForeignKey(Product, on_delete=models.CASCADE) dimension = models.PositiveIntegerField(verbose_name='Thickness in International SI unit', null=True, blank=True) dimension_unit = models.CharField(max_length=20, choices=MeasurementUnits.si_base_units, default=MeasurementUnits.millimetre, null=True, blank=True) alias = models.CharField(verbose_name='Thickness in Imperial unit', max_length=10, null=True, blank=True) alias_unit = models.CharField(max_length=20, choices=MeasurementUnits.imperial_base_units, default=MeasurementUnits.inch, null=True, blank=True) My forms.py: class ProductForm(ModelForm): class Meta: model = Product fields = ['product_id', 'video'] class ColorParentForm(ModelForm): class Meta: model = ColorParent fields = ['name'] class ProductColorForm(ModelForm): class Meta: model = ProductColor fields = ['color'] class ProductThicknessForm(ModelForm): class Meta: model = ProductThickness fields = ['dimension', 'dimension_unit', 'alias', 'alias_unit'] My views.py: def product_create_view(request): product_form = ProductForm(request.POST, prefix='product_form') color_form = ProductColorForm(request.POST, prefix='color_form') thickness_form = ProductThicknessForm(request.POST, prefix='thickness_form') if product_form.is_valid() and color_form.is_valid() and thickness_form.is_valid(): product = product_form.save() … -
How to store data in JSONField
I have a django model named Fixture class Fixture(models.Model): fixture = models.IntegerField(primary_key=True) league_id = models.ForeignKey('League',null=True, on_delete=models.SET_NULL, to_field="league") teams_h2h = JSONField(null=True) home_team_id = models.IntegerField(null=True) away_team_id = models.IntegerField(null=True) half_time_score = models.CharField(max_length=30,null=True) full_time_score = models.CharField(max_length=30,null=True)) The Fixture object in my app store the data of soccer match between to teams. Fixture model have teams_h2h field which is JSONField and i put there the data of previous soccer matchs between both commands. Here is my question. I have a list of fixture ids which i want to store inside teams_h2h field. In which data format i should put data into it?? List or dictionary?? -
Django upload file using get method
I would like to upload a single file or files at a time using get method. I have already done with the post method and working fine. But for some reason i would like to do the file upload using get method using command line. def home(request): if request.method == 'GET': varValue = request.GET.get('myfile', '') print(varValue) HTML code: <form method="GET" enctype="multipart/form-data"> <input type="file" name="myfile" accept="image/*" multiple> <button type="submit">Upload files</button> I can able to get the varValue as string. But wondering how to get the files using get method. -
Formated field on Django serializer breaks with CSV renderer
In my model I have a datetime field that is being formatted on my serializer with field_1 = serializers.DateTimeField(format="%d/%m/%Y - %H:%m") When a make a GET request to the endpoint /api/v1/myresource to fetch a JSON response it all works great. The problem happens when I try using a new endpoint to retrieve a CSV file. I created a new ViewSet and renderer as follows: class MyresourceCSVRenderer(CSVRenderer): header = ['Field 1', 'Field 2', 'Field 3',] class MyresourceCSVViewSet(viewsets.ModelViewSet): queryset = Myresource.objects.all() http_method_names = ['get'] serializer_class = MyresourceSerializer renderer_classes = (MyresourceCSVRenderer,) def get_queryset(self): myresources = Myresource.objects.all() content = [ { 'Field 1': myresource.field_1, 'Field 2': myresource.field_2, 'Field 3': myresource.field_3, } for myresource in myresources ] return content And when I call /api/v1/csv I get the following error: keyError at /api/v1/csv/ "Got KeyError when attempting to get a value for field `field_1` on serializer `MyresourceSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'field_1'." Please, what am I missing? -
Django UpdateView conflicting with AJAX in FormView
Recently added an AJAX progress bar to a VideoUploadView(FormView) to make the user aware of the progress of the upload. Just realized this has broken the VideoUpdateView but I cannot figure out why. What happens when the "update" button is clicked is the form is rendered with the instance data - ok, looks good. Then after updating a field (e.g. description) and clicking "save" the form is then repopulated with all of the data (as if it were going to give a validation error), including the new changes, though the file fields (video file and thumbnail/image file fields) are now blank. From here it gets a little more strange as if add a video to the video field and click save it will then save the changes of the other fields (description or title) but the video will remain as the first file. What I can take from this is that the AJAX is being called and not submitting the form data for the video/image fields (as if it is using the FormView to handle it all. Then it is redirecting to the FormView page (according to the URL) due to this return render(request, self.template_name, {'form': form}) line. My first … -
How do I create differen domains for creating a new website? (Step by Step)
I am completely new to programming and recently started studying Django after completing Python, I am trying to create a website for self education, so I bought a domain name, I saw at a place where they develop websites, they had one domain with different names like, example.com, sitevm.example.com, sitedev.example.com, sitetest.example.com, siteqa.example.com, I want to do something similar so it helps me get better knowledge of web development, I create a github account and created branches on it, dev, qa, test, master I please need a step by step document or anything that will help me do the same -
Django Converting HTML Form With Views To Work With Forms.py For Phone and Email Validation
I need help converting my previous working code without forms.py to work with forms.py for validation purposes for the phone and email a user types in. If the user types invalid phone and email and tries to submit, they should see "Enter a valid email address" and "Enter a valid phone number (e.g. +12125552368)" The form should not be submitted unless the user types in valid data. All current code: https://dpaste.org/22SV Previous Working Code (without forms.py): Html: https://dpaste.org/sgyo Views.py: https://dpaste.org/vjZZ In my current code, I got the form fields to show up on the webpage but now the form does not submit and the validation errors do not show up on the page when invalid phone and email is typed in as values. On top of that, the form does not submit either when valid data gets passed. Can anyone please help me? -
getting data from api_key in django restframework
I am going to make a small app but I do not know how to do it that's why I need you advice. For example, I have a api_key like that API_KEY='AdsbdmAYugjhnvcvbnRDgfcvbnb' from third party service, let's imagine this computer service group and I need to do is that when I post a computer model number (i.e XS54125) and it should return name, manufacturer, produced date, etc and I should save this details in the database but I do not know how to implement this app. Can you give me idea please? because I have never done this kind of app before. If anything is still unclear please let me know I'll try to explain in more detail. Thank you beforehand! -
How to send dynamic data in email in Django Rest Framework
I am trying to write a function that sends a notification email after a file has been uploaded. My below code works if I hard-code the "send-to" email address. def perform_create(self, serializer): serializer.save(owner=self.request.user) from_email = self.request.user.email send_mail('New Files have been Uploaded', 'New files have been uploaded.', from_email, ['sendto@email.com', ], fail_silently=False) I need to set the "sendto@email.com" dynamically based on the editor_email that is in the serializer. Below is the serializer. class VideoSerializer(serializers.ModelSerializer): projectName = serializers.SerializerMethodField(allow_null=True) editor_email = serializers.EmailField( source='editor.email', required=False) class Meta: model = Video # fields = '__all__' fields = [ 'url', 'handle', 'filename', 'size', 'source', 'uploadId', 'originalPath', 'owner', 'project', 'uploadDate', 'editor', 'projectName', 'editor_email' ] def get_projectName(self, obj): return obj.project.projectName When I check the JSON response in the front end of the app, the value for "editor_email" is what I expect it to be. I am relatively new to Django Rest Framework and there must be something I am missing here. I have spent hours reading through the documentation and trying different things but nothing seems to work. Please, can someone tell me how to set this email based on the serializer? -
django : How to prevent uploaded files from being saved
On django's the Admin page, you can check the uploaded file object. If you check the file, the user can see the path in the browser as / media / ..... /. You can save the uploaded file by accessing with the path. However, even after logging out of the admin page, you can save the file by accessing the path. So what I want is to prevent the file path from being accessed when admin logs out What is the method? -
Django: 2 connections to default DB?
In a long-running management command I'd like to have two connections to the same DB. One connection will hold a transaction to lock a certain row (select for update) and the other connection will record some processing info. If the process crashes, a new run of the management command can use the processing info to skip/simplify some processing steps, hence the need to record it in a different connection. How do I go about creating a 2nd connection in the same thread? My first thought was to add a default2 entry to DATABASES with the same connection info as default and use .using("default2") in one of the queries, but wasn't sure if that would cause issues in Django -
How do I replace boxes with images in css?
Here is the css. .mitch-d3-tree.boxed-tree .node.selected .body-group .body-box { cursor: inherit; pointer-events: none } .mitch-d3-tree.boxed-tree .node .d3plus-textBox, .mitch-d3-tree.boxed-tree .node .body-group .body-box, .mitch-d3-tree.boxed-tree .node .title-group .title-box { cursor: pointer } .mitch-d3-tree.boxed-tree .node .title-group .d3plus-textBox text { transform: translateY(0.15em) } .mitch-d3-tree.circle-tree .node.selected circle { cursor: inherit; pointer-events: none } .mitch-d3-tree.circle-tree .node circle { cursor: pointer; r: 10 } .mitch-d3-tree.circle-tree .node text { transition: 0.3s linear } .mitch-d3-tree.circle-tree .node.childless text { transform: translate(13px, 0.35em); text-anchor: start } .mitch-d3-tree.circle-tree .node.collapsed text, .mitch-d3-tree.circle-tree .node.expanded text { transform: translate(-13px, 0.35em); text-anchor: end } .mitch-d3-tree.circle-tree .node.middle.collapsed text, .mitch-d3-tree.circle-tree .node.middle.expanded text { transform: translate(-13px, -8px) } .mitch-d3-tree.boxed-tree.default .link { fill: none; stroke: #ccc; stroke-width: 2px } .mitch-d3-tree.boxed-tree.default .node.collapsed .body-group .body-box { fill: lightsteelblue } .mitch-d3-tree.boxed-tree.default .node.selected .body-group .body-box { stroke: #00A2A3; stroke-width: 2.5px } .mitch-d3-tree.boxed-tree.default .node .body-group .body-box { stroke: steelblue; fill: white; rx: 6; ry: 6 } .mitch-d3-tree.boxed-tree.default .node .title-group .title-box { stroke: steelblue; fill: #4682B4; rx: 10; ry: 10 } .mitch-d3-tree.boxed-tree.default .node .title-group text { fill: white } .mitch-d3-tree.circle-tree.default .link { fill: none; stroke: #ccc; stroke-width: 2px } .mitch-d3-tree.circle-tree.default .node.collapsed circle { fill: lightsteelblue } .mitch-d3-tree.circle-tree.default .node.selected circle { stroke: #00A2A3; stroke-width: 2.5px } .mitch-d3-tree.circle-tree.default .node circle { fill: #fff; stroke: steelblue; stroke-width: 3px } .mitch-d3-tree.circle-tree.default … -
Stream producer in django channels
Hello I want to stream text data to all members after they are connected in chat/room/group using websocket. I can't understand on what stage I need to initializate my endless loop. I need something like while True: await asyncio.sleep(10) await channel.group.send(my_message) When anybody would be connected to websocket and certain group I need to stream data to all user in that group. It's kind of a producer. But how can I initialize that just once if anyone was connected to the room to avoid duplicating instance? Now I have class FuckingConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = 'test' self.room_group_name = 'test_group' # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() # IT'S WORKING JUST ONCE await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': 'hello', } ) # BUT THIS WORKING JUST FOR CERTAIN USER CONNECTION while True: print('START TO SEND') await asyncio.sleep(10) await self.send(text_data='hello') # I NEED TO SEND MESSAGE IN ENDLESS LOOP TO ALL IN GROUP. IT DOESN'T WORK while True: print('START TO SEND') await asyncio.sleep(10) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': 'hello', } ) What's wrong?