Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
is there a way to prevent HTML input from taking some set of values, e.g (1,4,5,6,17)
I need to have some number input that takes any number except some specific set of numbers -
The right way to declare choices for django-form
I wonder what's the best way to set choices for forms.ChoiceField in Django. I need a form which first will get the set of choices using SQL query (done with that) and then display it to the user. The problem with my solution is that I have the query in forms.py and it only updates once when I run the server. Any ideas how to make it update every time the form itself renders for the user? -
how to turn off text overflow in rest framework
HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "title": "test title two", "description": "test description two", "paragraph": "test paragraph test paragraph \r\ntest paragraph test paragraph \r\ntest paragraph test paragraph \r\ntest paragraph test paragraph \r\n\r\ntest paragraph test paragraph \r\ntest paragraph test paragraph \r\n\r\n\r\ntest paragraph test paragraph \r\ntest paragraph test paragraph \r\ntest paragraph test paragraph \r\ntest paragraph test paragraph \r\n\r\ntest paragraph test paragraph \r\ntest paragraph", "author": "admin", "date": "2020-10-19T22:31:47.719276Z" } Using APIView class to view the content. I would like the "paragraph" not to overflow the text box, is there a way I could get the result something like this. "description": "test description two", "paragraph": test paragraph test paragraph test paragraph test paragraph test paragraph test paragraph .......... ............ "author": "admin", "date": "2020-10-19T22:31:47.719276Z" -
I can't create an virtual enviroment, because i have some problems with python archives
My english is not very well, so sorry about that. Python 3.8 Hello everyone, in my journey to learn Django and Kivy, i needed the virtual enviroments. When i try to create a virtualenv for Kivy, everything went well, but with Django... I have some problems inside this files: via_app_data.py via_app_data\pip_install\base.py Yes, INSIDE this files, i not understand because my paths are in the correctly directories, everytime i try to create a virtual enviroment, this message appears: User@User-PC MINGW32 ~/plzwork $ virtualenv new_env RuntimeError: failed to build image pip because: Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\via_app_data.py", line 58, in _install installer.install(creator.interpreter.version_info) File "c:\users\user\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 46, in install for name, module in self._console_scripts.items(): File "c:\users\user\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 116, in _console_scripts entry_points = self._dist_info / "entry_points.txt" File "c:\users\user\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv\seed\embed\via_app_data\pip_install\base.py", line 103, in _dist_info raise RuntimeError(msg) # pragma: no cover RuntimeError: no .dist-info at C:\Users\User\AppData\Local\pypa\virtualenv\wheel\3.8\image\1\CopyPipInstall\pip-20.2.3-py2.py3-none-any, has pip -
Django Models descending/nested query
I'm having trouble understanding how to use the table/model structure in Django to perform useful queries. What I'm trying to do is: given the primary key of a Show object, get a set of all the characters in the show. My models below: class Location(models.Model): identifier = models.CharField(max_length=200) def __str__(self): """String for representing the Model object.""" return self.identifier class Character(models.Model): identifier = models.CharField(max_length=200) def __str__(self): """String for representing the Model object.""" return self.identifier class Show(models.Model): name = models.CharField(max_length=200) shorthand = models.CharField(max_length=2, unique=True) def __str__(self): """String for representing the Model object.""" return self.shorthand class Season(models.Model): number = models.IntegerField() show = models.ForeignKey(Show, on_delete=models.SET_NULL, null=True, related_name="seasons") class Meta: unique_together = (("number", "show")) def __str__(self): """String for representing the Model object.""" return (str(self.show) + "s" + str(self.number)) class Episode(models.Model): number = models.IntegerField() season = models.ForeignKey(Season, on_delete=models.SET_NULL, null=True, related_name="episodes") class Meta: unique_together = (("number", "season")) def __str__(self): """String for representing the Model object.""" return (str(self.season) + "ep" + str(self.number)) class Scene(models.Model): number = models.IntegerField() character = models.ManyToManyField(Character, related_name="scenes") location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, related_name="scenes") episode = models.ForeignKey(Episode, on_delete=models.SET_NULL, null=True, related_name="scenes") class Meta: unique_together = (("number", "episode")) def __str__(self): """String for representing the Model object.""" return (str(self.episode) + "sc" + str(self.number)) This seems basic enough, but … -
Django: Redirect to the referring page (not the current form) when an UpdateView fails validation and is then Canceled?
My Django application allows a user to navigate to an Update Form (UpdateView) from multiple locations in the application. Currently, if the form is saved successfully I can redirect without a problem to the referring page by saving request.META.HTTP_REFERER in a hidden field in the template and retrieving it in form_valid. I can leverage the HTTP_REFERER data in MOST, but not ALL cases. One of those is the following scenario: My user navigates to the FORM A from Page X (HTTP_REFERER is set to Page X) FORM A is submitted and does not pass validation (HTTP_REFERER is now set to FORM A instead of Page X because indeed it has self-refered.) My user clicks Cancel (they are redirected back to FORM A instead of Page X) Is there a way to capture the Cancel event before it is processed and perform some logic so my user gets referred back to Page X instead of being stuck in the form? -
How to link CSS to HTML file for Email Sending in a Django Project
I trying to figure out a way to link CSS to an email html for sending. I have used inlinecss but it didn't work out due to errors in locating the CSS file in static. My question is there any way to add CSS to my HTML email other than Inlinecss In my template I have used using Inlinecss: {% load inlinecss %} {% inlinecss "/css/bootstrap.css" %} TEXT {% endinlinecss %} Here is the complete path of the CSS file: C:\Users\User\Desktop\Project\static_in_env\css\bootstrap.css After debugging I found that the reason is due to [Errno 2] No such file or directory: 'C:\\Users\\User\\Desktop\\static_root\\css\\bootstrap.css' Here is the files structure: # Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Any ideas to help link CSS to an email html for sending -
How can we add more than 3 authers field for a single article? in Django models
I created a magzine model in django. But their are more than three authors of a magzine. I have written below code for three authors. If I write the code of two or three author for a single magzine then it is looks somewhat good. But if I make for more than three authors then it will looks very bad. Now I am confused, Is the method that I have created is wrong? And if it is wrong then how should I write it? author_name1 = models.CharField(max_length=300, blank=True) designation1 = models.CharField(max_length=100, blank=True) author_pic1 = models.ImageField(upload_to="authorpic", blank=True) author_detail1 = models.TextField(max_length=1000, blank=true) author_name2 = models.CharField(max_length=300, blank=True) designation2 = models.CharField(max_length=100, blank=True) author_pic2 = models.ImageField(upload_to="authorpic", blank=True) author_detail2 = models.TextField(max_length=1000, blank=true) author_name3 = models.CharField(max_length=300, blank=True) designation3 = models.CharField(max_length=100, blank=True) author_pic3 = models.ImageField(upload_to="authorpic", blank=True) author_detail3 = models.TextField(max_length=1000, blank=true) -
How can i set pagination dynamically in Django Rest Framework?
I made an API endpoint using Django Rest Framework, it can be filtered according to two parameters. I'm trying to do the following: when there is no filter, it should retrieve x number of records, while when there is one or more filter, it needs to retrieve more records. So basically i need to change the pagination if there are filters. Here is what i tried: class My_View(viewsets.ModelViewSet): http_method_names = ['get'] serializer_class = My_Serializer pagination_class = StandardResultsSetPagination def get_queryset(self): valid_filters = { 'Name': 'Name', 'Date': 'Unix__gte', } filters = {valid_filters[key]: value for key, value in self.request.query_params.items() if key in valid_filters.keys()} if len(filters) == 0: pagination_class = StandardResultsSetPagination else: pagination_class = LargeResultsSetPagination queryset = My_Model.objects.filter(**filters) return queryset What this code what supposed to do is to set a standard pagination of 100 if there isn't a filter, and 200 if there are filters. This code doesn't work, the pagination will always be set to StandardResultsSetPagination, and it doesn't get changed. I think it's because get_queryset is called after the pagination is set, so it can't be set again later. Is there any way to do that? Thanks in advance! -
Error: Using the URLconf defined in mysite.urls
I am receiving an error when I open http://127.0.0.1:8000/v1/. I am following a beginner Django tutorial: https://www.youtube.com/watch?v=UxTwFMZ4r5k&ab_channel=TechWithTim I come across this error when I go to http://127.0.0.1:8000/v1/: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ [name='index'] The current path, v1, didn't match any of these. I appreciate your time to look over my code and offer any suggestions and clarification. Desktop/django_tutorial/mysite/main/views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(response): return HttpResponse("<h1>It's just David!</h1>") def v1(response): return HttpResponse("<h1>View 1!</h1>") Desktop/django_tutorial/mysite/main/urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("v1/", views.v1, name="views 1"), ] Desktop/django_tutorial/mysite/mysite/urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("main.urls")), ] I reviewed similar issues that have been posted on this website. However, the other posts were about older Django versions. I appreciate further clarification on this issue. Thank you. -
how to install and configure postgresql and django in the same dockerfile
I need to install and configure postgresql and django in one container, I can't use docker-compose because the hosting doesn't have support for docker-compose. i try of following but I get this error This is my configure postgres in settings.py -
How can I host my Django website on a local server?
I have created a website with Django, running locally in a linux virtual machine on ip adress 192.168.0.111:8000. Now I want to make this website available for the public, hosted on my own machine. I have a webproxy (NginxProxyManager) running on my server on ip adress 192.168.0.118:7818 which handles all my other static websites. I can route my domain name https://django.example.com to 192.168.0.111:8000 in my webproxy and everything works in DEBUG = True, but i know this is not the way to do it, and DEBUG = False does not serve static files properly. How can i do this? All websites about this topic are takling about publishing to Heroku or something else, but i want to host it locally. Thank you! -
Django ".widget.attrs.update" with NO effect
I have a ModelForm with the following init method: def __init__(self, *args, **kwargs): super(FragebogenForm, self).__init__(*args, **kwargs) self.fields['birth_date'].widget.attrs.update({'type': 'date'}) This doesn't change the type attribute of the input tag, although it should according to the documentation (ctrl + f -> "Or if the field isn’t declared directly on the form"). If I change it to e.g. .widget.attrs.update({'placeholder': '12.12.1999'}) it works, the new placeholder appears on the page. Only setting the type to date does not work, but why? -
docker multi stage build fails when trying to add another package
I am trying to add additional packages to saleor but I can't get docker to build the image. I want it to work but docker saleor service fails to build and returns an error: ModuleNotFoundError: No module named 'stream_django' ERROR: Service 'saleor' failed to build : The command '/bin/sh -c SECRET_KEY=dummy STATIC_URL=${STATIC_URL} python3 manage.py collectstatic --no-input' returned a non-zero code: 1 I think the error occurs due to whatever is being compiled with the package not being copied over to the final build but I am brand new to dev and am too inexperienced to fix it. So any help would be appreciated dockerfile FROM python:3.8 as build-python RUN apt-get -y update && apt-get install -y gettext \ && apt-get clean && rm -rf /var/lib/apt/lists/* COPY pyproject.toml /app/ WORKDIR /app RUN pip install poetry RUN poetry config virtualenvs.create false RUN poetry install FROM python:3.8-slim ARG STATIC_URL ENV STATIC_URL ${STATIC_URL:-/static/} RUN groupadd -r saleor && useradd -r -g saleor saleor RUN apt-get update && apt-get install -y libxml2 libssl1.1 libcairo2 libpango-1.0-0 libpangocairo-1.0-0 libgdk-pixbuf2.0-0 shared-mime-info mime-support && apt-get clean && rm -rf /var/lib/apt/lists/* COPY . /app COPY --from=build-python /usr/local/lib/python3.8/site-packages/ /usr/local/lib/python3.8/site-packages/ COPY --from=build-python /usr/local/bin/ /usr/local/bin/ WORKDIR /app RUN SECRET_KEY=dummy STATIC_URL=${STATIC_URL} python3 manage.py collectstatic … -
Creating a form instance in aview and then saving it gives a 500 Internal Server Error
This is my current view and because of using AJAX, the array sent to the view isn't in the right format so I'm using stringify to fix all of that. The problem is that I can't change the fields value on the existing form so I decided to create a new form. if request.method == 'POST': form = SubscriberForm(request.POST) category = json.loads(request.POST.get('category')) frequency = json.loads(request.POST.get('frequency')) formNew = SubscriberForm(form['email'], form['country'], category, frequency) This doesn't seem to work and I'm just getting a 500 Internal Server Error. -
LIST VARIABLE OF DJANGO OBJECTS
Is there a way to create a list variable in javascript of Django Model objects? I have a Project Model and I have several Project objects. I'd like to create a list of those objects in javascript. -
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 …