Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I hit a Django-allauth login endpoint for automated testing
Context: I am creating some boilerplate automation to essentially login to a website as a restricted user and then verify that when I hit another endpoint, I get an unauthorized response. I don't have much experience with setting up an API automated testing framework from scratch, but I am using Behave and Behave-Django for all other automation. All my test data is coming from a django .env file. My current step to hit the login api as a restricted user is as follows: @given('I log in as a restricted user') def login(context, user): context.url = 'https://myurl.com' context.user_logged_in.send(user) assert context.status_code == 403 I'm pretty green when it comes to django, so if I'm not even close let me know. Thanks! -
GET specific item from table on click in Django MVT
I have a table of products being displayed in my template using jinja loop. ` {% extends 'base.html' %} {% load static %} {% block css %} <link rel="stylesheet" href= "{% static 'css\store.css' %}" > {% endblock %} {%block content%} {% load static %} <div class="secondnav"> <a class="nav-item" href="construction"> Figures </a> <a class="nav-item" href="construction"> Manga </a> <a class="nav-item" href="construction"> Clothes </a> </div> {% for product in products %} <div class="container2"> <div href="item" class= 'product-item'> <div class= 'image-cont'> {# Pass the id of the product to the item view when the user clicks on the product #} <a href="{% url 'item' product.id %}"><img class='product-image'src = '{{product.product_picture.url}}' alt="" ></a> </div> {% if product.offer != 0 %} <div class= 'offer-banner' > {# Pass the id of the product to the item view when the user clicks on the offer banner #} <a href="{% url 'item' product.id %}">Special Offer</a> </div> {% endif %} </div> <div href="item" class="product-content"> <div href="item" class="product-title"> {# Pass the id of the product to the item view when the user clicks on the product title #} <a href="{% url 'item' product.id %}" >{{product.name}}</a> </div> <div class="product-price"> {# Pass the id of the product to the item view when the user … -
IntegrityError at /api/course/ (1048, "Column 'category_id' cannot be null")
Hello everyone i need some help over this issue in Django *IntegrityError at /api/course/ (1048, "Column 'category_id' cannot be null") i got this when i tried to insert a new course * class Course(models.Model): category = models.ForeignKey(CourseCategory, on_delete=models.CASCADE) teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE , related_name='teacher_courses') title = models.CharField(max_length=150) description = models.TextField() featured_img = models.ImageField(upload_to='course_imgs/',null=True) techs = models.TextField(null=True) class Meta: verbose_name_plural = "3. Courses" def related_content(self): related_content=Course.objects.filter(techs__icontains=self.techs) return serializers.serialize('json',related_content) def tech_list(self): tech_list = self.techs.split(',') return tech_list def __str__(self): return self.title class CourseList(generics.ListCreateAPIView): queryset = models.Course.objects.all() serializer_class = CourseSerializer def get_queryset(self): qs = super().get_queryset() if 'result' in self.request.GET: limit = int(self.request.GET['result']) qs = models.Course.objects.all().order_by('-id')[:limit] if 'category' in self.request.GET: category = self.request.GET['category'] qs = models.Course.objects.filter(techs__icontains=category) if 'skill_name' in self.request.GET and 'teacher' in self.request.GET: skill_name = self.request.GET['skill_name'] teacher = self.request.GET['teacher'] teacher = models.Teacher.objects.filter(id=teacher).first() qs = models.Course.objects.filter(techs__icontains=skill_name,teacher=teacher) return qs class CourseSerializer(serializers.ModelSerializer): class Meta: model = models.Course fields =['id','title','description','category_id','teacher','featured_img','techs','course_chapters','related_content','tech_list'] depth=1 I have been searching the solution for hours but i did not get any way to solve the issue and i expect you to help me thank you -
Django many to many model get none
I have been dealing with a project for a few days and today I encountered an error. I wanted to write it here as I have no idea how to solve it. My first model: from django.db import models # Create your models here. class Video(models.Model): title = models.CharField(max_length=100) video_slug = models.SlugField(unique=True) description = models.TextField(max_length=500) image = models.ImageField(upload_to='images/' , blank=True, null=True) video = models.FileField(upload_to='videos/', blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) category = models.ManyToManyField('categories.Category', blank=True) def __str__(self): return self.title def get_absolute_url(self): return "/video/" + self.video_slug class Meta: verbose_name_plural = "Videos" ordering = ['-created_at'] get_latest_by = 'created_at' secondary model: class Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) category_slug = models.SlugField(max_length=100, unique=True) image = models.ImageField(upload_to='category', blank=True, null=True) description = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return "/category/" + self.category_slug class Meta: verbose_name_plural = "categories" ordering = ['name'] and view.py ... class VideoListView(ListAPIView): queryset = Video.objects.all() serializer_class = VideoSerializer When i send get request i got this [ { ... "category": "categories.Category.None", ... } ] What should i do? Please help me. -
Getting field from another model into my custom serializer
I am trying to get 'first_name' and 'last_name' field into my serializer that uses a model which has no user information: This is the serializers.py file: enter image description here This is the models.py file (from django-friendship model): enter image description here I am also attaching views.py: enter image description here -
Why is my else clause not working in Django?
I'm trying to create a search error for my ecommerce website. When a user inputs a search that is not in the database, it should return the search error page. Though it seems my else clause isn't working. I tried putting the else clause in the search.html page, but it keeps giving me errors and it seems when I try to fix the errors, nothing really happens, it stays the same. I expect the search_error.html page to appear when the user inputs a product name that is not in the database. Though I keep getting for example, when I type "hello," the page appears with "Search results for hello." But it should result the search_error.html page. I also tried currently a else clause in my views.py, but it shows the same thing. I think my else clause isn't working and I don't know why. My views.py: def search(request): if 'searched' in request.GET: searched = request.GET['searched'] products = Product.objects.filter(title__icontains=searched) return render(request, 'epharmacyweb/search.html', {'searched': searched, 'products': products}) else: return render(request, 'epharmacyweb/search_error.html') def search_error(request): return render(request, 'epharmacyweb/search_error.html') My urls.py under URLPatterns: path('search/', views.search, name='search'), path('search_error/', views.search_error, name='search_error'), My search.html page: {% if searched %} <div class="pb-3 h3">Search Results for {{ searched }}</div> <div … -
problem initialize django serializer with extra vars to be used in choice field
I have a django serializer like this # urls urlpatterns = [ path("cat", CatView.as_view(), name="cat") ] and # serializers class CatSerializer(serializers.Serializer): name = serializers.ChoiceField(choices=[]) def __init__(self, *args, **kwargs): self.names = kwargs.pop("names") self.fields["name"].choices = self.names super().__init__(self, *args, **kwargs) and views # views class CatView(APIView): def __init__(self, *arg, **kwargs): super().__init__(*arg, **kwargs) self.names = ['a', 'b', 'c'] def get_serializer(self, *args, **kwargs): serializer_class = CatSerializer return serializer_class( *args, **kwargs, names=self.names ) def post(self, request): request_body = request.body serializer = self.get_serializer( data=json.loads(request_body), ) is_data_valid = serializer.is_valid() if is_data_valid: serialized_data = serializer.data return Response({"message": "success", "serialized-data": serialized_data}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is a simplified version of my question. I am trying to dynamically initialize a serializer that has a choice field name and its choices are coming from kwargs passed to the serializer once initialized. if I call OPTIONS method on this class it returns { "name": "Cat", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "name": { "type": "choice", "required": true, "read_only": false, "label": "Name", "choices": [ { "value": "a", "display_name": "a" }, { "value": "b", "display_name": "b" }, { "value": "c", "display_name": "c" } ] } } } } and if I make a … -
I want to change dict content when i clicked button django
Hey guys i have a problem i want to change dict data of python file from html button. I change change data just one time till now. Idk how can i change it when everytime i clicked the button. Django - When button is clicked I want to change the dictionary content Actually i want something like this problem That’s my html file <form action="change/" method="post"> {% csrf_token %} <input type="submit" name = "p1" value = "Program1"> <input type="submit" name = "p1" value = "Program1"><br><br> </form> And that’s the views.py from django.shortcuts import render def index(request): return render(request, "index.html") def change(request): if request.method == 'POST': p1 = request.POST["p1"] p2 = request.POST["p2"] dict = { 'p1': p1, 'p2': p2, } return render(request, 'change.html', dict) -
Lesson() got an unexpected keyword argument 'invoice_number'
I keep failing to save form data in order to pass them into the table to list in admin page. Since I'm fairly new to Django, I don't know what is wrong with my save method in form.py I have tried super().save(commit=False) but I'm not quite sure how to use it. As long as I understand it's used in order to manipulate the data before it's actually saved in the database. I'm not sure if that's the case for me though. Could someone explain why my error occurred and elaborate when to use super.save() and super.save(commit=False)? models.py class Lesson(models.Model): lesson_id = models.AutoField(primary_key=True) lesson_name = models.CharField(max_length=255) student = models.ForeignKey(User,on_delete=models.DO_NOTHING,related_name='studying') teacher = models.ForeignKey(User,on_delete=models.CASCADE, related_name='teaching') start_time = models.DateTimeField(default=timezone.now) interval = models.IntegerField() duration = models.IntegerField() created_at = models.DateTimeField(default=timezone.now, blank=True) updated_at = models.DateTimeField(default=timezone.now, blank=True) is_request = models.BooleanField() number = models.IntegerField(default=-1) price = models.IntegerField(default=-1, blank=True) invoice_number = models.CharField(max_length=10) @property def invoice_number(self): strStudentId = str(self.student_id) strLessonId = str(self.lesson_id) return strStudentId + "-" + strLessonId @property def price(self): return self.duration/5 * self.number forms.py class InvoiceForm(forms.Form): invoice_number = forms.CharField(label="Invoice Number") total_payable = forms.IntegerField(label="Total Payable") def save(self): """Create a new invoice request.""" lesson = Lesson.objects.create( invoice_number = self.cleaned_data.get('invoice_number'), price = self.cleaned_data.get('price'), is_request = False, ) return lesson views.py def invoice(request, … -
'dict' object has no attribute 'model' ISSUE
When I select a date range, I want it to show the number of hard drives saved in the database and the total size of these hard drives in the selected date range. FILTERS.PY class MateryalFiltrele(django_filters.FilterSet): baslangicTarihi = DateFilter(field_name="eklenmeTarihi", lookup_expr="gte", label='') bitisTarihi = DateFilter(field_name="eklenmeTarihi", lookup_expr="lte", label='') class Meta: model = MateryalEkle fields = ('cinsi','materyalBoyut') MODELS.PY class MateryalEkle(models.Model): MATERYALCINSI = [ ('USB', 'USB'), ('HDD', 'HDD'), ] cinsi = models.CharField(max_length=50, choices=MATERYALCINSI) materyalBoyut = models.IntegerField(max_length=5) eklenmeTarihi = DateField(auto_now_add=True) def __str__(self): return self.cinsi VIEWS.PY def istatistik(request): topla = MateryalEkle.objects.filter(cinsi='HDD').aggregate(tumhddtopla=Sum('materyalBoyut')) toplafiltre = MateryalFiltrele(request.GET, queryset=topla) return render(request, 'delil/istatistikler.html', {'toplafiltre':toplafiltre}) HTML <div> {{ toplafiltre.form.baslangicTarihi | as_crispy_field }} {{ toplafiltre.form.bitisTarihi | as_crispy_field }} <button type="submit" ></button> </div> <table class="table mt-5"> <thead> <tr> {% for tekil in hddToplaFiltre.qs %} <th class="ubold text-info ufo60" scope="col">{{tekil.tumhddtopla}}</th> {% endfor %} </tr> </thead> </table> enter image description here -
Django add element to dynamic form
Is there a way to add image element for each input in form? I need to have an image alongside each input from form. I created this sample form and model that works the same way as in my code. The result I'd like to get is this. Sample form code class CreateProfileForm(forms.ModelForm): fieldsets = [ ("Fieldset 1", {'fields': [ 'first_name', 'last_name' ]}), ("Fieldset 2", {'fields': [ 'address', 'phone' ]}), ] class Meta: model = Profile fields = '__all__' Sample model code class Profile(models.Model): # FIELDSET 1 first_name = models.CharField(max_length=50, verbose_name="First name") last_name = models.CharField(max_length=50, verbose_name="Last name") # FIELDSET 2 address = models.CharField(max_length=50, verbose_name="Address") last_name = models.EmailField(verbose_name="Email") The view def create_profile(request): form = CreateProfileForm() return render(request, 'form.html', {'form': form}) The template with the form {% load forms_fieldset static %} <div class="form data-form"> <form> {{ form|fieldset:'#000080' }} <div class="form-group"> <button name="upload" type="submit">Create</button> </div> </form> </div> -
username of the loggedin user is not showing in the profile page
I am doing a project using django where I have two apps. One is users app and another is blog app. Firstly, I used built-in django user model. But later I had to extend the built-in user model to add a new column. users/forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from blog.models import Category User = get_user_model() class UserRegisterForm(UserCreationForm): email = forms.EmailField() categories = Category.objects.all() cid = forms.ModelChoiceField(queryset=categories) class Meta: model = User fields = ['username', 'email', 'password1', 'password2', 'cid'] This is custom user model where I have added a new column cid which a foreign key in a category table. users/model.py from django.db import models from blog.models import Category from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): cid = models.ForeignKey(Category, on_delete=models.CASCADE) However, before implementing the custom user model, what I did that after successfully logging in, users will be able to see their profile page with their username. blog/profile.html {% extends 'users/base.html' %} {% block content %} <h1>{{ user.username }}</h1> {% endblock content %} but after creating the custom user model, when the users go to their profile page after logging in, the username is not displaying. How to solve … -
How to make a scheduled celery task that starts multiple jobs with different params?
I have a celery task like: # Inside tasks.py from .models import Animal @shared_task def process_animals(): animals = Animal.ojbects.filter(age=5) for animal in animals: utils.register_animal(animal) I have a schedule like: # Inside celery.py from celery import Celery from celery.schedules import crontab app = Celery("core") app.conf.beat_schedule = { "runs-every-1-min": { "task": "my_app.core.tasks.process_animals", "schedule": crontab(), }, } There is no reason to process the Animals one at a time, they're all independent. Is it possible to "multiprocess" or "multi-task" this list? -
testdriven.io: The Definitive Guide to Celery and Django. All containers logs are "Waiting for PostgreSQL to become available..."
I've followed each step of part 1 chapter 4 and literally copy pasted the code as shown. docker-compose is able to build the containers but I always get the Waiting for PostgresSQL to become available being logged from all the other containers as shown below. docker-compose logs Following is the output of docker ps -a. From which I can see that all containers are running in their respective ports. docker ps -a logs I checked the docker container logs of the db and it shows to be running. postgres container logs But, I'm unable to open the Django server on port 8010 nor able to view the flower server on port 5557 because in the container logs I'm getting the message "Waiting for PostgreSQL to become available..." Someone please help. This issue is killing me. I've tried to view the logs of each container and it's showing it's running, yet I'm not able to view the Django and flower server. Let me know if you guys need more info. Thanks! Tried checking if the DB is up and running at the correct port. checked if Redis is running. checked the logs of each running container which points to the same … -
Django Crispy Form doesn't add or update database
Hello, I am writing a small project about a car shop and this is the problem I came up with. I'm trying to add a new car and everything seems to work, but when I fill out the form and click submit, it just redirects me to products page without errors and without adding a new car to the database. Here is the code. views.py class AddProductView(View): action = 'Add' template_name = 'myApp/manipulate_product.html' context = { } form_class = ManipulateProductForm def get(self, req, *args, **kwargs): form = self.form_class() self.context['action'] = self.action self.context['form'] = form return render(req, self.template_name, self.context) def post(self, req, *args, **kwargs): form = self.form_class(req.POST or None) if form.is_valid(): form.save() else: print(form.errors) return redirect('products', permanent=True) models.py class Car(models.Model): name = models.CharField(max_length=32) model = models.CharField(max_length=32, unique=True) price = models.IntegerField(validators=[ MinValueValidator(0), ]) def __str__(self): return f'{self.name} {self.model}' forms.py class ManipulateProductForm(forms.ModelForm): def __init__(self, action="Submit", *args, **kwargs): super().__init__(*args, **kwargs) self.action = action self.helper = FormHelper(self) self.helper.add_input(Submit('submit', self.action, css_class='btn btn-primary')) class Meta: model = Car fields = '__all__' manipulate_product.html {% extends 'base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="product-manipulate-container"> {% crispy form form.helper%} </div> {% endblock %} I'm sure the problem is in Crispy, because if … -
Django: One-to-Many and Many-to-One Serializers and Queries
I have a relationship similar to this: One city has one-to-many buildings; one building has zero-to-many devices. The user must be able to request a city by its PK, receiving in response the city, the buildings in the city, and the devices in those buildings. I know that foreign keys are necessary in creating the models, like this: class City(models.Model): #Columns here class Building(models.Model): cityId = models.ForeignKey(City, on_delete=models.CASCADE) #Columns here class Device(models.Model): buildingId = models.ForeignKey(Building, on_delete=models.CASCADE) #Columns here What I'm having trouble with is how to write the serializers and the queries. As of now, my serializers only include fields corresponding to that table's columns: class CitySerializer(serializers.ModelSerializer): class Meta: model = City fields = ['id', ...] class BuildingSerializer(serializers.ModelSerializer): class Meta: model = Building fields = ['id', 'cityId', ...] class DeviceSerializer(serializers.ModelSerializer): class Meta: model = Device fields = ['id', 'buildingId', ...] However, when I have to respond to a GET request for the city, I only know how to use a nested for loops to get the building and device data after finding the city by the inputted ID. I presume there's a better way, but I'm having trouble finding clear answers online. -
Django admin site user password change
Django admin site used to have a form to change the password for a user that wasn't the logged in user. You would look at the user's update page, and by the password field, there was a change password link. You would click it, and it would take you to a different page for changing the password. I used to take advantage of that page to allow changing of a user's password, without having to open the admin. In Django 4, it seems to now be missing. In fact, I can't figure out how one would change a user's password other than their own, without writing my own view. I have 2 questions: Is there a way in the admin site now to change a different user's password? If this view is gone, what is now the best way for a superuser to have a view that can change passwords for a user? -
How to integrate a VueJS (made using vite) project with a Django project?
I cannot find a stackoverflow post regarding this. How can a login/authentication system created as part of a django project take a user to a vue front end project once authenticated/user is logged in? -
How to show category names in the dropdown list of django form
I am working on a article management platform webapp using django. I have created a registration form using the django form where I want to show category names from the category table. This is the code to create category table where I have two column. One is cid which is ID and another one is category_name. Here the category name will be for example: Technology, Software engineering, Medicine etc. blog.models.py from django.db import models # Create your models here. class Category(models.Model): cid = models.AutoField(primary_key=True, blank=True) category_name = models.CharField(max_length=100) def __str__(self): return self.category_name The cid is a foreign key for users table because each user must select a category name from the specialization field to register an account in this app. As I am using built-in user model, so I have added the cid as a foreign key in the user table as given below. users/model.py from django.db import models from blog.models import Category from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): cid = models.ForeignKey(Category, on_delete=models.CASCADE) in the forms.py file I have added the email and specialization field to display them in the registration form like below. However, I am not sure if the category code part is … -
Django site social authentication ERROR | Facebook OAuth - URL blocked error
I am working on a Django web application in which I have to implement social authentication using Facebook (reference - Django 4 By Example). I have installed the required python packages social_django, django_extensions and I am operating the website on https as mentioned in the book. Edited the hosts file of my machine to serve domain name of my choice, in ALLOWED_HOSTS setting added the domain name. I have created the app using Facebook's developers account and have kept the settings as mentioned in the book and added domain name in the required field. In main app's urls.py I have added a path social_auth. I have added the redirect url in Valid OAuth Redirect URIs field. The site is running perfectly on https with custom domain name, but I am getting this error - URL blocked: This redirect failed because the redirect URI is not whitelisted in the app's client OAuth settings. Make sure that the client and web OAuth logins are on and add all your app domains as valid OAuth redirect URIs. I hope the reader understands my problem I have tried to keep it as simple as possible, I am following Django 4 By Example Chapter 5. … -
Django throws Unique constraint failed IntegrityError with OneToOneField. Why?
I have two models, CaracteristiquesGenerales and DataBetweenViews. class CaracteristiquesGenerales(models.Model): utilisateur = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # some other fields ... (no field relating to another model) class DataBetweenViews(models.Model): caracteristiques_generales = models.OneToOneField(CaracteristiquesGenerales,on_delete=models.CASCADE) # some other fields ... (no field relating to another model) And I have a post_save signal. @receiver(post_save, sender=CaracteristiquesGenerales) def etape_1_ok(sender, instance, *args, **kwargs): data_between_views, created = DataBetweenViews.objects.get_or_create(caracteristiques_generales=instance) data_between_views.etape_1 = True data_between_views.save() Because of the signal, Django throws django.db.utils.IntegrityError: UNIQUE constraint failed: general_databetweenviews.caracteristiques_generales_id. I have also tried this : @receiver(post_save, sender=CaracteristiquesGenerales) def etape_1_ok(sender, instance, *args, **kwargs): try: data_between_views = DataBetweenViews.objects.get(caracteristiques_generales=instance) data_between_views.etape_1 = True data_between_views.save() except DataBetweenViews.DoesNotExist: data_between_views = DataBetweenViews.objects.create(caracteristiques_generales=instance) data_between_views.etape_1 = True data_between_views.save() Why is Django not able to create a new DataBetweenViews object since it cannot find it ? -
python sql table with paramter to json
Good Day! I am trying to conver sql query into json with python, but getting an error when try to use sql query with a paramater: sql syntax error: incorrect syntax near "%" it works ok without setting paramater my code def db(db_name="xxx"): return dbapi.connect(address=db_name, port="xx", user="xx", password="123") def query_db(query, args=(), one=False): cur = db().cursor() cur.execute(query, args) r = [dict((cur.description[i][0], value) for i, value in enumerate(row)) for row in cur.fetchall()] cur.connection.close() return (r[0] if r else None) if one else r def test(request): my_query = query_db("select bname, name_text from addrs where num=%s", (100,)) return JsonResponse(my_query, safe=False) urlpatterns = [ path('s4d/', test), ] thanks -
Trouble with heroku logs
When I try opening my app on HerokuHeroku Logs I get an error. Im still new to coding so I'm, not the best at reading what the error means. I have Been trying to go over my code and see what's wrong but I can really see anything obvious... Any pointers I was hoping for the app to launch without any trouble. -
Django - How do you create several model instances at the same time because they are connected
I want to create a user profile and the user profile has a location (address). I need to create the profile first and location second, and then match the profile and the location using a third model called ProfileLocation. I want to do this using one api call, because all the data comes from one form and the location depends on the profile. There is a location model that has OneToOne fields for Country, State and City. The countries, states and cities will have the database tables populated before the time. There is an extra model called ProfileLocation that links the profile to the location. So I have to create all of them at once and struggling with what the best way to do it is. Also what type of DRF view do I use for the endpoint? I need to understand the logic please and I cannot find an example on the net. Do I need to create a custom function based view and run the data through the existing serializers? In that case how can I bundle the incoming data for each specific serializer? This is all very new to me Locations model.py: from django.db import models from … -
Websocket connection not working in Django Channels ('WebSocket connection to 'ws://localhost:8000/ws/board/7/' failed:')
I'm trying to get a websocket running for a Django project I'm working on, but I can't get the websocket to connect, which is strange since I copied the example chat application from. the channels documentation and that worked fine but when I copy-pasted that same code over to my project, it didn't. So, here are the relevant sections of code: the relevant view in views.py def board_view(request, key): board = get_object_or_404(request.user.boards, pk=key) key = dumps(board.pk) return render(request, 'core/board.html', {"board":board, "permission":user_permission, "key":key}) board.html (the relevant part) <script> const key = JSON.parse("{{key|escapejs}}"); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/board/' + key + '/' ); routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"^ws/board/(?P<key>\d+)/$", consumers.ChatConsumer.as_asgi()), ] consumers.py import json from channels.generic.websocket import WebsocketConsumer class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() self.send(text_data=json.dumps({ 'type':'connection_established', 'message':'you are now connected' })) def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json["message"] self.send(text_data=json.dumps({"message": message})) asgi.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sketchboard.settings') django_asgi_app = get_asgi_application() import core.routing application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(core.routing.websocket_urlpatterns)) ), }) settings.py (relevant part): ASGI_APPLICATION = 'sketchboard.asgi.application' and INSTALLED_MY_APPS …