Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: [WinError 10053] An established connection was aborted by the software in your host machine
I'm writing an API for django & django-rest. I used to develop it on ubuntu, but when I switched to windows I've started getting these errors on every response from django. Exception happened during processing of request from ('127.0.0.1', 54161) Traceback (most recent call last): File "C:\Users\Admin\anaconda3\envs\project\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Admin\anaconda3\envs\project\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Admin\anaconda3\envs\project\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Admin\anaconda3\envs\project\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Admin\anaconda3\envs\project\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Admin\anaconda3\envs\project\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine Developer tools also show me that this connection was cancelled. I have firewall & anti-virus programs disabled. This is the only lin in my /etc/hosts/ 127.0.0.1 localhost.localdomain localhost I'm using windows 10. Python 3.86 Django 3.1.2 django-cors-headers 3.5.0 djangorestframework 3.12.1 Do you know how to help this? -
FieldDoesNotExist error when using Django Rest Auth registration with a custom user model that does not have a username field
I have a custom user model that uses email for login and does not have a username field. I am trying to use django-rest-auth for rest-based user registration and login. I placed the following in my settings.py: SITE_ID = 1 AUTH_USER_MODEL = "users.User" ACCOUNT_EMAIL_VERIFICATION = "none" ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = False AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ) REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'users.serializers.CustomRegisterSerializer', } When trying to register via the registration endpoint the execution never even reaches my custom registration serializer, as it raises an error Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/torsten/opt/anaconda3/envs/journal/lib/python3.7/site-packages/django/db/models/options.py", line 581, in get_field return self.fields_map[field_name] KeyError: 'username' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/torsten/opt/anaconda3/envs/journal/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Users/torsten/opt/anaconda3/envs/journal/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/torsten/opt/anaconda3/envs/journal/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/torsten/opt/anaconda3/envs/journal/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/torsten/opt/anaconda3/envs/journal/lib/python3.7/site-packages/django/core/management/base.py", line 395, in check include_deployment_checks=include_deployment_checks, File "/Users/torsten/opt/anaconda3/envs/journal/lib/python3.7/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/Users/torsten/opt/anaconda3/envs/journal/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/torsten/opt/anaconda3/envs/journal/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/torsten/opt/anaconda3/envs/journal/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/torsten/opt/anaconda3/envs/journal/lib/python3.7/site-packages/django/urls/resolvers.py", line 407, in … -
Updating model field after input in Django
I am trying to update an account value model field after the user inputs a stock price and quantity from a form. Essentially the user would input a stock price and share quantity and their account balance should reflect the purchase amount. Below are images of my models.py, my forms.py, my views.py and my buy_stock.html page. Any insight as to how I can get the value to save would be very helpful. Thanks in advance. - Total newb [Models.py][1] [Forms.py][2] [views.py pt 1][3] [views.py pt 2][4] [buy_stock.html][5] [1]: https://i.stack.imgur.com/EpWDi.png [2]: https://i.stack.imgur.com/CCUQy.png [3]: https://i.stack.imgur.com/bhc74.png [4]: https://i.stack.imgur.com/wOe4v.png [5]: https://i.stack.imgur.com/fM7S6.png -
What does KeysValidator do in django?
I found pice of code where KeysValidator was used, but I didn't undestand what id does, so I've read the documentation https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/validators/ and I still don't understand it. Could someone explain, if we have JSONfield, what is KeysValidator? -
Uploaded image not displaying Django
Am trying to display an uploaded image but it is not displaying . Any help, please. Here are my settings MEDIA_ROOT=os.path.join(BASE_DIR,'media') MEDIA_URL='/media/' here urls.py from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) here is my model class ImageModel(models.Model): imagefile=models.ImageField(upload_to='images/', null=True, verbose_name="") result=models.CharField(max_length=100,choices=DISEASE_CHOICES ,default='tomato early blight') def __str__(self): return str(self.imagefile) Here is my view def upload(request): user = User.objects.get(username=request.user) if request.method == 'POST': form=imageForm(request.POST,request.FILES) if form.is_valid(): form.save() image=ImageModel.objects.last() disease=Disease.objects.get(name=image.result) new_prediction=Prediction() new_prediction.user=user new_prediction.disease=disease new_prediction.save() pestisides=Pestiside.objects.filter(disease=disease) else: image=None form=imageForm() pestisides=None disease=None print(disease,pestisides) context={'form':form,'image':image,'disease':disease,'pestisides':pestisides} return render(request,'diagnose/predict.html',context) Here is the image tag where am trying to display the image -
Exception Type: ValidationError - Babdly formed hexidemical
I get a ValidationError at /administration/administration/user/list ['“4” is not a valid UUID.'] when using: user_list = Actor.objects.filter(parent__parent__user_organisation__in=request.session['organisation']) the session produces the correct format e.g.: 89992d0d-284c-44ee-b8dc-6f9cf9cb1762 I have 3 Models: Actor(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) type = models.Charfield(max_length=20) Organisation(Actor): id = id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.Charfield(max_length=20) actor = models.OneToOneField(Actor, on_delete=Models.CASCADE) parent_organisation = models.ForeignKey(Actor, on_delete=models.CASCADE) CustomUser(AbstractBaseUser,PermissionsMixin,Actor): name = models.Charfield(max_length=20) member_of = models.ManyToManyField(Actor, on_delete=models.CASCADE) I am basically trying to get all users within an organisation: I have also tried: user_list = CustomerUser.objects.filter(parent__parent__id=request.session['organisation'] and user_list = Organisation.objects.filter(parent__parent_user_organisation=request.session[''organisation'] although I would like to try and keep all queries on the actor model if possible. Eventually, id like to get all users within a multi-tiered organisation structure although for now, I'm happy to get just users based on Organisation_parent rather than ----- Organisation_parent_Organisation_parent etc... I have changed my model structure to inherited to try and make queries easier but not having much luck. -
Wagtail document re upload with the same name doesn't purge CloudFront
I'm using an S3 backend for Wagtail. When I upload a pdf with the name dummy.pdf and then reupload a different file with the same name, if the document was linked in a page then the page on the frontend of the site leads to the old link. I can get around this by uploading the file with a slightly different name or publishing the page with the linked document. Are there any solutions to this in Wagtail 2.10.1? Again I don't want to have to fork the framework. -
apache sites-enabled confusion
I see a ton of files in this sites-enabled folder in my /etc/httpd (I inherited this server). I believe it is acting like a firewall before passing off to other virtualhosts/servers. I want to make sure I understand what is going on. For instance, one website that lives on a different server has two files in the sites-enabled on this 'firewall server': site-abc-ssl.conf site-abc.conf Inside the site-techdb.conf I have: <VirtualHost *:80> ServerName techdb.abc.com ServerAlias techdb Redirect "/" "https://techdb.abc.com/" </VirtualHost> I believe this is forcing the request to SSL/HTTPS? So then in the site-techdb-ssl.conf I have (And this is what I am not sure what is going on, I am no guru in apache). <VirtualHost 110.104.19.17:443> ServerName techdb.abc.com ServerAlias techdb <If "%{HTTP_HOST} != 'techdb.abc.com'"> Redirect "/" "https://techdb.abc.com/" </If> ProxyRequests Off ProxyPass / http://mynewserver.abc.com:591/ ProxyPassReverse / http://mynewserver.abc.com:591/ <Proxy *> Order deny,allow Deny from all Allow from 110.104.19. 10. 153.16. </Proxy> Include extra/ssl-certs </VirtualHost> mynewserver is just an internal ip address to a machine that is actually defined in our DNS so the mynewserver.abc.com points to our 10.71.10.1 which is the new server I am trying to show on the web as techdb.abc.com This new server is running django (more than likely in … -
Django Channels Error: No route found for path 'socketcluster/'. (I dont have any route called 'socketcluster/')
I'm learning Django Channels and I keep getting this error randomly: [Failure instance: Traceback: <class 'ValueError'>: No route found for path 'socketcluster/'. C:\Users\Alvaro\.virtualenvs\DjangoChannels-lIBZLoxz\lib\site-packages\autobahn\websocket\protocol.py:2839:processHandshake C:\Users\Alvaro\.virtualenvs\DjangoChannels-lIBZLoxz\lib\site-packages\txaio\tx.py:366:as_future C:\Users\Alvaro\.virtualenvs\DjangoChannels-lIBZLoxz\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred C:\Users\Alvaro\.virtualenvs\DjangoChannels-lIBZLoxz\lib\site-packages\daphne\ws_protocol.py:72:onConnect --- <exception caught here> --- C:\Users\Alvaro\.virtualenvs\DjangoChannels-lIBZLoxz\lib\site-packages\twisted\internet\defer.py:151:maybeDeferred C:\Users\Alvaro\.virtualenvs\DjangoChannels-lIBZLoxz\lib\site-packages\daphne\server.py:200:create_application C:\Users\Alvaro\.virtualenvs\DjangoChannels-lIBZLoxz\lib\site-packages\channels\staticfiles.py:41:__call__ C:\Users\Alvaro\.virtualenvs\DjangoChannels-lIBZLoxz\lib\site-packages\channels\routing.py:54:__call__ C:\Users\Alvaro\.virtualenvs\DjangoChannels-lIBZLoxz\lib\site-packages\channels\routing.py:150:__call__ ] WebSocket DISCONNECT /socketcluster/ [127.0.0.1:58432] My client application is a very simple HTML Page with Javascript that connects to the server and that sends a message when a button is clicked. // Connect Socket const endpoint = 'ws://localhost:8000/test/' const socket = new WebSocket(endpoint) // Button Event listener const btn = document.getElementById('myBtn') btn.addEventListener('click', ()=>{ socket.send("Button Clicked!!!!") }) My consumer is very simple, only accepts connections and prints them as well as the messages and disconnections: from channels.consumer import AsyncConsumer class MyConsumer(AsyncConsumer): async def websocket_connect(self, event): # Runs when new client tries to connect print("Connected:", event) await self.send({"type": "websocket.accept"}) async def websocket_receive(self, event): # Runs when new message received print("Received:", event) async def websocket_disconnect(self, event): # Runs when client gets disconnected print("Disconnected:", event) Finally, I only have 1 route called "test/" inside my "routing.py": from channels.routing import ProtocolTypeRouter, URLRouter from django.urls import path from apps.core.consumers import MyConsumer router = URLRouter([ path("test/", MyConsumer) ]) application = ProtocolTypeRouter({ 'websocket': router }) Everything else seems to work fine, when … -
(Django + IIS) Get current LAN account
I am currently running an app locally which has a huge dependency on pulling the LAN account for the current user. I have tried... (1) getpass.getuser() which returns the server name where the site is running via IIS. (pulls LAN account locally) (2) os.getlogin() which seems to return the name of the site configured in IIS (pulls LAN account locally) Any ideas on this would be EXTREMELY helpful, as I am very stuck with where I currently am. -
I want to project data from mongodb to a website in Django via html. How can i do that?
Here is what i am doing in settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'jobs_db', 'HOST': 'localhost', 'PORT': '27017', 'username': '', 'password': '', } } in models.py from mongoengine import * connect('jobs_tbl') class jobs_tbl(models.Model): job_company = models.CharField(max_length=200,null=True) job_location = models.CharField(max_length=200,null=True) job_title = models.CharField(max_length=200,null=True) Views.py content from mongoengine import * connect('jobs_tbl') def home(request): job=jobs_tbl.objects.all() context={ 'jobs':job, } return render(request,'Jobseeker.html',context) html content <div class="container card"> <h1>Available openings</h1> <div class="card-body"> <table class="table table-hover"> <tr> <th>Name</th> <th>Position</th> <th>Description</th> </tr> {% for c in jobs %} <tr> <td>{{c.job_company}}</td> <td>{{c.job_location}}</td> <td>{{c.job_title}}</td> <td><a href="{% url 'apply' %}" class="btn btn-info btn-sm" type="submit">Apply</a></td> </tr> {% endfor %} </table> </div> </div> I'm pretty new to web development, mongodb, html. I have been trying in the net for days but couldn't find solution for this. Any help is greatly appreciated. -
How would I create a button that submits a form and downloads a pdf simultaneously
Right now my download button has two separate areas, you can click the button and it will increase the download count but not download the pdf, but if you click on the Download text it will download but not increase the download count. I want to be able to click the button and it increase the download count and download the pdf simultaneously. I cant seem to figure out how to get this working any help would be appreciated. empowerment_card.html <form action="{% url 'download_count' empowerment.pk %}" method="post"> {% csrf_token %} {% if empowerment.empowerment_pdf_slick %} <button name="empowerment_id" value="{{ empowerment.id }}" class="download-button"> <a href="/media/{{ empowerment.empowerment_pdf_slick }}" download> download </a> </button> {% endif %} </form> views.py def download_add_count(request, pk): empowerment = get_object_or_404(Empowerment, id=request.POST.get('empowerment_id')) empowerment.download.add(request.user) return HttpResponseRedirect(request.META['HTTP_REFERER']) -
Is it possible to reduce/eliminate MyPy errors for system level code with a command line option?
Running MyPy over my code, These errors seem impossible to disable with a command line option. I don't want to mark the code to be ignored so that when they do get type hints things get better. I just want to eliminate this from files in the site-packages folders, not in any of my code. from django.db import connection from django.conf import settings from django.test import TestCase, TransactionTestCase from django.utils import timezone All of these suffer from this "error" error: Skipping analyzing 'django.conf': found module but no type hints or library stubs I should be clear that I don't want to ignore the non-existence of this code, just the non-existence of the type hints. -
Django cookies not working on Minikube at .local domain
I have a web app on Django with simple authentication as follows: # in a request handler username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') The app works fine running on localhost and on real servers through HTTPS at my-app.com (no a real domain of course). Now I'm trying to make it running on Kubernetes and Minikube. I've set up a Deployment, Service, NginX-Ingress, also I specified minikube ip in my /etc/hosts file as my-app.local, and I can access it using Chrome browser, but the authentication doesn't work! Browser saves no cookies, and I always get redirected to the log in page. And I cannot find any reason: I've checked server logs and browser network traces, they look fine, I also used curl to compare authentication method results of real .com version of the app and my minikube/.local version, they are pretty same, I see correct Set-Cookie: ... everywhere, but the cookies don't get saved in the browser. What can be the cause of this problem?? -
How to update form field text to show converted time
So I have a form that uses flatpickr to let the end user select a time using the local date/time. After the enduser selects this, I want the text in the form field to show the converted UTC time. I'm not able to get this working as the date field keeps showing the local time that was initially selected, and is not updating with the UTC time. I assume its just a simple jquery typo or not using the correct id's. <div id="create-modal" class="modal {{ form.is_bound|yesno:'show,fade' }}" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="{% trans 'Close' %}"><span aria-hidden="true">×</span></button> {% trans "New Program" %} </div> <div class="modal-body"> <form id="create-form" action="{% url 'app:create' application.id %}" method="POST"> {% csrf_token %} {% next_url request %} {% bootstrap_field form.application %} <div class="form-group"> {% bootstrap_field form.title %} </div> <div class="form-group"> <!-- <span id="schedule-value-display"> --> {% bootstrap_field form.scheduled_at %} <!-- </span> --> <script type="text/javascript"> $(document).ready(function() { {% if form.is_bound %} $("#create-modal").modal("show"); {% else %} $("#create-modal").modal("hide"); {% endif %} $("#create-modal").on("hide.bs.modal", function() { $("#create-modal").addClass("fade").removeClass("show"); $("#create-form").trigger("reset"); }); var defaultDate = new Date("{% now 'c' %}"); //var $scheduleSelector = $("#schedule-selector", $form); // var $scheduleBtn = $("#schedule-btn", $form); //var $scheduleValueDisplay = $("#schedule-value-display", $form); $("#create-form #id_scheduled_at").flatpickr({ enableTime: … -
Exclude list in django cannot update
Im having a trouble where I cannot filter and update exclude items in Django. I just want to update those item exclude from my list variable but it seems it's not working. Below is everything I got for now, thanks in advance I appreciate any help and suggestions lets say for example I have list ['1', '2', '5'] and I want to update all of my data in database exclude from 1,2,5 list and update all value into "3" views.py def update(request): if request.method=="POST": product_ids=request.POST.getlist('id[]') for id in product_ids: result = Person.objects.filter(province="DATA_1",municipality="Data_2").exclude(pk = id).update(paid=3) return render(request, 'dashboard.html') -
What smtp should I use to send email to other email providers in django?
I am not able to send email verification to other email providers using django. I am currently using Gmail smtp. What EMAIL_HOST I should use to send email verification to all email providers? enter image description here -
Django Login working, but Register not working
I having the landing page that the user is presented with the when they navigate to the home page. This page have both the login form and the register form, the login for works as expected, however when I try to register a user nothing happens. I don't get any errors or warnings. views.py def login_page(request): form = CreateUserForm() context = {'form': form} if request.user.is_authenticated: return redirect('dashboard:dashboard') elif request.method == 'POST': if 'login-submit' in request.POST: username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('dashboard:dashboard') else: messages.info(request, 'Username OR password is incorrect') elif 'register-submit' in request.POST: if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + user) return redirect('dashboard:login') return render(request, 'main/login.html', context) login.html <form id="register-form" action="" method="POST" role="form" style="display: none;"> {% csrf_token %} <div class="form-group"> {{form.username}} </div> <div class="form-group"> {{form.email}} </div> <div class="form-group"> {{form.password1}} </div> <div class="form-group"> {{form.password2}} </div> <div class="form-group"> <div class="row"> <div class="col-sm-6 center"> <button type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register">Register</button> </div> </div> </div> </form> forms.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username': forms.fields.TextInput(attrs={'class': 'form-control', … -
Make boolean values editable in list_display Wagtail?
I want to edit boolean values from the list page in Wagtail Admin. I cant seam to get this functionality working in Wagtail as its built upon Django i believe it can work on Wagtail as well but i cant figure it out. Django way of doing it: class TaskAdmin(models.ModelAdmin): list_display = (..., 'boolean_field') list_editable = ('boolean_field',) Thank you -
TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block
I have a large number of instances that I want removed from DB and ES on a daily basis. Also when I remove that instance from the ads table I want a version of it to be created in the expiredads table. For this I have a cron job that runs once a day every day at the same time. During the execution of this cron job in different places in the code begin to generate errors of the type: TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. I've been researching for weeks and haven't found a solution for this problem. As I have seen it is due to the use of transaction.atomic() but I don't know how to fix it. I'm using django 2.2.3 and python 3.7 def archive_ad(ad_id, **kwargs): """Archive an ad""" try: ad_instance = Ad.objects.get(id=ad_id) AdDocument().update(ad_instance, action="delete", raise_on_error=True) try: with transaction.atomic(): expired = ExpiredAd() fields = [field.name for field in ExpiredAd._meta.get_fields(include_parents=False) if not field.auto_created] fields.append('id') for field in fields: setattr(expired, field, getattr(ad_instance, field, None)) expired.status = AbstractAd.StatusChoices.expired expired.last_status = ad_instance.status expired.save() ad_instance.delete() except Exception as exception: AdDocument().update(ad_instance) raise exception except Ad.DoesNotExist: return -
How to optimise Images and Videos while Uploading with Django to Amazon S3?
I have a Django Project where my users can upload images/videos. I am using Amazon S3 storage for static and media files via boto to upload images and videos directly to Amazon S3. I want to optimise the image and videos both either on the fly or before uploading them. I mean if there is a static file it should be optimised and then uploaded(optimised in my django app) or optimised on fly? Which is the best way also how should I go about doing that? -
Best way to serialize a boolean representing a reverse lookup
I have some models that look like the following, where I would like to serialize Parent with a boolean field representing whether an associated Child reverse lookup exists. class Parent(models.Model): ... some fields class Child(models.Model): parent_fk = models.OneToOneField( "Parent", on_delete=models.CASCADE, related_name="child", ) ... some other fields class ParentSerializer(serializers.ModelSerializer): has_child = serializers.BooleanField() class Meta: model = Parent fields = ["has_child", ... some fields] These are the solutions I've tried and what I understand to be the problems with them just add "child" to fields - this inserts the value of the foreign key? use SerializerMethodField - triggers a DB lookup for each row? Is there a clean way to implement this feature? -
How can i perform 'row in' condition in django
I am using django, i want to implement a condition evaluating specific fields in a subquery, for instance: select a, b, c from letters where row(a,b) in( select a, b from other_letters can i do a row filter in django? -
How to have Django model fields with possibility of multiple entry/input?
I am using Django models fields and i want one of the fields with multiple entry or input. is it possible using *args? Below is my models and the "cc" fields is the one that I want to have multiple input and using def save function, but no avail. thank you in advance for possible advise. models.py: class Rtana(models.Model): rsc_name = models.CharField(max_length=128,unique=True) rsc = models.PositiveIntegerField(unique=True) cc = models.CharField(max_length=32,unique=True) def save(self,*args): super(Rtana,self).save(*args) def __str__(self): return '%s %s' % (self.rsc_name , self.rsc) def get_absolute_url(self): return reverse("app7_cbv:details",kwargs={'pk':self.pk}) -
How send message to groups on AsyncJsonWebsocketConsumer.disconnect()?
Please suggest to me a workaround on how to send message to groups on AsyncJsonWebsocketConsumer.disconnect()? class UserConsumer(AsyncJsonWebsocketConsumer): ... // some code async def disconnect(self, close_code: str) -> None: channel_layer = get_channel_layer() await channel_layer.group_send( "some_group", {"type": "send_message", "message": "some test message"}, ) This is a simple example of my code. When I do this, I've got error: File "/home/user/.pyenv/versions/3.8.6/envs/venv38/lib/python3.8/site-packages/channels_redis/core.py", line 666, in group_send await connection.zremrangebyscore( aioredis.errors.ConnectionForcedCloseError I think, disconnect() method is not the best place to send messages. If yes, what is a good place for this? Some useful links: https://channels.readthedocs.io/en/latest/topics/consumers.html?#asyncwebsocketconsumer https://aioredis.readthedocs.io/en/v1.3.0/api_reference.html#aioredis.ConnectionForcedCloseError - my error that raised by aioredis