Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can you add a Browsable API into an ASP.NET application?
The Django web framework has a Browsable API and I would like to implement something similar in my ASP.NET (with ReactJS) application. Essentially, suppose that there's an API endpoint called api/test; I would like to be able to navigate to https://.../api/test in a web browser and be presented with a web page (React component) that contains what api/test normally returns but in a better, human-readable format like Django does. But when accessed as an API, it returns the content without the surrounding HTML page. The simple controller would look like: [ApiController] [Route("api/[controller]")] public class TestController : ControllerBase { [HttpGet] [Produces("text/json")] public IList<string> Get() { return new string[] { "hello", "world" }; } } It seems that something similar to Content Negotiation would work. So, I would either have to implement a custom formatter (which I'm not sure is the right approach) or make a middleware of my own. Does this sort of thing already exist somehow? Any suggestions on how to implement it if it doesn't already exist? Thanks in advance! -
how to display products from every seller and make it changing every time page reloading?
The default displaying in django is for the latest product first . how can I change the viewing way ? my view.py coding @login_required() def products(request): f = ForSaleProductFilter(request.GET, queryset=Product.objects.filter(status=ProductStatus.LISTED).order_by('-pub_date')) paginator = Paginator(f.qs, NB_PER_PAGE) page = request.GET.get('page') pproducts = paginator.get_page(page) request.session['products_filters'] = request.GET return render(request, 'products/products.html', {'filter': f, 'pproducts': pproducts}) sale = PorductSale() sale.product = product sale.buyer = buyer sale.seller = seller -
Django IntegrerField +1 by viewing page
I need to make object view counter, how i can make +1 to django models.IntegerField by viewing page with using of DetailView -
Typeerror in Django-Channels
I am trying to send data from client-side in my django app but I keep getting this error and the socket disconnects. I am lost to why this is so, This is the error: Exception inside application: receive() got an unexpected keyword argument 'text_data' Traceback (most recent call last): File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/sessions.py", line 254, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/routing.py", line 160, in __call__ send, File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/generic/websocket.py", line 196, in websocket_receive await self.receive(text_data=message["text"]) TypeError: receive() got an unexpected keyword argument 'text_data' WebSocket DISCONNECT /ws/orders/ [127.0.0.1:49984] This is the consumers.py: import json from .models import Order from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer class WSConsumer(AsyncWebsocketConsumer): @database_sync_to_async … -
Django rest framework do I need to close file before the response
I have an endpoint returning a FileResponse. When I use a code like the following I get an error 'read of closed file' The code looks like this: @action(detail=True, methods=['get'], url_path='download') def get_file(self, request, pk=None): instance = self.get_object() fa = getattr(instance, file_location) if fa: with open(fa.path, 'rb') as f: response = FileResponse(f, as_attachment=True) return response else: raise FileNotFound when I remove the with-block it works. Do I need the with block? -
How to display an avatar?
I made a function that generates avatars for users when they create a profile: users/models.py def random_image(): directory = os.path.join(settings.BASE_DIR, 'media') files = os.listdir(directory) images = [file for file in files if os.path.isfile(os.path.join(directory, file))] rand = choice(images) return rand class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar_new = models.ImageField (default=random_image) def __str__(self): return f'{self.user.username} Profile' For changing avatar i am using django-avatar There is a line like this (settings): DEFAULT_URL = ("avatar/img/default.jpg") I would like to display not a static image (default.jpg), but the result of the random function, which assigned the user an avatar. How can I make sure that the default url contains not a static image, but the result of the field avatar_new? Tried itDEFAULT_URL = Profile.avatar_new error. Need help pls -
GithubOauth gives "non_field_errors": [ "Incorrect value" ] after posting code to GithubLogin view
I am using GitHub OAuth to login to my django_RESTFRAMEWORK api. with front end React js. Oauth works fine when i try to login with my github account. but gives "non_field_errors": [ "Incorrect value" ] i am very certain that code is correct. and the fact this works for my github account. please help http://localhost:8000/accounts/dj-rest-auth/github/?code=***************** -
Adding Websockets to Django server deployed on Azure Appservice
I have a Django application which starts a server using the websockets https://websockets.readthedocs.io/en/stable/index.html library for Python. The manage.py file looks like this: import os import sys import asyncio import threading if __name__ == '__main__': os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', 'UPH_Chart_Re.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc try: from WebsocketClass import StartServer x = threading.Thread(group=None, target=StartServer, name="Websocket Thread") x.daemon=True x.start() except ImportError as exce: raise ImportError("Importing WebsocketsClass failed") from exce execute_from_command_line(sys.argv) The StartServer function starts a websocket server using asyncio: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) start_server = websockets.serve(Receive, "localhost", 5001) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() The Django webpages and websocket server work perfectly on my local machine. The problem I'm running into now is that when deploying to Azure Web App Service, I don't seem to be able to access the sockets. My Web App Service has Websockets set to enabled, and I get no errors on my deployment. However, I can't seem to connect to the websocket at all. I have tried setting the port to 443, which is considered a forbidden port since … -
Django and chartjs using json (doesn't show chart)
I'm trying to display a chart in Django with data from database using JSON. When I go to /distancechart I see my data printed. But when it comes to chart I get blank screen, nothing shows. I was using some tutorials from internet and I have no idea what is wrong here... views.py fragment def distancechart(request): labels = [] data = [] queryset = Distance.objects.values('day', 'distance') for entry in queryset: labels.append(entry['day']) data.append(entry['distance']) return JsonResponse(data={ 'labels': labels, 'data': data, }) distance.html {% extends 'index.html' %} {% block content %} <canvas id="distancechart" width="1000" height="400"></canvas> <script> $.get('{% url "distancechart" %}', function(data) { var ctx = $("#distancechart").get(0).getContext("2d"); new Chart(ctx, { type: 'bar', data: { labels: data.labels, datasets: [{ label: 'Distance', data: data.data, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); }); </script> {% endblock %} -
Django checkbox form does not update
I have form where I want to let users add their skills by using check boxes. I can get the check boxes to render in the template but I can't get it to update if the user select a check box, nor am I able to let it show current active skill. I am a bit confused what's wrong, any ideas? My models.py file class Skills(models.Model): math = models.BooleanField(default=None) language = models.BooleanField(default=None) driving = models.BooleanField(default=None) account = models.ForeignKey( Account, on_delete=models.CASCADE, default=None, null=False ) My forms.py file class SkillsForm(forms.ModelForm): SKILLS = ( (True, 'math'), (True, 'language'), (True, 'driving'), ) skills = forms.MultipleChoiceField(choices=SKILLS, widget=forms.CheckboxSelectMultiple) def clean_skills(self): print(self.cleaned_data["skills"], self.cleaned_data["skills"][0]) return self.cleaned_data["skills"][0] class Meta: model = Skills fields = ( 'math', 'language', 'driving', ) My views.py file @login_required def userSkills(request): if request.user.is_authenticated: if request.method == "POST": skills = SkillsForm(request.POST, instance=request.user) if skills.is_valid(): skills.save() return HttpResponseRedirect(request.path_info) else: skills = SkillsForm(instance=request.user) return render(request, 'page/userprofile.html', { "skills": skills, }) My template file <ul class="list-group"> <form method="POST" action=""> {% csrf_token %} <li class="list-group-item"> <div class="custom-control custom-checkbox"> <label>math</label> {{ skills.math }} </div> </li> <li class="list-group-item"> <div class="custom-control custom-checkbox"> <label>language</label> {{ skills.language }} </div> </li> <li class="list-group-item"> <div class="custom-control custom-checkbox"> <label>driving</label> {{ skills.driving }} </div> </li> <input class="btn btn-primary" type="submit" … -
Django Inheritance one model choice field from another
I have couple tables in DB. class VehicleBrand(models.Model): name = models.CharField(max_length=128, unique=True) class VehicleModel(models.Model): name = models.CharField(max_length=128, unique=True) class Vehicle(models.Model): link = models.CharField(max_length=256, unique=True, blank=False, null=False) model = models.ForeignKey(VehicleModel, on_delete=models.PROTECT) brand = models.ForeignKey(VehicleBrand, on_delete=models.PROTECT) I tried to crate form with two ModelChoiceField depending one from another. I have first Field (just all items from VehicleBrand) # first field brand = forms.ModelChoiceField(queryset=VehicleBrand.objects.all()) Next I want to get qs of models depending of first choice: # get brand brand = VehicleBrand.oblects.get(name=brand) # get qs for all items with chosen brand qs = Vehicle.objects.filter(brand=brand) # I want get second field with choices as list of distinct models values model = qs.values('model').distinct() For example I have next table 1 link1 Toyota Corolla 2 link2 Toyota Camry 3 link3 Nissan Altima 4 link4 Nissan Almera If I choose 'Toyota' I wanna have only models for it: 'Corolla' and 'Camry'. I wanna get it in one page dinamically depending of first(brand) field. Is it possible? Could someone give me advise please? Thanks. -
How to to create a Dynamic variable and Value in Django Admin
Please, I am completely new to this approach but I believed it is possible. I want to dynamically create something like this image in Django admin and render the result for other users to see. -
Manytomany into notifications does not work
I don't really understand why when I save my model. The notification does not save the ManyToMany relationship, exemple. Do you have any idea? def notifs_rerservationorder(sender, instance, *args, **kwargs): rerservationorder = instance table_nb = rerservationorder.exemple.all() notify = Notification(rerservationorder=rerservationorder, notification_type=9) notify.save() notify.exemple.add(*table_nb) notify.save() post_save.connect(notifs_rerservationorder, sender=RerservationOrder class Notification(models.Model): NOTIFICATION_TYPES = ... ... exemple = models.ManyToManyField('post.Exemple',blank=True, null=True, related_name='notifs_exemple') ... ) -
Python Flask-WTF Forms not showing up when running server, only base html not child html file, how can i fix it?
tried to create a signup form, here is my file tree right now: -mysite\ --app.py --forms.py --form.html --templates\ ----index.html so im pretty sure the structure is fine, however when i use terminal in PyCharm and run command, flask run, server starts without errors, however my forms.py is not running just index.html here is what my scripts look like from forms import RegistrationForm app = Flask(__name__, instance_relative_config=False) app.testing = True app.config['SECRET_KEY'] = 'any secret string' @app.route('/', methods=('GET', 'POST')) def registration(): form = RegistrationForm() if form.validate_on_submit(): return redirect(url_for('success')) return render_template( 'index.html', form=form ) so when i click on the link in the terminal from pycharm i get index.html boots up, however, the script from form.html does not work.. i have in form.html: {% extends 'index.html' %} ........... {% endblock %} obviously i have some script between the blocks .. not too sure what i am doin wrong. parent html = index.html child html = form.html -
Items after reload showing in different order Django
Hi I've made django webstore and there is small yet annoying bug. If I add click on add quantity in my cart items after reload are in different order note this only happens when user is not authenticated here are short gifs to help you understand my probelm not working correctly when user is auth and working correctly on guest user cart.js var updateBtn =document.getElementsByClassName("update-cart") for (i = 0; i < updateBtn.length; i++){ updateBtn[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action if (user === "AnonymousUser"){ addCookieItem(productId,action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId,action){ if(action == "add"){ if(cart[productId] === undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == "remove" || action =="delete"){ cart[productId]['quantity'] -= 1 if(cart[productId]['quantity'] <= 0){ delete cart[productId] } } document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/" history.go(0) } function updateUserOrder(productId, action){ var url = 'http://127.0.0.1:8000/updateItem' fetch(url, { method:'POST', headers:{ 'Content-Type': 'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log(data) history.go(0) }) } html <div class="row no-gutters"> <div class="col-4"> <div class="controlQtyCart"> <i data-product="{{ x.product.id }}" data-action="remove" class="fas fa-minus update-cart updatePointer"></i> </div> </div> <div class="col-4"> <div class="controlQtyCart"> &nbsp;{{x.quantity}} </div> </div> <div class="col-4"> <div class="controlQtyCart"> <i data-product="{{ x.product.id }}" … -
Django: Parent object has no attribute children_set
I have these two models: class Periodo(models.Model): # id usato per identificare i documenti # periodo rilevato in fattura data_i_p = models.DateField('data inizio', blank=True) data_f_p = models.DateField('data fine ', blank=True) mc_p = models.DecimalField('mc', max_digits=7, decimal_places=0, blank=True, default=0) idfatt = models.ForeignKey(FattAqp, verbose_name="fattura AQP", on_delete=models.CASCADE, related_name='periodo_rel') descr = models.CharField('descrizione', max_length=50) objects = models.Manager() class Meta: verbose_name = 'Periodo' class DettFAqp(models.Model): imponibile = models.DecimalField('imponibile', max_digits=8, decimal_places=2, default=0) iva = models.DecimalField('%IVA', max_digits=4, decimal_places=2, default=10) mc = models.DecimalField('qtà (gg/mc)', max_digits=7, decimal_places=0, blank=True, default=0) voce = models.ForeignKey(VoceAqp, verbose_name="metodo di ripart.", on_delete=models.CASCADE) periodo = models.ForeignKey(Periodo, verbose_name="Periodo in fattura", on_delete=models.CASCADE, related_name='dettfaqp', help_text=u"periodo cui la voce appartiene") rigo = models.DecimalField('rigo', max_digits=2, decimal_places=0, default=0, help_text=u"rigo di fattura") when I try to access the set related to the parent I get the following error: >>> p=Periodo.objects.get(pk=2) >>> p <Periodo: consumo accertato in 344 gg> >>> p.dettfaqp_set.all() Traceback (most recent call last): File "<input>", line 1, in <module> p.dettfaqp_set.all() AttributeError: 'Periodo' object has no attribute 'dettfaqp_set' Any suggestion? Many tankds in advance. -
Nextcloud as User Master for other web apps (i.e. django based)
I have a Nextcloud instance where all potential users have an account. I would like to set up an Open Source Doodle (Bitpoll) that is django based, as I don't like the nextcloud poll app. For security reasons I would like to limit the Doodle app to users of my nextcloud. Also I don't want them to enter a password using the doodle app (so single sign on is required). I imagine a similar user user flow as the Login in with Github button that can be used to also create user accounts. The doodle app supports LDAP, so does nextcloud. There are django modules for OAuth as well as for the nextcloud. I have no LDAP experience at all and only very little OAuth experience. With which Nextcloud Settings / Apps and which Django Apps (and an idea of the settings) can I realize the explained scenario? To be more precise: Do I need to use LDAP at all? Or can I configure OAuth in a way that all users that come from nextcloud.mydomain.org generate a new account in the app? What are the correct OAuth terms for my nextcloud istance and for the doodle app in this scenario? … -
Images not showing after about 1 day of upload with editors (ckeditor)
I host my files on Digitalocean space. Almost everything works fine. The only issue is that I am unable to see images uploaded with editors for instance ckeditor after about a day of upload. This does show at first but fail to display by second day. When I tried to preview the image to ascertain what is wrong, I encountered this kind of error: <Error> <Code>AccessDenied</Code> <RequestId>txgjk006000a4ca-47ce82d-nyc3bkkhv**""**</RequestId> <HostId>47ce82d-***********zg02</HostId> </Error> Note: I replaced some things with ****. I've tried what I could do eg changing permission but all to no avail. Other images uploaded through IMG tags are displaying properly. The app is a django app. The site is medsjoin.com The concerned URLs are: https://www.medsjoin.com/post/101-are-covid19-vaccines-safe-for-hiv-patients/ https://www.medsjoin.com/forum/topic/14/covid19-update-in-nigeria/#c13 Kindly help. -
Nested Serializer in case of multiple children models
Given the following models class Parent(models.Model) type = models.CharField() # 1 = Child1, 2 = Child2 class Child1(models.Model) parent = models.ForeignKey(Parent, related_name='child1') class Child2(models.Model) parent = models.ForeignKey(Parent, related_name='child2') How do I go about setting up a Parent serializer which also serializes its children appropriately class ParentSerializer(serializers.ModelSerializer): child = ... # SomeSerializer depending on the `type` field on the parent class Meta: model = Parent fields = '__all__' -
How to serialize ChoiceFields in Django Rest Framework?
First time Python user here, coming from Javascript world. I'm able to retrieve my Model serialized to JSON from Django API and display it on the frontend written in React. But now I just added one more field priority to the Model that has multiple choices and I struggle to get these choices to the frontend (I want to display them in a dropdown and update REST API). Migration was successful and I can select choices from the back end but on the frontend I just get the default value set from migrations. Here is my code right now: models.py class Todo(models.Model): title = models.CharField(max_length=120) description = models.TextField() completed = models.BooleanField(default=False) priority_choices = [ ('High', 'High'), ('Medium', 'Medium'), ('Low', 'Low'), ] priority= models.CharField(max_length=6, choices=priority_choices, default='Low') #new field def __str__(self): return self.title serializers.py from rest_framework import serializers from .models import Todo class TodoSerializer(serializers.ModelSerializer): class Meta: model = Todo fields = ('id', 'title', 'description', 'completed', 'priority') views.py class TodoView(viewsets.ModelViewSet): serializer_class = TodoSerializer queryset = Todo.objects.all() I just want the simplest solution, preferably to just update TodoSerializer(serializers.ModelSerializer) class inside serializers.py so that it would all come from this one Model. Is that possible? Reading https://www.django-rest-framework.org/api-guide/fields/#choicefield is not clear for me whether I need … -
Django Form Not Saving the Data
I've imported this from django.contrib.auth.forms import UserCreationForm used csrf_token in the form but still when I hit submit the page reloads but doesn't save the data to database def signup(req): if req.method == 'POST': form = UserCreationForm(req.POST) if form.is_valid(): form.save() form = UserCreationForm() reg_con={ 'regform': form } return render(req, 'signup.html', reg_con) <form action="." method="POST">{%csrf_token%} {{regform.as_ul}} <input type="submit" value="Sign Up"> -
Django: What's the difference between Queryset.union() and the OR operator?
When combining QuerySets, what's the difference between the QuerySet.union() method and using the OR operator between QuerySets |? Consider the following 2 QuerySets: qs1 = Candidate.objects.filter(id=1) qs2 = Candidate.objects.filter(id=2) How is qs1 | qs2 different from qs1.union(qs2)? Is there some subtlety under the hood that I'm missing? -
Evaluating Django QuerySet is fast, but still consumes a lot of server time
Using Django Query Profiler, I get the following results when loading my page. My query only takes 48ms to run, but the total server time is nearly 2 seconds! I have been able to verify that the query is fast by printing out the raw query and then running it manually. The relevant code in my ListAPIView view looks like: def get_queryset(self): start = time.perf_counter() queryset = MyModel.objects.all() \ .prefetch_related( # Prefetch related fields ).defer( # Don't select these fields ) print(len(queryset)) end = time.perf_counter() print(f"Evaluation time: {(end - start):.2f}s") return [ # Return hardcoded JSON result with single value to eliminate other factors ] The print(len(queryset)) statement is where the evaluation occurs. For some reason, this takes almost 2 seconds to complete, but only 48 ms of it is spent on the database. For some perspective, there are only 11 rows in MyModel. I wanted to rule out the possibilities that the server time was due to transforming the data, serializing the data, etc., so I am just returning a single JSON object. Given that all the other views in my application work just fine, I see no reason the server time can't be at least 10x faster. Any … -
How to use the AJAX with DJANGO appropriately?
I am a newbie in web dev and I know how to use the AJAX with DJANGO but i want to know what method is going to be the best one i use the script tags within my html files because they allow me to use DTL for urls but the time when use them I feel I'm doing something bad about design. Any guidelines what is standard way of writing a clean code which will be more usable? -
Why does django-channels not connect to secure Websockets wss?
I am trying to deploy my django = app to heroku. All features work except for the chat which uses Websockets. Keep in mind all everything works on my local machine. The problem has to do with wss vs ws on my server I the ChatConsumer does not connect when the websocket url starts with wss Here's my code on the browser: var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws"; const chatSocket = new WebSocket( ws_scheme + '://' + window.location.host + '/ws/chat/' + friendship_id + '/' ); here's asgi.py import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DBSF.settings") import django django.setup() from django.core.management import call_command from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack import social.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DBSF.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( social.routing.websocket_urlpatterns ) ), }) here's routing.py from django.urls import re_path, path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<friendship_id>\w+)/$', consumers.ChatConsumer.as_asgi()), ] here's consumers.py import json from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer from .models import Message, Friendship, User import datetime class ChatConsumer(WebsocketConsumer): def connect(self): print('fuuuuuuuu') self.room_name = self.scope['url_route']['kwargs']['friendship_id'] self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name …