Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django images don't show up on the web-site
settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') template <img src="{{ group_avatar.avatar.url }}" style="width:30%" alt="Group Avatar" class="navbar-brand"> urls.py `urlpatterns = [ path('admin/', admin.site.urls), # Django admin route path("", include("apps.authentication.urls")), # Auth routes - login / register # ADD NEW Routes HERE # Leave `Home.Urls` as last the last line path("", include("apps.home.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)` Instead of getting an image, I get an alt text... I've tried to fix it up for a long time, but nothing works... Django version 3.2.16, using settings 'core.settings' I suppose that the problem is in the project structure. It was done before I started working on the project and it would be difficult to change it... application is in the folder apps, which is in the root folder, and template which is needed is also there. But the folder 'media' is in the root directory. Although I'm not sure that the problem is in this. Interesting fact is that if I manually write the way to the image from static folder (static folder is also localed in apps directory) it will work. Would be glad for any help) Searching, reading documentation. I expect a hint how to fix it or where to search the … -
Django Paginator with bulk_update only updates odd pages
I have a two tables that have around 1M rows and in one of them, I've added a new migration that adds two new columns to one of them and that requires some computation to add their values. What I did was a command that fetches all rows in that table, and use Paginator with a chunk size of 1000, and after adding the new values, I perform the bulk_update. The problem is that only the odd pages are updated, the even ones stay with the null value. I start with 1000 pages to update, then I need to run again only to update 500 pages, and so on. I've also tested with chunks of 10, and the problem persists. Is there something wrong with this code? def add_values_to_columns(foo): foo.col1=... foo.col2=... class Command(BaseCommand): def handle(self, *args, **options): try: queryset = Foo.objects.all() \ .filter(col1__isnull=True, col2__isnull=True) \ .order_by("id") \ .select_related("bar") chunk_size = 1000 paginator = Paginator(queryset, chunk_size) pages = paginator.page_range number_pages = pages[-1] for page_number in pages: page = paginator.page(page_number) updated_rows = [] for foo in page.object_list: add_values_to_columns(foo) updated_rows.append(foo) Foo.objects.bulk_update(updated_rows, ["col1", "col2"]) except Exception as e: self.stdout.write(e) -
Django VS-Eextenstion is not colorizing syntax inside cotation
I am using Django extension to highlight my text. it works perfectly outside but fails to highlight inside citations. not working under cotations I expect if there is any solution to overcome this. I want it to highlight the code inside exactly as outside , what can i do to overcome this. -
List column data in Django template can not be iterated
Please read my code <p>{{request.POST}}</p> <p>langchi : {{request.POST.langchi.0}}/{{request.POST.langchi.1}}/{{request.POST.langchi.2}}/{{request.POST.langchi.3}}<p> <p>langeng : {{request.POST.langeng.0}}/{{request.POST.langeng.1}}/{{request.POST.langeng.2}}/{{request.POST.langeng.3}}</p> <p>langjpn : {{request.POST.langjpn.0}}/{{request.POST.langjpn.1}}/{{request.POST.langjpn.2}}/{{request.POST.langjpn.3}}</p> Output Screen We can tell in the request.Post, there are 3 list data langchi, langeng and langjpn. But when I try to read them by request.Post.langchi.0,request.Post.langchi.1... I can not get the actual value. Did I do something wrong? Appreciate for any help. Appreciate for any help. -
Django admin panel CSS files are denied to access to GC bucket
In my Django rest framework project, I have used the filter from django admin panel to filter users This is what I'm using : my codein admin.py based on their profile. This work fine in my local host localhost filtering users Now I'm hosting my project on GCP, once I push to live staging the screen display like this : the panel after pushing to staging . What I got in the console when I go to filter users is console when I use the filter the network tab in condole when I click over one of the error Thanks a lot of any suggestions https://github.com/jschneier/django-storages/issues/454 -
How to get User queryset from his Profile
Good afternoon. I am creating a referral system and at the last stage a question appeared. I need to get request.User and inviting.User querysets for Friends.create.objects(inviting=current_user, invited=inviting_query.user) How i get they? My models Post function -
artichels_pagination.get() missing 1 required positional argument: 'request'
class artichels_pagination(ListView): queryset =models.article.objects.all().order_by('-upload') template_name = 'blog.html' def get(self,request): page_artichel = Paginator(self.queryset, 2) page_number = request.GET.get('page') page_obj = page_artichel.get_page(page_number) render(request,self.template_name,context={'artichel':page_obj}) this is eror: artichels_pagination.get() missing 1 required positional argument: 'request' -
How to create a Standalone Shopify Public App Using Django
I am taking reference from https://github.com/Shopify/sample-django-app. This repository makes an Embedded shopify app. Is there a way to turn this into a standalone shopify app? If this repository can't be turned into an Standalone Shopify app, what are the ways to make a standalone shopify app in Django. I tried surfing the internet to find any solution but there is not any solution that uses Django. Any help would be appreciated. -
how to use json in django
{ "symbol": "GOLD", "rates": [{ "time": "2023.08.02 09:00:00", "open": 1948.75000, "high": 1950.30000, "low": 1947.92000, "close": 1949.57000, "tick_volume": 3342, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 08:00:00", "open": 1946.28000, "high": 1949.90000, "low": 1946.27000, "close": 1948.78000, "tick_volume": 6574, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 07:00:00", "open": 1949.27000, "high": 1949.28000, "low": 1945.18000, "close": 1946.29000, "tick_volume": 3716, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 06:00:00", "open": 1948.18000, "high": 1949.44000, "low": 1946.58000, "close": 1949.27000, "tick_volume": 4494, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 05:00:00", "open": 1947.54000, "high": 1949.80000, "low": 1947.03000, "close": 1948.19000, "tick_volume": 6357, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 04:00:00", "open": 1949.14000, "high": 1949.79000, "low": 1947.58000, "close": 1947.60000, "tick_volume": 6730, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 03:00:00", "open": 1952.12000, "high": 1952.35000, "low": 1948.27000, "close": 1949.17000, "tick_volume": 5801, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 02:00:00", "open": 1951.14000, "high": 1952.80000, "low": 1950.44000, "close": 1952.10000, "tick_volume": 3464, "spread": 0, "real_volume": 0 },{ "time": "2023.08.02 01:00:00", "open": 1947.38000, "high": 1951.78000, "low": 1945.56000, "close": 1951.08000, "tick_volume": 5473, "spread": 0, "real_volume": 0 },{ "time": "2023.08.01 23:00:00", "open": 1944.36000, "high": 1944.82000, "low": 1943.97000, "close": 1944.24000, "tick_volume": 1335, "spread": 0, "real_volume": 0 } ] } This is the data I sent to the background, I named it data … -
Not Found: /static/frontend/styles.css (Docker, Django, Nginx)
I am trying out docker for the first time to deploy in production environment I followed some you- tube tutorials but i was successful in containerizing my Django project. but when i run it nothing appears and i get a 404 error saying not found static/fronted/styles.CSS. Please refer to the attached snippet: error: Here is my Docker file: FROM nikolaik/python-nodejs:python3.8-nodejs14-bullseye ENV PYTHONUNBUFFERED 1 ENV LC_ALL C.UTF-8 ENV LANG C.UTF-8 RUN python3 -m pip install --upgrade pip RUN set -ex && mkdir /app WORKDIR /app # Copy the requirements file and install dependencies COPY d_requirements.txt /app/ RUN pip install -r d_requirements.txt # Copy the application code COPY . /app/ # Create the /opt/ai_sensei_data_source directory and set permissions RUN mkdir /opt/ai_sensei_data_source WORKDIR /opt RUN chmod a+x+w+r ai_sensei_data_source # Copy the .env file to /opt/ai_sensei_data_source/ COPY /.env /opt/ai_sensei_data_source/.env # Change back to the frontend directory to install frontend dependencies WORKDIR /app/frontend # Install frontend dependencies RUN npm install -f RUN npm install -g @angular/cli RUN ng build --configuration production # Copy build static files to nginx conf dir & set permissions RUN mkdir -p /home/kchavan/Desktop/dlops-portal/static RUN cp -r /app/static/* /home/kchavan/Desktop/dlops-portal/static/ # # RUN chown -R <user>:<group> /home/kchavan/Desktop/dlops-portal/ && \ # # chmod -R … -
Can not configure postgres database in GitHub actions pipeline using Docker
I am creating pipeline for my Django Project with GitHub actions and can't make it working correctly. As I use docker, when I start the Docker and start my tests with 'python manage.py test' it works correctly. But when my tests are started I get an error. The reason is probably is that it does not know how to connect to DB, as Docker works with that in my case. I tried to use github secrets, but it seems that it does not work. Here is the traceback in GitHub Actions: Creating test database for alias 'default'... /opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/db/backends/postgresql/base.py:405: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. warnings.warn( Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection self.connect() File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/db/backends/base/base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Found 2 test(s). File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.4/x64/lib/python3.11/site-packages/django/db/backends/postgresql/base.py", line 275, in get_new_connection connection = … -
Semantic-ui multiple How about customizing the display?
I have created a multi-selection dropdown box, but I don't want it to increase by one every time I click on it. I envisioned that it would display no more than three values, and if it did, it would display "4 for 10 selection", is there anything I can do to make this happen? I have tried this method but it gives me an error. //Customize the text that is displayed after multiple selections onLabelCreate: function(value, text) { if ($('.ui.dropdown').dropdown('get value').length > 3) { return '4 of 6 selected'; } } -
Django Form Does Not Validate With Correct Files
class RentalImageForm(forms.Form): images = forms.FileField(validators= [FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png'], message='Only JPG, JPEG, PNG, and GIF files are allowed.')]) @login_required def createListing(request): if request.method == 'POST': createListingForm = RentalForm(request.POST) if request.FILES.getlist('images'): uploaded_files = request.FILES.getlist('images') print(uploaded_files) for files in uploaded_files: rental_image_form = RentalImageForm({'images':files}) if rental_image_form.is_valid(): print('VALID') else: print(rental_image_form.errors) <input type="file" name="images" accept="image/*" required multiple id="id_images" /> _____________________________________________________ I am trying to validate each file I upload to my input and then put them in a loop to verify that all files are in correct extensions. Even when my extensions are all correct my Rental Image Form gives out false when I check with .is_valid(). Overall I have checked and seen that my images files are correctly uploaded but when it comes to validating the form it fails. -
toggle table row based on unchecked checkbox
Not super familiar with frontend, but I have 4 checkboxes I'm using to filter table data. Any number of them can be selected at once. What I want to accomplish: get all unchecked boxes if no boxes are checked pass (meaning don't hide any rows) if a box is checked, for any box that is NOT checked, exclude the row associated with that unchecked box This is for a Django app and the table row id is being generated via database query. The table will have max 100 rows. Per the query I'm executing, any table row will be either: id="audio", id="video", id="writing", id="games" HTML: <div> <input type="checkbox" value="music" id="music_filter"> <input type="checkbox" value="video" id="video_filter"> <input type="checkbox" value="writing" id="writing_filter"> <input type="checkbox" value="games" id="games_filter"> </div> <table class="table"> <thead> <tr> <th>Col 1</th> <th>Col 2</th> </tr> </thead> {% for i in query_set %} <tbody> <tr id="{{i.media_type}}"> <td>{{some data}}</td> <td>{{some other data}}</td> </tr> </tbody> I have jQuery loaded via CDN in the html file and trying this: JQUERY/JS: $(document).ready(function(){ $('#music_filter', '#video_filter', '#writing_filter', '#games_filter').on('click',function(){ var notChecked = $("input:checkbox:not(:checked)"); if (notChecked.length > 0) { for (let i = 0; i < notChecked.length; i++) { $('#i').toggle(); }; }; }); }); A little help to see my mistake(s)? Thanks! -
Django: Auto populate data based on selection
I am trying to create an invoice/PO Form and need some help. I am using 4 models: Client, Shipping, Billing, and PO models. I have the OneToOne relationship between shipping and billing models to the client model and both as foreign keys (please let me know if this method is still ok) in PO model. models.py ClientBillingAddress and ShippingAddress are identical, except "billing" is replaced with "shipping" class ClientBillingAddress(models.Model): client = models.OneToOneField(Client, on_delete=models.CASCADE, related_name='billing_address') billing_location_name = models.CharField(max_length=255, unique=True) address_line_1 = models.CharField(max_length=200, blank=True, null=True) address_line_2 = models.CharField(max_length=100, blank=True, null=True) address_city = models.CharField(max_length=50, blank=True, null=True) address_province = models.CharField(max_length=50, blank=True, null=True) address_postal = models.CharField(max_length=15, blank=True, null=True) address_country = models.CharField(max_length=50, blank=True, null=True) phone = models.CharField(max_length=15, null=True, blank=True) email_to = models.CharField(max_length=150, null=True, blank=True) email_cc = models.CharField(max_length=150, null=True, blank=True) bill_contact_name = models.CharField(null=True, blank=True, max_length=50) is_default = models.BooleanField(default=False) def get_formatted_address(self): address_lines = [self.billing_location_name, self.address_line_1, self.address_line_2] address_city_info = f"{self.address_city}, {self.address_province}, {self.address_postal}" address_lines.append(address_city_info) address_lines.append(self.address_country) return "\n".join(address_lines) def __str__(self): return self.billing_location_name class ClientPO(models.Model): client_PO_number = models.CharField(max_length=50, unique=True) customer_company = models.ForeignKey(Client, on_delete=models.CASCADE, related_name="customer_name_PO") order_reserved_total = models.PositiveBigIntegerField(default=0) order_total = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=Decimal("0.00")) order_line = models.PositiveBigIntegerField(default=0) order_product = models.ForeignKey(InventoryItemDetail, on_delete=models.CASCADE, related_name="order_products") order_qty = models.PositiveBigIntegerField(default=0) order_unit_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=Decimal("0.00")) order_extended_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=Decimal("0.00")) order_units = models.CharField(max_length=10, … -
Reactjst-WebSocket is already in CLOSING or CLOSED state
I created chat system using Django and Reactjs,when i want to send Message then in console give me Error of : WebSocket is already in CLOSING or CLOSED state. my code is let socket = new WebSocket(ServerUrl.WS_BASE_URL + ws/users/${CommonUtil.getUserId()}/chat/); const messageSubmitHandler = (event) =\> { event.preventDefault(); if (inputMessage) { socket.send( JSON.stringify({ action: SocketActions.MESSAGE, message: inputMessage, user: CommonUtil.getUserId(), roomId: CommonUtil.getActiveChatId(match), }) ); } setInputMessage(''); }; \<div className="flex-grow-0 py-3 px-4 border-top"\> \<form onSubmit={messageSubmitHandler}\> \<div className="input-group"\> \<input onChange={(event) =\> setInputMessage(event.target.value)} onKeyUp={chatMessageTypingHandler} value={inputMessage} id="chat-message-input" type="text" className="form-control" placeholder="Type your message" autoComplete="off" /\> \<button id="chat-message-submit" className="btn btn-outline-warning"\> Send \</button\> \</div\> \</form\> \</div\> I search in stackOverflow but there is no Such solution -
Add field in swagger ui using drf-yasg
My code is hosted here. It uses drf-yasg, jwt and the django rest framework. I am trying to set up a patch method to have the user edit his task. The code in a nutshell is as follows def get_payload(request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated!') try: payload = jwt.decode(token, 'secret', algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated!') return payload class TaskView(APIView): pk = openapi.Parameter('pk', openapi.IN_QUERY, description="field you want to order by to", type=openapi.TYPE_INTEGER) @swagger_auto_schema( request_body=openapi.Schema( manual_parameters=[pk], type=openapi.TYPE_OBJECT, properties={ 'taskname': openapi.Schema(type=openapi.TYPE_STRING, description='Add taskname'), 'completion': openapi.Schema(type=openapi.TYPE_BOOLEAN, description='completion'), } ) ) def patch(self, request, pk): payload = get_payload(request=request) task = Tasks.objects.filter(id=pk, username=payload['username']).first() serializer = TaskSerializer(task, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) However, the swagger ui does not display the field for pk. I can see the sample body but the field for pk is missing. How do I add the field for pk here? -
How to change related object when creating object in DRF
I want to change is_available field in Book object when reservation is being create. I found a way which I am pasting here, but this digging in request looks messy, so as it often is with so mature frameworks as drf there are probably better ways to do that. So I have serializer.py class BookSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = BookModel fields = ["number", "title", "author", "is_available"] class ReservationSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = ReservationModel fields = ["reserved_by", "book", "started_at", "valid_until"] And views.py class BookViewSet(viewsets.ModelViewSet): queryset = BookModel.objects.all() serializer_class = BookSerializer permission_classess = [] class ReservationViewSet(viewsets.ModelViewSet): queryset = ReservationModel.objects.all() serializer_class = ReservationSerializer permission_classess = [] def perform_create(self, request, *args, **kwargs): super().perform_create(request, *args, **kwargs) book = BookModel.objects.get(pk=request.data.serializer.instance.book_id) book.is_available = False book.save() I posted what I did, Please teach me do it better - proper way -
How can I assert that a pdf file was returned in python?
I am working on asserting that a pdf is returned from my request. Here is what my test looks like so far. @mock.patch('path.to.class._get_file', return_value=MockResponse(status.HTTP_200_OK, 'application/pdf')) def test_get_should_successfully_return_the_requested_pdf(self, get_file_mock): response = self.client.get(f'/api/v1/path/to/file/abc123.pdf, content_type='application/vnd.api+json') self.assertEqual(response.status_code, status.HTTP_200_OK) # works great self.assertEqual(response['Content-Type'], 'application/pdf') # works great self.assertEqual(response, <abc123.pdf>) # not so great If I do a print to see whats in the response: print(response) <HttpResponse status_code=200, "application/pdf" I am pretty sure I am not setting up the @patch correctly. Specifically, this: status.HTTP_200_OK, 'application/pdf' I've seen a lot of posts about reading or opening files, but I just need to make sure it was in fact a pdf (file) that was returned. How can I set my mock up so that I can assert a pdf (file) was returned? -
How to attach HTMX parameters to a django input form
I am trying to implement an HTMX autosearch function to an input created by a django form. When I inspect the element on the page, the htmx tags are all present. However, the htmx never intializes and it never goes to the views endpoint. The code for the django input form is as follows: widget_attrs_nha_autosearch = { 'class': 'form-control', 'data-user-entry': 1, 'disabled': value.get('read_only'), 'hx-post': "{% url 'ng_django_pmp:nha-autosearch' %}", 'hx-target': '#results', 'hx-trigger': "keyup changed delay:500ms" } if value.get('label') == 'nha_override': self.fields[field] = forms.CharField( initial=value.get('default', ''), label=value.get('label'), max_length=value.get('max_length'), required=required, widget=forms.TextInput(attrs=widget_attrs_nha_autosearch), validators=value.get('validators', [])) When I attempt to create the htmx code on its own in html, it works just fine. However, I need the code to be created in this manner in order to properly trigger something on the backend. The HTMX code on its own is as follows: {% csrf_token %} <div class="d-flex justify-content-end mb-4"> <input type="input" hx-post="{% url 'ng_django_pmp:nha-autosearch' %}" hx-target='#results' hx-trigger="keyup changed delay:500ms" name="search" class="d-flex flex-grow-1 flex-column p-3 border border-secondary rounded m-2" style="overflow: auto; min-width: 0; min-height: 0" placeholder="" id='id_nha_override' /> </div> <div id="results"></div> Am I missing something? -
Deploy Django app as a DigitalOcean's Cloud function?
The Scenario is, I want to deploy my Django application as a PaaS cloud function of the Django application. I have tried to search over the internet but come up with nothing. If this is possible, what will be the complications? Do I need to write the application from scratch again in vanilla Python for deploying it to the Cloud function? -
Django test failes ModuleNotFoundError: No module named 'base' in github actions
i am trying to put down a CI/CD workflow using github action for my project. i have created some test which run fine locally. but on github actions it fails with an error. i have given it the env variables it ask for in the error but still it isn't working link to the repo https://github.com/Suryansh5545/Ticketify. This is the workflow https://github.com/Suryansh5545/Ticketify/actions/runs/5729864155. After fixing this i am gonna try to make workflow to make and export the images from my compose file and then run staging on portainer. Error given by workflow:- ModuleNotFoundError: No module named 'base' ModuleNotFoundError: No module named 'event' It also says about CELERY_BROKER_URL not being a attribute but it is set in both github environment variable and by default if not present in settings. -
How to Save the current user for the created model object in django rest framework
Sorry if I'm asking a noob question. i have this model which used to create a article and the article has a field which associated to the django user model from django.db import models from django.contrib.auth.models import User class Article(models.Model): headline = models.CharField(max_length=150) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateField(auto_now_add=True) pub_time = models.TimeField(auto_now_add=True) # fields need to be added # location # byline -> line tells who writes the article # conclusion # tags def __str__(self): return self.headline i use this django rest framework view to create the object. using postman and giving the author id i can create the article post @api_view(['POST']) def create(request): if request.method == 'POST': serializer = ArticleSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST) what i need to achieve is the only the logged user need to be able to create the article and when the user create the article the author id need to be auto updated at the time the object was created. here is my serializer from rest_framework import serializers from . models import Article class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = '__all__' -
youtube transcript summariser using chrome extension project
In youtube transcript summariser using chrome extension , im getting warning as " This is a development server. Do not use it in a production deployment. Use a production WSGI server instead". im not understanding what to do -
django-channels: Not Found: /ws/
Hi I have typical django app for real-time notifications using websockets Have 2 apps "core" and "notification" I need to show notification on notification page when Review is created. I added channels core and notification to installed apps INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "channels", "core", "notification", ] Added asgi configuration ASGI_APPLICATION = "reviewproject.asgi.application" Configured channel layers CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } Here is asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import notification.routing os.environ.setdefault("DJANGO_SETTINGS_MODULE", "reviewproject.settings") application = ProtocolTypeRouter( { "http": get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter( notification.routing.websocket_urlpattern ) ) } ) I also have routing.py from django.urls import re_path from . import consumers websocket_urlpattern = [ re_path(r'ws/notification/$', consumers.NotificationConsumer.as_asgi()), ] consumer.py import json from channels.generic.websocket import AsyncWebsocketConsumer class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.group_name = "notification" await self.channel_layer.group_add(self.group_name, self.channel_name) await self.accept() async def disconnect(self): await self.channel_layer.group_discard(self.group_name, self.channel_name) async def send_message(self, event): message = event['message'] await self.send(text_data=json.dumps({'message': message})) And sending notification when Review is created class ProductView(View): def send_notification(self, message): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)("notification", {"type": "send_message", "message": message}) def get(self, request, pk): reviews = ReviewModel.objects.filter(product=pk) product = get_object_or_404(ProductModel, pk=pk) context = { "reviews": reviews, "product": product } return render(request, …