Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Access Remote PostgreSQL Database Server Through VPN
I'm currently working with my office server, when i want to connect to the server, i have to use their VPN. I have installed PostgreSQL database in their server and have succesfully migrate data to database from Django project. But, when i want to remote access from HeidiSQL, it always gives me Connection Timed Out Error eventhough i have already connected to their VPN. I've tried to this code below /var/lib/pgsql/14/data/pg_hba.conf host all all 0.0.0.0/0 md5 host all all ::/0 md5 /var/lib/pgsql/14/data/postgresql.conf listen_addresses = '*' i have tried to refresh everytime i change files and see if i'm in the correct port but it still gives me Connection Timed Out Error this is the full error message could not connect to server: Connection Timed out (0x0000274C/10060). Is the server running on host "xxx.xxx.xxx.xxx" and accepting TCP/IP connections on port 5432 ? NOTES OS : CentOS 8 DB : PostgreSQL 14 -
DRF - Authentication credentials were not provided. (Djoser + SimpleJWT)
I am currently getting an error when making a request to /users/me to receive back my user's data. From what I have been reading, I am not sending the token, though I'm not sure how to store it when I receive it from the jwt/create endpoint when signing in. This is from my Auth-Test/nuxt-auth/pages/index.vue file: onMounted(async () => { const cookie = useCookie('jwt'); console.log('COOKIE: ' + JSON.stringify(cookie)); const response = await fetch('http://localhost:8000/api/auth/users/me/', { headers: { 'Content-Type': 'application/json', 'Authorization': `JWT ${JSON.stringify(cookie)}`, }, credentials: 'include' }) const content = await response.json(); console.log(content); }) and this is from my Auth-Test/nuxt-auth/pages/login.vue const router = useRouter(); async function submit() { console.log(JSON.stringify({ email: user.email, password: user.password })) await fetch('http://localhost:8000/api/auth/jwt/create/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ email: user.email, password: user.password }) }); await router.push({ path: '/' }); } Could anyone help me realize what I might be (am) doing wrong? I can't seem to figure out it myself through the use of documentation after a lot of reading. In case you might need to access the other files (front and back end), here is the Github repo. -
how to call form method from template for dynamic form in django
I have a model that one of it's field is CharField, use to store a JSON (list of dictionary) called 'schema' SCHEMA_DATA_TYPES=( (1, 'Integer'), (2, 'String'), (3, 'Date'), ) class MailTemplate(models.Model): name = models.CharField(max_length=20) tfile = models.FileField(upload_to='uploads/mailtemplate', null=True, blank=True) schema = models.CharField(max_length=256, blank=True, null=True, editable=False) def __str__(self) -> str: return self.name Currently, it only have one record and the 'schema' value is : [{"name": "date", "label": null, "type": 2, "format": ""}, {"name": "invoiceNumber", "label": null, "type": 2, "format": ""}, {"name": "company", "label": null, "type": 2, "format": ""}, {"name": "total", "label": null, "type": 2, "format": ""}, {"name": "items", "label": null, "type": 2, "format": ""}] I need to build a dynamic form that have additional fields contructed from that 'schema' field. first try I use htmx. The form is showed prefectly, but additional fields could read by forms.py as suggested by SO user @vinkomlacic at my post How to read additional data posted by form in django forms.py , I serach for doc on how to play with init of form to do it. I found https://www.caktusgroup.com/blog/2018/05/07/creating-dynamic-forms-django/ looks informative. so my admin.py is class MailTemplateAdmin(admin.ModelAdmin): change_form_template = 'mailtemplate_form.html' form = MailTemplateForm admin.site.register(MailTemplate,MailTemplateAdmin) and mailtemplate_form.html is {% extends "admin/change_form.html" %} {% block after_field_sets … -
Refrehing the Django model after save and 5 second sleep get me old state, what's wrong?
I was able to save the data to a Django model without any errors, but data not reflected in db. But after a sleep time I was able to save the data again with same method. What might be causing this ? I suspect use of the Google API, but was able to print the data before performing the save operation. def update_channel(): client = Client.objects.get(name="name") print(f"Existing channel: {data['id']}") # 123 # fetch channel data from google api data = google_drive.subscribe_new_channel() client.channel_id = data["id"] client.channel_resource_id = data["resourceId"] client.save() client.refresh_from_db() print(f"New channel: {data['id']}") # 456 print(f"New channel in db: {client.channel_id}") # 456 time.sleep(5) client.refresh_from_db() print(f"channel in db: {client.changes_channel_id}") # 123 -
add image from model in background:url()
hello i have in my model images and i store it inside media and i want to show image in html code using background:url() so , what i must write in background:url() to show image for each post my code in models : image = models.ImageField(upload_to='images/',null=True, blank=True) in css in html file : background: black url(what i must write here) no-repeat center center; in views : def mods_posts(request,slug): mods_posts = get_object_or_404(Mods, slug=slug) context = {'mods_posts':mods_posts} return render(request,'mods/mods_posts_page.html', { 'mods_posts': mods_posts }) so i need preview images in html page for each post -
How to deploy multiple django apps on apache in Windows?
I want to deploy multiple django apps on apache on Windows but only know how to deploy one. Overriding the localhost of the Wamp Server I can deploy the app without problem but I need to deploy more and don't know how. I've sehen virtual hosts and think are good but don't know how to configurate them. Anyone know how can I do this? Thanks in advance. -
django rest framework is removing "+" from datetimes
I have a simple django get view: @api_view(["GET"]) @permission_classes([IsAuthenticated]) def test_endpoint(request): print(request) print(request.GET) The result of this - <rest_framework.request.Request: GET '/api/test_endpoint?start=1969-12-31T19:00:00+05:00&end=2023-01-16T21:22:52-05:00'> <QueryDict: {'start': ['1969-12-31T19:00:00 05:00'], 'end': ['2023-01-16T21:22:52-05:00']}> If you notice start for some reason is cleansing out the + in the datetime. Thus causing an incorrectly formatted datetime object. I have no interest in changing my formatting, but rather fixing why django rest framework is removing the +. You can clearly see in the actual GET request that the + is properly in the string. Any ideas on how to fix this so start value would be '1969-12-31T19:00:00+05:00' instead of '1969-12-31T19:00:00 05:00' without "fixing" it after the fact? (I want the request.GET object to be correct, I don't want to fix the values after retrieving them from request.GET) -
Django: can't delete item in Model inherting django-mptt
in models.py, i've the following code: import uuidfrom django.db import modelsfrom django.db.models import Qfrom mptt.models import MPTTModel, TreeForeignKey from company.models import Account class Plan(MPTTModel): id = models.UUIDField(primary_key=True, unique=True, editable=False, default=uuid.uuid4) coding = models.CharField(max_length=50) title = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') entreprise = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.parent is not None: coding = str(self.coding) parent = str(self.parent) if not coding.startswith(parent): raise ValueError('Le code ne correspond pas au code parent {}'.format(parent)) if len(coding) == len(parent): raise ValueError("Le code ne peut pas être identique au code parent {}".format(parent)) if self.parent.get_level() == 0 and self.entreprise is not None: raise ValueError("Vous ne pouvez pas associer une entreprise à ce niveau") else: if self.entreprise is not None: raise ValueError("Vous ne pouvez pas associer une entreprise à ce niveau") class MPTTMeta: order_insertion_by = ['coding'] and in my views.py, i've this code: @api_view(['DELETE']) def delete_plan(request): try: id = request.data['id'] entreprise = request.data\['entreprise'\] plan = Plan.objects.get(id=id, entreprise=entreprise) context = { 'message': 'Le compte {} - {} a été supprimé de votre plan comptable avec succès'.format(plan.coding, plan.title) } plan.delete() return Response(context, status=status.HTTP_200_OK) except Plan.DoesNotExist as e: context = { 'message': "Ce compte n'existe pas dans votre plan comptable" } return Response(context, … -
Django: Retrieving tweets followed by current user
I currently have the following Models set up User Model class User(AbstractUser): pass Follower Model class Follower(models.Model): # user is following userFollowing user = models.IntegerField() userFollowing = models.IntegerField() Tweet Model class Tweet(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="tweets") content = models.TextField() date = models.DateTimeField(auto_now_add=True) likes = models.IntegerField(default=0) I want to get a QuerySet of Tweets consisting of Tweets from Users that the current user follows. I managed to get the following but I'm not sure if there's a better way to write the Query # Retrieve all users followed by current user usersFollowedByCurrentUser = Follower.objects.all().filter(user=request.user.id) # Retrieve all Tweets tweets = Tweet.objects.all().filter(user_id__in=Subquery(usersFollowedByCurrentUser.values('userFollowing'))) Appreciate any feedback/advice -
Comment Mixin for Django. Why is CommentPost defined like this?
I am a beginner in Django, and I was reading WS Vincent's Django for beginners. In the second to last chapter, he writes the following code. He's creating a view that allows for comments that can handle GET and POST requests without mixing FormMixin and his created ArticleDetailView. I understand all of that, but what I don't understand is why it was constructed like this? Can someone explain what self.object and self.get_object are in this example? Also, why do we save twice in the second method? Thanks!: def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) def form_valid(self, form): comment = form.save(commit=False) comment.article = self.object comment.save() return super().form_valid(form) def get_success_url(self): article = self.get_object() return reverse("article_detail", kwargs={"pk": article.pk}) -
The model has two identical many-to-many relations through the intermediate model
from django.db import models class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, through='Membership', through_fields=('group', 'person'), ) class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) inviter = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="membership_invites", ) invite_reason = models.CharField(max_length=64) python manage.py makemigrations app ERRORS: The model has two identical many-to-many relations through the intermediate model -
Django - Adding a 2nd form to a page dynamically
I'm looking for guidance on creating a dynamic form in Django that changes depending on which participants are in a meeting. The background is as follows: The app is used to track meeting scores across several teams, each with 4-8 members. Over the course of a few days a team may have 6 meetings. For each meeting the Team will elect 1 or 2 members to be meeting Participants. Each meeting requires the team to put forward members such that over the course of the training all team members have participated in one or more meetings. For each meeting all other team members are "Observers". The challenge I'm facing is how to dynamically insert a form or form fields for each of the Observers given that the number of observers may be anything from none to 6. The idea is to allow Observers to "rate" the meeting and record this result in the Observer model. The ScoreCreate view correctly sets the 1st participant and populates the "Other Participant" dropdown with all other team members. HTMX in the template passes the 1st and if selected "other participant" to the observers function which is then able to sort out who the observers … -
How to create a "CHOICES" filter field from a model based on unique values from another model?
Good day! I would be very grateful for any help. I have two related tables - Django models. The field "nomer_kotl = models.TextField()" has an association with another model. And as "choices = CHOICES" I would like to have "unique" values from the "Nomerkotelnoy(models.Model)" model. How can I make the "choices = CHOICES" of the model (EmployeeModel(models.Model)) get the values from the field "nomer_kotl = models.TextField()" of the model (Nomerkotelnoy(models.Model)) ? When creating a form for selecting data from a model table for display in an application on a site. - I think how can I make the form have a choice in the form of "select dropdown" - the choice of only one value. class Nomerkotelnoy(models.Model): nomer_id = models.IntegerField(primary_key=True) nomer_kotl = models.TextField() def __str__(self): return self.nomer_kotl CHOICES = ( ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5"), ("6", "6"), ("7", "7"), ("8", "8"), ) class EmployeeModel(models.Model): empid = models.IntegerField(primary_key=True) empname = models.CharField(max_length=50) salary = models.IntegerField() joindate = models.DateField() nomer_kotl = models.ForeignKey(Nomerkotelnoy, default=1, on_delete=models.CASCADE, choices = CHOICES) class Meta: db_table = "employee" -
How to reorder the form elements when rendering in template in Django
When rendering a form how do I reorder the form elements in the template? In the above form how do I change the position of the 'Sort by' element. If suppose I want to position it to the top right, how will I do it? forms.py class RoomsForm(forms.Form): numbers = forms.CharField(validators=[int_list_validator()], required=False, max_length=4000, widget=forms.TextInput(attrs={'class': 'unbold-form'})) ROOM_CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) categories = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple(attrs={'class': 'unbold-form'}), choices=ROOM_CATEGORIES, ) ROOM_CAPACITIES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacities = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple(attrs={'class': 'unbold-form'}), choices=ROOM_CAPACITIES, ) advance = forms.IntegerField( required=False, widget=forms.NumberInput(attrs={'class': 'unbold-form'}) ) SORT = ( ('number', 'Numbers: Ascending'), ('-number', 'Numbers: Descending'), ('capacity', 'Capacities: Ascending'), ('-capacity', 'Capacities: Descending'), ('advance', 'Advance: Ascending'), ('-advance', 'Advance: Descending'), ) sort_by = forms.ChoiceField( required=False, widget=forms.Select(attrs={'class': 'unbold-form'}), choices=SORT, ) HTML Template <h2>Search</h2> <form method="POST" id="bold-form"> {% csrf_token %} {{ form.as_p }} <input type="submit" class= "submit submit-right" value="Search" /> </form> -
Best GUI to run python [closed]
I am building an object detection tool using the Yolo algorithm(Which contains many dependencies). my python script works successfully. My question is, what would be the best GUI to implement with python? I am trying to build a commercial app that anyone on a windows computer can run without having to download python and all its dependencies. Here are some of the ideas that come to mind. Build a C# application form application and combine it with python with either ironpython or compile the python app into an exe and then fetch its output and display it on C# form. I can maybe create a Django web application. If you would have any suggestions from experience, I would be extremely grateful. -
django custom users permissions
i working in big project (first time for me ) for schools chain what is the best setup for Custom model for permission to get different type of permissions i need :- CEO permission >> permissions for all schools and department school manager >> permission for his school only teacher >> permissions for his department only student >> permissions limited permissions for his courses allowed only in his school the privilege tree for me is complected ,, so i cant figure what should i implement to don't waste a lot of time -
How to autoescape form value in UpdateView in Django
I have a form where I use TinyMCE on textareas because I need my users have the option to style the text they enter. It works fine and saves the html codes to the model. I use the safe mode to show the values in the way the users entered it and it works fine but I have an UpdateView where the user can edit what was entered. My problem is that if the user uses the UpdateView to change whet he entered he see the html code in the UpdateView like below and I have no idea how to solve this. <h2>Text</h2> <b><p>More text</p></b> Can I autoescape off the form? I tried these methods but not worked: <div class="container"> <h2>Edit report</h2> <h5 class="my-3">You can edit your report here:</h5> {% autoescape off %} {{ form.as_p|safe }} <!-- tried it separately --> {% end autoescape %} <button type="submit" class="btn btn-warning my-3">Submit changes</button> -
How we can use model objects in ModelSerializer?
I have to create an endpoint to make a customer subscribes to a chef. The subscription model has two FK fields chef and customer. I created this serializer: class SubscriptionSerializer(serializers.ModelSerializer): chef = serializers.SerializerMethodField("get_chef") customer = serializers.SerializerMethodField("get_customer") class Meta: model = Subscription fields = [ "id", "chef", "customer", ] def get_chef(self, *args): return Chef.objects.get(pk=self.context.get("chef")) def get_customer(self, *args): return User.objects.get(pk=self.context.get("customer")) I want to have one endpoint like this: customer/chef/<int:chef_id>/subscribe So in view.py I used ModelViewSet: class CustomerSubscribeChefView(viewsets.ModelViewSet): permission_classes = (permissions.IsAuthenticated,) serializer_class = SubscriptionSerializer def get_serializer_context(self): context = super(CustomerSubscribeChefView, self).get_serializer_context() context.update({"chef": self.kwargs['chef_id']}) context.update({"customer": self.request.user.id}) return context def get_queryset(self): return self.request.user.subscription_set def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response( {"msg": "Chef is subscribed!"}, status=status.HTTP_201_CREATED ) def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response({"msg": "Chef is unsubscribed!"}, status=status.HTTP_200_OK) when I try to send a post request I got this error: django.db.utils.IntegrityError: NOT NULL constraint failed: core subscription. chef _id I've tried to use my custom serializer so I've updated SubscriptionSerializer to be like this: class SubscriptionSerializer(serializers.ModelSerializer): chef = ChefListSerializer customer = CustomerSerializer class Meta: model = Subscription fields = [ "id", "chef", "customer", ] But I don't know how to serializer chef and customer objects. What is the … -
Django return class attribute based on object status in database
I am new to django and trying to learn. Looking to see if there is a better way to produce the result wanted. See my example below: application_list.html - Table Data <td><span class="badge {% if app.application_status_id == 1 %} bg-secondary {% elif app.application_status_id == 2 %} bg-success ">{{ app.application_status }} </span> </td> See here I am setting the class based on the value of the application status id from the database. Instead of having multiple if statements, is it possible to place this code elsewhere to process and return the class attribute back to line? I have tried looking at views.py for the application, but unable to determine how this works. My thoughts were to create a function to return a context value for application_list. application/views.py def application_list(request): """List of all applications""" template = 'application/application_list.html' applications = Application.objects.all() context = { 'applications': applications, } return render(request, template, context) -
Android app written in kotlin with the volley library fails to call my backend, which was written in python with django
so as the post says, i'm making an app, for which i have a server/rest api written with the django framework. When i try to call the api using volley, i fail to get any response, and i don't see it show up on my server's dashboard The server is running on my local machine, and the app is running on an emulator, since i'm using android studio i'd like to send a request and display the response in a textview on the app, for now thats all i need to continue onto the next part What ends up happening instead is that it seems to not even hit my server, the app displays the text i set for if the request fails, adn it doesn't show up on the dashboard of my server -
How to implement a model like "playlist", which is in relation with multiple models like "track"
I have multiple independent video models (let's call them A, B, and C) with different features and I want to design an ordered playlist model to be able to add these videos to the playlist in a desired order. I already studied the [django documentation many_to_many example][1], but, I don't think it is a good idea to implement such a model with multiple many_to_many relationships. [1]: https://docs.djangoproject.com/en/4.1/topics/db/models/#intermediary-manytomany:~:text=something%20like%20this%3A-,from%20django.db%20import%20models%0A%0Aclass%20Person(models.Model,()%0A%20%20%20%20invite_reason%20%3D%20models.CharField(max_length%3D64),-When%20you%20set -
ModuleNotFoundError: No module named 'tutorial'
I am trying to learn how to set up a Django web server using an AWS Ubuntu Machine, I have solved a few of my problems but now I am getting hit with the ModuleNotFoundError: No module named 'tutorial' and I am also getting the 500 internal server error. Here is what I think the necessary code is: error.log GNU nano 6.2 /home/ubuntu/django-project/site/logs/error.log [Mon Jan 16 19:35:18.750368 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] mod_wsgi (pid=10330): Failed to exec Python script file '/home/ubuntu/djang> [Mon Jan 16 19:35:18.750441 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] mod_wsgi (pid=10330): Exception occurred processing WSGI script '/home/ubun> [Mon Jan 16 19:35:18.750979 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] Traceback (most recent call last): [Mon Jan 16 19:35:18.751031 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] File "/home/ubuntu/django-project/src/tutorial/wsgi.py", line 16, in <mod> [Mon Jan 16 19:35:18.751037 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] application = get_wsgi_application() [Mon Jan 16 19:35:18.751043 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] File "/home/ubuntu/django-project/venv/lib/python3.10/site-packages/djang> [Mon Jan 16 19:35:18.751048 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] django.setup(set_prefix=False) [Mon Jan 16 19:35:18.751053 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] File "/home/ubuntu/django-project/venv/lib/python3.10/site-packages/djang> [Mon Jan 16 19:35:18.751058 2023] [wsgi:error] [pid 10330:tid 139960159290944] [remote 136.41.64.54:40330] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) … -
Why is my Django template not displaying on my webpage?
I have two classes in my models, two defs in views and one template in one app. Just one of the functions doesn't work properly. Everything else works fine. I double checked everything but didn't find the issue. Below the code: Models from django.db import models class BildTextMarkt(models.Model): fotomarkt = models.ImageField(upload_to='images/') text = models.TextField(blank=True, max_length= 512) views def bildtextmarkt(request): all_maerkte = BildTextMarkt.objects.all() context = {'my_maerkte':all_maerkte} return render(request, 'maerkte/maerkte.html', context) templates {% for maerkte2 in my_maerkte %} <div class="bild">{{ maerkte2.fotomarkt }}</div> <div>{{ maerkte2.text }} </div> {% endfor %} Thank you for any hints. -
How to automatically set the value of a many to many field in Django
I have a blogPost model which has authors, reviewers and tags. The three fields are part of a ManyToMany relantionship. But I want to set the value of each field in programatically way. Rigth now I can do this: blog.authors.set(qs) This works, but this mean that I have to repeat the same line of code for each field. I was thinking something like this def set_values(blog,field,new_values): setattr(blog, field, new_values) that didn't work and it raises and exception telling me to use the set method. But is there a way to implement something like this? -
Why does my Django application using websocket not work when deployed?
So I created an online chat site using Django and Javascript and I'm having trouble making it work when I deploy it on a live server. It works perfectly fine locally though. Whenever I try to send a message on the chat on the deployed server I get a "Firefox can’t establish a connection to the server at ws://url". I think this is a websocket issue. My asgi.py file is as follows : import os import rooms.routing from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webchat.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( rooms.routing.websocket_urlpatterns ) ) }) And my consumers.py file : import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import sync_to_async from django.contrib.auth.models import User from .models import Room, Message class Consumer(AsyncWebsocketConsumer): async def connect(self): self.room_name=self.scope['url_route']['kwargs']['room_name'] self.room_group_name='chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): data=json.loads(text_data) msg=data['message'] username=data['username'] room=data['room'] if msg.isspace()==False and msg != "" : #On ne veut pas stocker ou envoyer les messages vides ou ne contenant que des espaces await self.storeMsg(msg,username,room) await self.channel_layer.group_send( self.room_group_name, { 'type': 'chatmsg', 'message': msg, 'username':username, 'room':room, } ) async def …