Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django display html page based on user type
I want to display the home page of my site based on the user type (admin, guest, student, etc.). It would be nice to display a link to the login page for guest users, but this link should be hidden for already authenticated users. For admins there should be a link to django-admin. Besides that there also some differences in the home page for other user roles. What is a good way to implement this? I have several options for that: Create html page for each user role: home_guest.html, home_admin.html, ... Create a single html page but put some if-clauses inside it like {% if user.is_authenticated %} -
How to send POST or GET requests to one API and get data from ERP API?
I have access to API of ERP software. I want to give my clients access to it but not directly, just by another API. I want to restrict what They can POST and GET, but API from ERP couldn't do it so need to create my own like some connector or something. I want to use Django for it. How my clients make POST or GET requests and get info from ERP API? -
how to link between chrome extension and auth system built in django?
I'm making a chrome extension & I've made a log in and create a new account system using Django. When users try to use the extension for the first time it will take them to the "Create new account" page, What I need to know is how to link between the extension & the Django authentication system in a way that it can always remember the user after signing up for the first time or logging in afterwards. I know that I need to use API end point but if someone can give more detailed steps to do so will be much appreciated -
Django, how to reuse views code in other views and template
I'm new in django and I was wondering if is it possible to reuse code and annotate output write in a views.py. I have created a lot of new annotate output that I want to reuse to figure out a dashboard with graphs and key indicator. I don't like to rewrite all code because I wouldn't follow the DRY principles. -
django cannot find object field. error: Items() got an unexpected keyword argument 'sellbtn'
I am trying to access my object but a field I created, it is telling me it is not there. $ cat userdash/views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .models import AssetList, Items from .forms import CreateNewTrade # Create your views here. #def index(response): # return HttpResponse("<h1>Hello Dark World!</h1>") def userdash(response, id): ls = AssetList.objects.get(id=id) if response.method == "POST": print(response.POST) if response.POST.get("save"): for item in ls.items_set.all(): if response.POST.get("c" * str(item.id)) == "clicked": item.sellbtn = True else: item.sellbtn = False item.save() elif response.POST.get("newItem"): txt = response.POST.get("new") if len(txt) > 2: #this validation is retarded and needs to be fixed ls.items_set.create(user_asset=txt, sellbtn=False) #this is the line in question else: print("invalid") #items = ls.items_set.get(id=1) #return HttpResponse("<h1>User Dashboard!</h1><h2>%s</h2><br></br><p>%s</p>" %(ls.name, str(items.user_asset))) return render(response, "userdash/list.html", {"ls":ls}) def home(response): #pass return render(response, "userdash/home.html", {}) def create(response): if response.method == "POST": form = CreateNewTrade(response.POST) if form.is_valid(): n = form.cleaned_data["user_asset"] t = AssetList(name=n) t.save() return HttpResponseRedirect("/userdash/%i" %t.id) else: form = CreateNewTrade() return render(response, "userdash/create.html", {"form":form}) $ cat userdash/templates/userdash/list.html {% extends 'userdash/base.html' %} {% block title %} List Page {% endblock %} {% block content %} <h2>{{ls.name}}</h2> <form method="post" action="#"> {% csrf_token %} <ul> {% for item in ls.items_set.all %} {% if item.sell_asset == True %} … -
"AttributeError: module 'django.contrib.auth.views' has no attribute 'password_reset' " error in urls.py
I am using Django 3.0.5 and python 3.6 and getting the error from the terminal as : " AttributeError: module 'django.contrib.auth.views' has no attribute 'password_reset' " in my urls.py file. urls.py ``` from django.contrib import admin from django.urls import path from django.contrib.auth import views as auth_views from django.conf.urls import url from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('index/',views.index, name='index'), path('datetime/',views.current_datetime,name='datetime'), path('',views.post_list,name='post_list'), url(r'^blog/(?P<id>\d+)/(?P<slug>[\w-]+)/$',views.post_detail,name="post_detail"), url('post_create/',views.post_create,name = "post_create"), url('login/', views.user_login,name="user_login"), url('logout/', views.user_logout,name="user_logout"), #Password reset urls url('password-reset/',auth_views.password_reset, name='password_reset'), url('password-reset/done/',auth_views.password_reset_done,name="password_reset_done"), url('password-reset/confirm/(?P<uidb64>[\w-]+)/(?P<token>[\w-]+)/',auth_views.password_reset_confirm, name="password_reset_confirm"), url('password-reset/complete/', auth_views.password_reset_complete,name="password_reset_complete"), ] ``` I have checked here which is talking about the same 4 views which I have written then why I am getting the error. When I change "auth_views.password_reset" to "auth_views.PasswordResetForm in "url('password-reset/',auth_views.password_reset, name='password_reset')" then, terminal does not show any error for "password_reset" but then it shows error for "password_reset_done". Can anyone please tell why I am getting this error and how to fix it. Any help would be appreciated. -
How can I avoid hard-coding multiple elements into my Django model?
I'm pretty new to Stack Overflow, so thank you in advance for your insight. This is a question about Django 3.0 (so Python 3.6+). Use case: Let's say I've successfully parsed through the Code of Federal Regulations and I've determined that each regulation has three parts - the citation, the subject, and the regulation itself. I can parse these into a nested dictionary at need (or XML, or CSV, or any format really). Let's also assume I have a complex business that needs to comply with many of these regulations, so I have to figure out whether the regulation is applicable and how I'm going to implement it. So this is my models.py class CFR(models.Model): citation = models.CharField(max_length = 25) subject = models.CharField(max_length = 25) regulation_text = models.TextField() applicable = models.BooleanField(default = True) implementation = models.TextField() My forms.py. Yes I know I shouldn't use __all__. class RegulationForm(forms.ModelForm): class Meta(): model = CFR fields = ('__all__') and my views.py class ApplicabilityView(CreateView): model = CFR template_name = "template.html" form_class = RegulationForm I'd like to use the model to: Iterate through each regulation. Render a form containing each regulation (there could could be hundreds of regulations, so the length of the form doesn't … -
Datatables do not update with jQuery when using Django models
I am trying to implement the answers given in an old post(1). It describes a "problem" when jQuery Datatables is not refreshed after adding a row of data / writing to the model database in Django. The two non-accepted answers suggests: $("#analytic-table").DataTable().destroy(); flush DT's cache and then re-initialize the DataTablead table with $("#analytic-table").DataTable(); or, to add a row trough table.rows.add($(data.html_analytic_list))).draw(); After consulting other posts suggestion similar solutions, nothing really works. With this I mean, I can write data to the model/database but changes does not appear in the table until I manually reload the page containing the table. To instruct Datatables to contact Django for a refresh of data does not seems to work. Given this, I am let to believe I am missing some crucial steps within the combination of jQuery Datatables and Django models and would like to ask if someone else have experienced the same problem and know the solution. Please note that I visually can "fake" data by $("#analytic-table > tbody:last-child").append(`<tr> table data </tr>') However, I cannot apply any other action until i refresh the page with the table. -
Django AttributeError: 'ManyToManyDescriptor' object has no attribute 'filter'
Hi I am trying to see if a user exists users in a ManyToMany relationship between my models. I have two models: A Course model A Profile model My course model is: class Course(models.Model): course_code = models.CharField(max_length=20) course_content = models.CharField(max_length=100) course_name= models.CharField(max_length=100) course_likes = models.ManyToManyField(Profile, blank=True, related_name='course_likes') and my user models I have this field: courses = models.ManyToManyField('home.Course',related_name='profiles') in my course model, I have a method that filters courses based on the course regardless of the course description and checks to see if user exists: def is_liked(self,user): Course.course_likes.model.objects.filter(course_code=self.course_code, profiles__id=user.id).exists() and I am also trying to add a user to likes by: Course.objects.get(course_code=code).course_likes.add(request.user) Which I believe is also incorrect(Haven't tested yet since the first step is to check if user already exists) Now when I test the method for checking if the user exists I get an error: return Course.likes.filter(course_code=self.course_code,profiles__id=user.id).exists() AttributeError: 'ManyToManyDescriptor' object has no attribute 'filter' I am using a template tag execute the method using: @register.simple_tag(takes_context=True) def check_is_liked(context): request = context['request'] course = context['course'] return course.is_liked(request.user) Which I believe is working properly as the error is related to my models function. In my template I use (I have tested the course object is being sent correctly): {% with course=course … -
Should i quit Django for freelancing? [closed]
THIS IS NOT A TECHNICAL QUESTION....! Just looking for a sincere advice.... The thing is i have been learning python & django since last year spending 4-6 hours each day. My ultimate goal was to be a successful freelance web developer afterwards. I had an option of Php but i didn't choose it because i just liked python (as i was using Linux that time) and now i think that was the biggest mistake i made. Now when i am in the freelance business, i see there is only php everywhere. 90% of jobs in web development are for php and it is very hard for a newbie to get the job for django when it is in such a low demand. Now, I am quite confused if i should quit django right now and learn php from scratch to make some stand in the business or should i just stick with it ? Sincere advices would be really appreciated...! Thankyou -
Django-Simple-Captcha Cron Job To Delete Captcha Records
I need some help with making a cron job for django-simple-captcha to be able to delete captcha database records from postgresql on a daily basis or an hourly basis. According to the docs and the maintainer himself, you can use: CAPTCHA_GET_FROM_POOL, CAPTCHA_GET_FROM_POOL_TIMEOUT, CAPTCHA_TIMEOUT settings combined with python3 manage.py captcha_create_pool command. But the docs are a bit confusing and do not show you an example of how to do the cron job with postgres. I also do not know in production if it is good to run the python3 manage.py captcha_create_pool while the site is actively running in gunicorn. Does gunicorn need to be stopped to be able to run the captcha_creat_pool command with a cron job? Can any of the django packages below be used to make this easier? If so, how? I would prefer if someone gave a nice example or description of how to do this. https://djangopackages.org/grids/g/cron/ https://django-simple-captcha.readthedocs.io/en/latest/advanced.html -
Image.save() is saving empty empty image (0B)
I am saving Images in amazon s3 storage. image = models.ImageField(upload_to=upload_avatar_to, null=True, blank=True) def upload_avatar_to(instance, filename): import os from django.utils.timezone import now shop_uuid = Shop.objects.get(id=instance.shop_id).uuid instance_dict = instance.__dict__ filename_base, filename_ext = os.path.splitext(filename) return 'shops/%s/items/%s/%s%s' % ( shop_uuid, instance_dict['uuid'], now().strftime("%Y%m%d%H%M%S"), filename_ext.lower(), ) Now i am getting the image saved on storage and resizing it to thumbnail per it is saving empty file (having size 0B) by calling create_avatar_thumb def create_avatar_thumb(self): import os from PIL import Image from django.core.files.storage import default_storage as storage if not self.image: return "" file_path = self.image.name filename_base, filename_ext = os.path.splitext(file_path) thumb_file_path = "%s_thumb.jpg" % filename_base f = storage.open(file_path, 'rb') image = Image.open(f) image.thumbnail((400, 400)) f_thumb = storage.open(thumb_file_path, "w") image.save(f_thumb, "JPEG") f_thumb.close() Please help; using django -
How to view Django Rest Framework Source Code in VS Code
I am new to Django Rest Framework. I am working on a project running in Docker containers. I would like to view Django Rest Framework source code in VS Code. When I right-click on anything from the following line and click Go to Definition I get the message No definition found for 'rest_framework' from rest_framework import viewsets How can I view django rest framework source code in VS Code, particularly if I'm running my projects in containers? Thank you -
How to add other views and models into generic detail view in Django
I am creating a django ecommerce website. My cart page shows the items, quantity, price and all that stuff of the order. I am creating a mini-cart that shows up on all pages when the user hovers over the cart icon, which shows all this data, and the user can click on it to go to the cart page. This worked on all my other pages (products page and cart page), but I can't seem to add the needed variables into my DetailView page for each product. The models that are related to this are: class Product(models.Model): name = models.CharField(max_length=200, null=True) price = models.FloatField(max_length=200) description = models.TextField(max_length=500, default='No description') digital = models.BooleanField(default=False, null=True, blank=False) image_1 = models.ImageField(null=True, blank=False, default='') image_2 = models.ImageField(null=False, blank=True, default='') image_3 = models.ImageField(null=False, blank=True, default='') images = [image_1,image_2,image_3,] def __str__(self): return self.name def get_absolute_url(self): return reverse('product-detail', kwargs={'pk':self.pk}) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) … -
I can´t save or init a form in Django
I want to fill in a form datas from via GET url. This is a Detail View inside has a form page1.html <form action="{% url 'home_app:viajes_all' %}" method="get">{% csrf_token %} <p>Name: <input type="text" name="FullName" size="40" value={{user.username}} disabled></p> <p>Number: <input type="number" name="counter" min="1" max="10" default=1></p> <p> <input type="submit" value="Submit"> </p> </form> this generate a URL with params like: validate/?csrfmiddlewaretoken=OUANf34UX4lB68tCKffBEE&counter=6 and other page html generate the form: <div> <form method="post">{% csrf_token %} {{ form.as_p }} <button type="submit">Add</button> </form> </div> So, if I want to save only filled the form and y press Add button and all its fine. class CreateContact(CreateView): model=Prueba template_name='userviaje/registerUV.html' form_class=ContactForm success_url = '/' def form_valid(self, form): self.object = form.save(commit=False) self.object.save() return super(CreateContact, self).form_valid(form) But if i want than this form is automatic fill by params in his URL. I need add this code in my View def get(self, request): context ={} if self.request.method == 'GET': counter= self.request.GET.get('counter', None) form = ContactForm( counter=counter, ) return render(request,'userviaje/registerUV.html', {'form':form }) and add this code the Form too def __init__(self, counter, *args, **kwargs): super(ContactForm,self).__init__(*args,**kwargs) self.fields['counter'].initial=counter So this way my form is auto filled by URL but the button Submit Doesn't work. Somebody knows Why? Apeers a error like : _init__() missing 1 required … -
Unable to handle users and models in my django project
In my django project ,when a user sign up, a form is redirected to fill user information,further iam displaying this info on other page ,but whats happening is when i am dislaying the information of the current user who had logged in ,information of all users is displayed who had been signed up earlier. -
get output of external barcode scanner to Django
I am building a product store application with django. how can I get output of external barcode scanner to Django project ? I don't know how to start in this. -
Django is getting static file path when inspect But cannot find the file on location
Here is my URLs of project file from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', include('resume.urls')), ] urlpatterns += staticfiles_urlpatterns() urlpatters = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) here is my URL of resume app from django.urls import path, include from . import views urlpatterns = [ path('', views.resume,name='resume',) ] Here is my resume models class about(models.Model): profile = models.ImageField(upload_to='pictures/') name = models.CharField(max_length=50) Here is my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL = '/static/media/' MEDIA_ROOT = (os.path.join(BASE_DIR,'/media/')) This is my Files orientations This is my Files orientations in django Here is my element in chrome where link of image is perfectly found but file is not getting, Here is my element in chrome where link of image is perfectly found but file is not getting, I am new to django , please use simple terms so I can understand , where I am doing wrong and How can I fix this. please help. -
Get extra data in Django social auth app with custom user model
Hi i am trying to login through steam on my django project using social auth app. I am very new to django and web development infact its my first project so i am sorry if i don not know some obvious things. For now what i am trying to do is get some rank data from my csgo server mysql database, sort it and search for logged in user ranks etc. I want to add more fields to user model in future so i created class Profile and as i can gather from doing searches online if i want to use django authentication and do not wanna implement my own i have to extend using AbstractUser and add extra fields here (correct me if i am wrong). class Profile(AbstractUser): credit = models.BigIntegerField(default='0') # and some function relating this below in settings.py AUTH_USER_MODEL = 'users.Profile' SOCIAL_AUTH_STEAM_EXTRA_DATA = ['player'] now when i login i a user is created under social user which i can see in admin panel enter image description here if i click on it i can see extra data too. Now when i try to access it in views.py using if request.user.is_authenticated: userID = request.user.social_auth.get( provider='steam' ).extra_data.player.steamid i get … -
POST request with curl to Django endpoint works but using python request module it fails
There are a bunch of similar posts, but none of the solutions seem to work for me. The problem is that for a Django endpoint, curl in following format gives 201: curl --request POST 'http://hostname/path' \ --header 'Content-Type: application/json' \ --data-raw '[ {k1: v1, k2: v2}, {...} ]' however a similar attempt with Python requests, gives 400 response with message: {"non_field_errors":["Invalid data. Expected a dictionary, but got list."]} requests.post(HTTP_ENDPOINT, json=json_rows) where json_rows is a valid json of the form [{k1: v1, k2: v2}, {...}]. I did try a bunch of variations in requests including using data, trying to send body as string, etc. But, none of them worked. I guess, it's some peculiarity of how Django expects data (is it the correct way to expect data?) but would also like to know how to replicate the curl request in requests. -
Storing vs computing Permissions in Django Rest Frameword Views
Suppose in an application there is a model "Service". There is also an "Orders" model which takes care of "User" purchases. class Service(models.Model): name = models.CharField(max_length=10) class Order(models.Model): service = models.ForeignKey(Service) user = models.ForeingKey(get_user_model()) My question is what is better while checking access of a user to a service: A> Storing and using per object permissions(saved in another table) with the help of third party libraries like Django guardian. B> Computing the permission on each request. Example Permit if the user has bought that service. Does A. makes sense only in case of large computations? Or there is some other benefit of storing these permissions as well? -
How can I access table's data on Django admin website at my controller?
Ok so I have some problems to print my NewsUsers model's datas in my template. If I decide to print NewsUsers.first_name, it shows to me, not the NewsUsers first_name but the django-admin first_name. And I don't know why. Although, if I decide to print it directly in the console, it shows to me the right thing... Please, help me. I'm confused... HERE IS THE NEWUSERS MODEL class NewUsers(models.Model): first_name = models.CharField(max_length=30, default='') last_name = models.CharField(max_length=30, default='') username = models.CharField(max_length=30, default='') email = models.EmailField(max_length = 254, unique=True, default='') password = models.CharField(max_length=100, default='') phone_number = models.CharField(max_length=255, blank=True) isAdmin = models.BooleanField(default='False') THERE IS MY CONTROLLER: def login(request): title = 'Connexion' if request.method == 'POST': email_sent = request.POST['email'] password_sent = request.POST['password'].encode('utf-8') global isConnected user = NewUsers.objects.filter(email = email_sent).first() print(user.first_name) if user: if isConnected in request.session: isConnected = request.session['isConnected'] return redirect('http://localhost:8000/', {'isConnected':isConnected, 'first_name':user.first_name, 'last_name':user.first_name}) else: request.session['id'] = user.id request.session['first_name'] = user.first_name request.session['last_name'] = user.last_name request.session['phone_number'] = user.phone_number """ request.session['isConnected'] = isConnected """ isConnected = True print(request.session['id'], request.session['first_name'], request.session['last_name'], request.session['phone_number']) return redirect('http://localhost:8000/', {'isConnected':isConnected, 'user':user}) else: print('Something went wrong') return render(request, 'login.html', {'title':title, 'isConnected':isConnected}) return render(request, 'login.html', {'title':title, 'isConnected':isConnected}) else: return render(request, 'login.html', {'title':title, 'isConnected':isConnected}) AND THIS HOW I CALL THE USER OBJECT: <span class="initials" style="...">{{ user … -
How to get number of items within a category in wagtail/django?
On my website page, I am trying to display the number of posts within each category on the html component. Here is an example of what I want to do below. I already added category names on the html component. The value next to the category names are just random number used as placeholder. I have been struggling to get the value for the number of posts within each category. I really dont know what queryset im suppose to use. Here are my code. blog.py class BlogPage(Page): def get_context(self, request, *args, **kwargs): context = super().get_context(request, *args, **kwargs) category_slug = request.GET.get('category', None) blogposts = PostPage.objects.live().public().order_by('-first_published_at') if category_slug == None: context['blogposts'] = blogposts else: context['blogposts'] = blogposts.filter(categories__slug__contains=category_slug) context['category_slug'] = category_slug context['categories'] = BlogCategory.objects.all() # category object return context class PostPage(Page): date = models.DateField(verbose_name="Post date") categories = ParentalManyToManyField("blog.BlogCategory", blank=True) body = RichTextField(blank=False) main_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=False, on_delete=models.SET_NULL, related_name='+') content_panels = Page.content_panels + [ FieldPanel('date'), FieldPanel('categories', widget=forms.CheckboxSelectMultiple), ImageChooserPanel('main_image'), FieldPanel('body', classname="full"), ] @register_snippet class BlogCategory(models.Model): name = models.CharField(max_length=120) slug = models.SlugField( verbose_name="slug", allow_unicode=True, max_length=255, help_text='A slug that identify post by category.' ) panels = [ FieldPanel('name'), FieldPanel('slug'), ] def __str__(self): return self.name blog_page.html <ul class="cat-list"> {% for cat in categories %} <li> <a … -
Django-Ngix-Gunicorn returning wrong path for media files using Docker Compose
Im having trouble with a Django REST Framework App deployed in production mode using docker compose. The problem is when my endpoint returns the model with an ImageField it returns the wrong path, specifically missing the url port. Static files are working fine with the port included in the response url. For example: Current value: http://127.0.0.1/media/machines/034793bb-8516-45e3-a50a-4e00e7488617.png Expected: http://127.0.0.1:8000/media/machines/034793bb-8516-45e3-a50a-4e00e7488617.png Settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATIC_ROOT = '/app/static/' ** Docker file ** FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir /app WORKDIR /app ADD . /app/ RUN pip install -r requirements.txt CMD ["gunicorn", "-c", "config/gunicorn/conf.py", "--bind", ":8000", "--chdir", "app_api.wsgi:application"] Docker-compose version: '3.7' services: web-service: build: . command: bash -c "pip install -r requirements.txt && python manage.py makemigrations && python manage.py migrate && python manage.py collectstatic --noinput && python manage.py runserver 0.0.0.0:8000" container_name: app_backend volumes: - static:/app/static - media:/app/media - .:/app depends_on: - db restart: on-failure:2 db: image: postgres container_name: app_postgres environment: - POSTGRES_USER=bd_user - POSTGRES_PASSWORD=password - POSTGRES_DB=new_database ports: - "5432:5432" volumes: - postgres:/var/lib/postgresql/data restart: on-failure:2 nginx: image: nginx:latest ports: - 8000:80 volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static:/app/static - media:/app/media depends_on: - web-service volumes: media: static: postgres: driver: local … -
Unable to get websockets tests to pass in Django Channels
Given a Django Channels consumer that looks like the following: class NotificationConsumer(JsonWebsocketConsumer): def connect(self): user = self.scope["user"] async_to_sync(self.channel_layer.group_add)("hello", "hello") self.accept() async_to_sync(self.channel_layer.group_send)( "hello", {"type": "chat.message", "content": "hello"} ) def receive_json(self, content, **kwargs): print(content) async_to_sync(self.channel_layer.group_send)( "hello", {"type": "chat.message", "content": "hello"} ) print("Here we are") def chat_message(self, event): self.send_json(content=event["content"]) def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)("hello", "hello") and a test that looks like the following: @pytest.mark.asyncio class TestWebsockets: async def test_receives_data(self, settings): communicator = WebsocketCommunicator( application=application, path="/ws/notifications/" ) connected, _ = await communicator.connect() assert connected await communicator.send_json_to({"type": "notify", "data": "who knows"}) response = await communicator.receive_json_from() await communicator.disconnect() I am always getting a TimeoutError when I run the test. What do I need to do differently? If you'd like to see a full repo example, check out https://github.com/phildini/websockets-test