Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is multi-tenant architecture in Django web development?
I have been working on website development in Django with multi-tenant architecture. I have searched many reference online but not able to find any satisfactory answer. What is multi-tenant architecture & how could I use it in my Django website. -
Django 2.2 - Testing response context with assertQuerySetEqual fails
Trying to test response context in Django TestCase with assertQuerysetEqualbut it fails. I tried printing count of Country.objects.all().count() and response.context['countries'].count(). both returns 1 as I create one record at start of the test. Also tried ordered=True on assertion method but no luck still fails the test. Am I missing something or need do it other way? View that returns response class CountriesListView(generic.ListView): model = Country template_name = 'management/countries/countries.html' context_object_name = 'countries' Test using class CountryTest(TestCase): def setUp(self): self.countries_list_url = '/countries' def test_response_returns_countries_context(self): Country.objects.create( name='India', iso_3166_1='IN' ) response = self.client.get(self.countries_list_url) self.assertQuerysetEqual(Country.objects.all(), response.context['countries']) Error I'm getting AssertionError: Lists differ: ['<Country: Country object (1)>'] != [<Country: Country object (1)>] First differing element 0: '<Country: Country object (1)>' <Country: Country object (1)> - ['<Country: Country object (1)>'] ? - - + [<Country: Country object (1)>] -
django rest frame work show all apis in homepage
i am having a django project with 2 apps first called facility and the other called booking and my structure looks like below : now in my urls if u see i can only show booking or facility in my home page api root like below : now i want to know what should i write in my urls.py to list all apis in root api and see them all here !!! -
What are the uses and benifits of get_quert_set() and get_context_data()? Can we use both of them together inside a view?
I was going through Django documentations and I encountered two methods of showing object's data. I am wondering if we can use both get_query_set() and get_context_data inside a single view. For example if I have 3 models named Publisher, Books, Author where Books and Author are related to each other with ManyToMany field and Books and Publisher are related via ForeignKey. There is a view template_name='some_name.html' There are 2 methods of showing data via getting the objects. self.Publisher=get_object_or_404(Publisher,name=self.kwargs('name_of_publisher') return Books.objects.filter(publisher=self.publisher) I think it will return all the Book objects that are related to name_of_publisher. I want to ask how the data will be displayed? Will there be a loop in templates? How will the Url look like and if there is no context defined then how will it show data? 2nd method I came across is def get_context_data(self,**kwargs): context=super().get_context_data(**kwargs) context['publisher']=self.publisher return context I found the working of this one very confusing. I am unable to understand how is this working here. I have read another posts too here just in case you'll try to give me a link. Thanks for that in advance. But what I know is can both of these be used inside a single template and ListView? … -
How can I insert file object in xlsx sheet with python?
I have an app which will download an excel file on button click.I have a FileField stored in the database which i would like to insert in that .xlsx file so that it appears as an icon. I have tried using xlsxwriter and openpyxl libraries and I dont think they can insert objects.If you know any other library for the job That'll be helpful. class SearchView(View): def WriteToExcel(self,item): output = io.BytesIO() **workbook = xlsxwriter.Workbook(output)**; worksheet_s=workbook.add_worksheet("Reports") header = workbook.add_format({ #some format }) worksheet_s.write('A1', "Date",header) #Some Headings worksheet_s.write('E1', "Attachment",header) row = 1 for data in item: worksheet_s.write(row, 0, data.date) #Write stuff **worksheet_s.write(row, 4,data.document)**#Here I want the file to be inserted as an icon row += 1 workbook.close() xlsx_data = output.getvalue() return xlsx_data def post(self,request): response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=Report.xlsx' xlsx_data = self.WriteToExcel(item) response.write(xlsx_data) return response -
How to pass data for OneToOneField when testing?
I've a signupView that shows 2 forms: SignUpForm and ProfileForm. Basically SignUpForm collects data like first_name, last_name, user_name, email, password1, password2. And ProfileForm collects data like dni, birthdate, shipping_address, etc. I'm testing the ProfileForm but I don't know how to pass the information for the user field of the Profile Model, is is a OneToOneField to the User model. models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthdate = models.DateField(null=True, blank=True) dni = models.CharField(max_length=30, blank=True) phone_number = models.CharField(max_length=30, blank=True) shipping_address1 = models.CharField(max_length=100, blank=False) reference = models.CharField(max_length=100, blank=False) shipping_department = models.CharField(max_length=100, blank=False) shipping_province = models.CharField(max_length=100, blank=False) shipping_district = models.CharField(max_length=100, blank=False) photo = models.ImageField(upload_to='profile_pics', default='profile_pics/default_profile_pic_white.png') def __str__(self): return str(self.user.first_name) + "'s profile" test_forms.py: from django.test import TestCase from django.utils import timezone from django.urls import reverse from shop.forms import SignUpForm, ProfileForm import datetime #coverage run manage.py test shop/tests -v 2 class SignUpFormTest(TestCase): def test_signup_form(self): form_data = {'first_name': 'oma', 'last_name': 'gonza', 'username': 'omagonza', 'email': 'oma.gonzales@gmail.com', 'password1': 'caballo123', 'password2': 'caballo123'} form = SignUpForm(data=form_data) self.assertTrue(form.is_valid()) def test_profile_form(self): district_list = 'Lima' province_list = 'Lima' department_list = 'Lima' form_data = {'user': #¿?¿?¿? 'dni': 454545, 'phone_number': 96959495, 'birthdate': datetime.datetime.now(), 'shipping_address1': 'Urb. Los Leones', 'shipping_address2': 'Colegio X', 'shipping_department': 'Lima', 'shipping_province': 'Lima', 'shipping_province': 'Ate'} form = ProfileForm(district_list=district_list, province_list=province_list, department_list=department_list, data=form_data) self.assertTrue(form.is_valid()) AttributeError: … -
manage.py test: error: argument -v/--verbosity: expected one argument
I'm learning testing. I want to test a SignupForm I have, and for that I'm using the package coverage. However, when running: coverage run manage.py test shop/tests -v I get: $ coverage run manage.py test shop/tests -v usage: manage.py test [-h] [--noinput] [--failfast] [--testrunner TESTRUNNER] [-t TOP_LEVEL] [-p PATTERN] [-k] [-r] [--debug-mode] [-d] [--parallel [N]] [--tag TAGS] [--exclude-tag EXCLUDE_TAGS] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [test_label [test_label ...]] manage.py test: error: argument -v/--verbosity: expected one argument (stickers-gallito-app) shop/tests/test_forms.py: from django.test import TestCase from django.utils import timezone from django.urls import reverse from shop.forms import SignUpForm #coverage run manage.py test shop/tests -v class SignUpFormTest(TestCase): def test_signup_form(self): form_data = {'first_name': 'oma', 'last_name': 'gonza', 'username': 'omagonza', 'email': 'oma.gonzales@gmail.com', 'password1': 'caballo123', 'password2': 'caballo123'} form = SignUpForm(data=form_data) self.assertTrue(form.is_valid()) shop/forms.py: class SignUpForm(UserCreationForm): error_messages = { 'password_mismatch': "Las contraseñas no coinciden.", } first_name = forms.CharField(label="Nombre", max_length=100, required=True) last_name = forms.CharField(label='Apellido', max_length=100, required=True) username = forms.CharField(label='Nombre de usuario', max_length=100, required=True, error_messages={'invalid': "you custom error message"}) email = forms.EmailField(label='Correo electrónico', max_length=60, required=True) password1 = forms.CharField(label='Contraseña', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirmar contraseña', widget=forms.PasswordInput) def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) for fieldname in ['username', 'password1', 'password2']: self.fields[fieldname].help_text = None def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if … -
Newbie to Github: how to view work in progress
I'm pretty new to coding, so am trying to explore and learn as much as possible. I've been playing around with Github and exploring some more complex repos (the team is using Django and React) - how can you load this more complex code to see a work in progress? For HTML and CSS I understand how you can load a work in progress and see how things are going, but I'm completely lost with these more robust repos with a lot of different languages and files going on. I tried downloading the repo and just reading through the code, and just tried playing around to see if I can load the website, but nothing was working... -
AttributeError at /registration/list/ 'str' object has no attribute 'get'
I want to display the records from the table on the basis of the municipality login but it gives me the above error.Would someone please tell me how to fix it? Thank you. views.py class ListRegistration(LoginRequiredMixin, FilterView): model = models.NewRegistration template_name = 'registration_list.html' context_object_name = 'registrations' paginate_by = 10 def get_queryset(self): user_id=self.request.user.id profile_qs = Profile.objects.filter(id=user_id).values_list("user_id", flat=True) p_m=Profile.objects.filter(id=profile_qs).values_list("municipality",flat=True) all=Profile.objects.filter(municipality=p_m).values_list("user_id",flat=True) return models.NewRegistration.objects.filter(is_forwarded=False,user_id__in=all).order_by('-id') registration.html {% with registration.get_overall_registration_status as reg_status %} {% if reg_status|get_item:"iscomplete" %} <td> <div class="btn btn-success">Completed</div> </td> {% elif reg_status|get_item:"ispartial" %} <td> <div class="dropdown status-registration noborder"> <button class="btn btn-warning" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Partial</button> <div class="dropdown-menu"> {% with registration.get_initial_registration_status.iteritems as statuses %} {% for x,y in statuses %} <span style="display: block; margin-bottom: 2px;" class="dropdown-item glyphicon {% if y %} glyphicon-ok alert-success {% else %} glyphicon-remove alert-danger {% endif %}"> {[{ '{{ x }}' | translate_detail_registration_level }]}</span> {% endfor %} {% endwith %} </div> </div> </td> {% else %} <td> <div class="btn btn-danger">Noinfo</div> </td> {% endif %} {% endwith %} -
How I can store images in Database by using url to images
My problem is that I want to store images in database, but I don't want to store them physically in my project as static files, I want to save in database url to images which are already uploaded somewhere in Internet. How can I do this, just use CharField or TextField as type of field and paste url? But I also want later to display this photo in my template. class Image(models.Model): name = models.CharField(max_length=25, verbose_name='Image name') image_file = def __str__(self): return self.name -
How do I continue working on an existing django project from my laptop?
I created a django project in pycharm from my desktop computer. Now that I want to work on that same project from my laptop I'm not able to do so. What are the commands to be written in the terminal for continuing the project in pycharm from my laptop? (how do I work in that existing virtual environment and run the server now?) -
Can't dynamically create path with upload_to
In my user model, I have an ImageField that contains an upload_to attribute that will create the image path dynamically based on the user's id. avatar = models.ImageField(storage=OverwriteStorage(), upload_to=create_user_image_path) def create_user_image_path(instance, image_name): image_name = str(instance.user.id) + image_name[-4:] return 'users/{0}/avatars/{1}'.format(instance.user.id, image_name) When I sign up, I get an error that looks like this: The system cannot find the path specified: 'C:\Users\xx\PycharmProjects\project_name\media\users\150\avatars' If I remove the id and avatars and just include the image name (with no new directories) it works successfully and writes the image. I have tried doing chmod -R 777 on this directory, but it still doesn't create these new directories dynamically. I'm not sure what I'm doing wrong. -
Serialize nested object as flat attributes of current parent object
I've model A and model B, model B is child of model A. I've implemented a ModelSerializer for my model A object and I need to represent all attributes of related model B as attributes (properties) of model A. How can I do that with Django Rest Framework? Thank you -
Django got an unexpected keyword argument while I'm making register page
I'm trying to make a register page in Django and got TypeError TypeError at /impassionuser/register/ Impassionuser() got an unexpected keyword argument 'useremail' Exception Type: TypeError Exception Value: Impassionuser() got an unexpected keyword argument 'useremail' Python Version: 3.7.2 Python Path: ['/Users/subin/Desktop/Django/3rd/impassion_community', '/Users/subin/Desktop/Django/3rd/impassion_venv/lib/python37.zip', '/Users/subin/Desktop/Django/3rd/impassion_venv/lib/python3.7', '/Users/subin/Desktop/Django/3rd/impassion_venv/lib/python3.7/lib-dynload', '/usr/local/var/pyenv/versions/3.7.2/lib/python3.7', '/Users/subin/Desktop/Django/3rd/impassion_venv/lib/python3.7/site-packages'] Server time: Sat, 22 Jun 2019 23:36:07 +0000 I added everything, but got this error and don't know what to do about it. why I got this problem? from register.html <div class="form-group"> <label for="useremail">사용자 이메일</label> <input type="email" class="form-control" id="useremail" placeholder="사용자 이메일" name="useremail"> </div> class Impassionuser(models.Model): username=models.CharField(max_length=64, verbose_name='사용자명') useremail=models.EmailField(max_length=128, verbose_name='사용자이메일') password=models.CharField(max_length=64, verbose_name='비밀번호') registered_dttm=models.DateTimeField(auto_now_add=True, verbose_name='등록시간') from views.py request.method == 'POST': username = request.POST.get('username', None) useremail = request.POST.get('useremail', None) password = request.POST.get('password', None) re_password = request.POST.get('re-password', None) res_data={} if not (username and useremail and password and re_password): res_data['error'] = '모든 값을 입력해야합니다.' elif password != re_password: res_data['error'] = '비밀번호가 다릅니다.' else: impassionuser = Impassionuser( username=username, useremail=useremail, password=make_password(password) ) impassionuser.save() -
How to make django admin logo dynamic?
i'm using django-cms admin style, here i had managed to change the default DjangoCMS logo, by following the solution mentioned here: Django cms 3.4.1 admin dlogo now the logo is a static one, i want it to be dynamic, means it should get the image path from the Database, where the location is stored. As these admin pages are not render through views.py, so i'm not able to sent the querysets to it. can anyone suggest, how to do it? -
Validate two inline models in the Django admin
I have three models that look like this (simplified from the actual models): class LayoutPage(models.Model): name = models.CharField(max_length=190, unique=True) height = models.DecimalField(max_digits=10, decimal_places=4) width = models.DecimalField(max_digits=10, decimal_places=4) class PageImage(models.Model): page = models.ForeignKey(LayoutPage) name = models.CharField(max_length=150) class Meta: unique_together = ('page', 'name') class PageText(models.Model): page = models.ForeignKey(LayoutPage) name = models.CharField(max_length=150) class Meta: unique_together = ('page', 'name') My admin definitions look like this: class PageImageInline(admin.TabularInline): model = PageImage form = PageImageForm class PageTextInline(admin.TabularInline): model = PageText form = PageTextForm class LayoutPageAdmin(admin.ModelAdmin): inlines = [LayoutImageInline, LayoutTextInline] And my forms look like this: class PageImageForm(forms.ModelForm): def clean(self): cleaned_data = super(PageImageForm, self).clean() page = cleaned_data.get('page') name = cleaned_data.get('name') if page.pagetext_set.filter(name=name).exists(): self.add_error('name', forms.ValidationError(_('Cannot be the same name as an existing layout text on the page'), code='name_conflict')) class PageTextForm(forms.ModelForm): def clean(self): cleaned_data = super(PageTextForm, self).clean() page = cleaned_data.get('page') name = cleaned_data.get('name') if page.pageimage_set.filter(name=name).exists(): self.add_error('name', forms.ValidationError(_('Cannot be the same name as an existing layout image on the page'), code='name_conflict')) This accomplishes two of the three things I need. 1) For each page, no two images can have the same name, and no two texts can have the same name. 2) When editing a page in the admin, you cannot rename an image to have the same name as … -
How do I properly import templates from HTML5 UP into django
Im trying to upload templates from HTLM5 UP into the Django framework. However I'm not sure where to place some of the supporting CSS, SASS, Webfonts, Javascript files. Link to the template I downloaded below. Files I'm referring to are in the "Assets" folder. https://html5up.net/strata I've tried placing them in the path below. I'm using the Pycharm IDE if that changes anything. ProjectName/mysite/templates/mysite/assets I've been trying to call them with href="mysite/assets/css/main.css" with no success. -
Doesn't show the video for some reason
I have a model of where the user can choose the title of their video and can upload the video but for some reason when I try to display the video in the html and I visit that page it does a GET request on the file but the file doesn't include .mp4 on the end so it doesn't work. Tried a few things but I can't remember what exactly since it was a few days ago and none of them worked. My models.py: # Create your models here. class Video(models.Model): title = models.CharField(max_length=40, blank=False) video_file = models.FileField(name="Upload a mp4 file", upload_to=f"uploadvideos/video", validators=[FileExtensionValidator(['mp4'])], blank=False) def __str__(self): return self.title My views.py: def movie(request, movie_id): video = get_object_or_404(Video, title=movie_id) context = {'video': video} return render(request, template_name=f'uploadvideos/movie.html', context=context) My html template: </head> <body> <h1 class="movietitle">{{ movie }}</h1> <div class="videoDetails"> <video width="700" height="430" controls> <source src="{{ idk what to put here }}" type="video/mp4"> </video> </div> </body> </html> -
How to calculate the total after applying discount in Django?
I want to calculate the total amount after applying the discount. For that i have made cart.py. But when i call the functions from cart.py in templates.html. It neither display the total amount after discount nor the discounted percentage. cart.py created in cart app from decimal import Decimal from django.conf import settings from shop.models import Product from coupons.models import Coupons class Cart(object): def __len__(self): return sum(item['quantity'] for item in self.cart.values()) def get_total_price(self): return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()) def clear(self): del self.session[settings.CART_SESSION_ID] self.session.modified = True @property def coupon(self): if self.coupon_id: return Coupons.objects.get(id=self.coupon_id) def get_discount(self): if self.coupon: return (self.coupon.discount / Decimal('100')) * self.get_total_price() def get_total_price_after_discount(self): return self.get_total_price() - self.get_discount() template.html <tr class="gray2"> <td colspan="2"> coupon ({{discount}}) % off</td> <td colspan="3"></td> <td class="num neg"> {{cart.get_discount|floatformat:"2"}}</td> </tr> <tr class="total"> <td>Total</td> <td colspan="4"></td> <td class="num">{{cart.get_total_price_after_discount|floatformat:"2"}}</td> </tr> </table> <div class="divo"> <p> coupon code to apply discount </p> <form action="{% url 'coupons:apply' %}" method="post"> {{coupon_apply_form}} {% csrf_token %} <input type="submit" value="apply" class="btn"> </form> </div> views.py @require_POST def coupon_apply(request): now = timezone.now() form = CouponApplyForm(request.POST) if form.is_valid(): code = form.cleaned_data['code'] try: coupon = Coupons.objects.get(code__iexact=code, valid_form__lte=now, valid_to__gte=now, active=True) request.session['coupon_id'] = coupon.id except Coupons.DoesNotExist: request.session['coupon_id'] = None return HttpResponseRedirect(reverse("cart")) This portion of template.html is not displaying. Please … -
Extend admin page for users from specific groups with custom html and js
I need to implement moderator functionality and the builtin django admin suffices except I need additional form to send some data and receive result from an API endpoint. What's the easiest way to do this. Do I need to create middleware to catch requests from the specified user and return extended versions? -
ManyToMany field returns None despite having a value
I have 2 classes: categories and pizzas. One of them is a list of categories for the object and another one is the object. Problem is, when I call an object, I can see all the fields except that ManyToMany field returns catalog.Category.None instead of the assigned value. Here is my models.py: class Category(models.Model): CLASSIC = 'Classic' VEGETARIAN = 'Vegetarian' SPICY = 'Spicy' TYPE = [ (CLASSIC, 'Classic'), (VEGETARIAN, 'Vegetarian'), (SPICY, 'Spicy') ] type = models.CharField( max_length=100, choices=TYPE ) def __str__(self): return self.type class Meta: verbose_name_plural = 'Categories' class Pizza(models.Model): name = models.CharField(max_length=100) price = models.IntegerField() size = models.OneToOneField( Size, on_delete=models.CASCADE, primary_key=True ) category = models.ManyToManyField(Category) def __str__(self): return f"name = {self.name}, size = {self.size}, category = {self.category}" And here is my shell output: >>> from catalog.models import Pizza >>> from catalog.models import Category >>> pizza = Pizza.objects.all() >>> pizza <QuerySet [<Pizza: name = Chicken, prices = 8, 10, category = catalog.Category.None>, <Pizza: name = Pepperoni, prices = 8, 12, category = catalog.Category.None>, <Pizza: name = Mushroom, prices = 7, 9, category = catalog.Category.None>]> >>> cat = Category.objects.filter(pizza=1) >>> cat <QuerySet [<Category: Classic>]> >>> cat = Category.objects.filter(pizza=2) >>> cat <QuerySet [<Category: Classic>, <Category: Spicy>]> -
How to make QuerySet JSON serializable?
I have a problem with creating a new object in my Rest Framework. As much I as understand, when I tried to overwrite item's field so it could have all the items that are in my database. I thought, that this would work, and it showed me the working page and I could choose an item. But when I tried to post it to create a new object, it said "Object of type 'Item' is not JSON serializable" I was trying to figure it out, how to convert Item.objects.all() into JSON data. But nothing helped me. I understand, that this isn't really hard to do, but I can't figure it out on my own. So I ask for your help, how to solve this problem? Here's my serializer from rest_framework import serializers from items.models import OrderItem, Item class OrderItemSerializer(serializers.ModelSerializer): item = serializers.ChoiceField(choices=Item.objects.all()) class Meta: model = OrderItem fields = ('item', 'size', 'quantity', 'id') -
Django - using 1-1 relationship method to create two different user profiles, same authentication
I have a Django project in which I have currently used the default user authentication process, and extended it to allow for user profiles. I now want to create profiles for two different types of users, e.g. User type 1: = WP. User type 2: = W. I have looked at some of the suggested solutions but wanted some specific guidance on my particular scenario and code. As I understand it, there are three ways of attempting to do this 1. Proxy Model 2. 1-1 Relationship Method 3. Custom User Model. I want to use option #2 - 1-1 Relationship Method and avoid the other two, with the objective being to a) allow users to log in b) allow a user to specify if they are user type 1 (WP) or user type 2 (W) c) If a user is user type 1 (WP) they are directed to a WP profile, and if a user is user type 2 (W) they are directed to user type 2 (W) profile. I currently have this in my models.py (for users) from django.db import models from django.contrib.auth.models import User from PIL import Image from django import forms class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) … -
Accessing containerized Django app from ECS public IPv4 endpoint
I have a dockerized django app that is stored in ECR. When I set-up a new ECS cluster (using Fargate), this image loads correctly and I can see the logs in Cloudwatch: 20:12:21 Operations to perform: 20:12:21 Apply all migrations: admin, auth, contenttypes, sessions 20:12:21 Running migrations: 20:12:21 No migrations to apply. 20:12:23 No changes detected 20:12:25 Watching for file changes with StatReloader 20:12:25 Performing system checks... 20:12:25 System check identified no issues (0 silenced). 20:12:26 June 22, 2019 - 20:12:26 20:12:26 Django version 2.2.2, using settings 'config.settings' 20:12:26 Starting development server at http://127.0.0.1:8000/ 20:12:26 Quit the server with CONTROL-C. but when I got to the public ipv4 listed under the task network details, and go to :8000 in my browser, nothing loads and I dont see any requests going to the server in the container in cloud watch. I'm wondering if the issue is related to using: python manage.py runserver 0.0.0.0:8000 in my container set-up. Alternatively, a setting in the security group, etc. But i've allowed inbound traffic to 127.0.0.1 & 0.0.0.0 port 8000 inside the settings there already. I'm somewhat at a loss as I've looked around at a variety of documentation and I seem to have my … -
How can I make my django channels websocket server work over ssl?
I'm setting up a web application that has a chatroom system. I originally followed the tutorial here: https://channels.readthedocs.io/en/latest/tutorial/index.html It worked flawlessly in development, but I had to use daphne to get it to work when I deployed the app because I'm using apache. sudo daphne -b 0.0.0.0 -p 81 myapp.asgi:application But when I used certbot to get ssl certificates for https, I started getting the following console errors whenever I try to send a message: Mixed Content: The page at: https://example.com/home/chat/46508f6fc17b04ad04ba0e8e5095e4b233944ed3d4145e5501ada21bab7042c6/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://example.com:81/ws/chat/46508f6fc17b04ad04ba0e8e5095e4b233944ed3d4145e5501ada21bab7042c6/'. This request has been blocked; this endpoint must be available over WSS. My first thought was to change the javascript in room.html from this: var chatSocket = new WebSocket( 'ws://' + window.location.host + ':81/ws/chat/' + roomName + '/'); to this: var chatSocket = new WebSocket( 'wss://' + window.location.host + ':81/ws/chat/' + roomName + '/'); this did not work and resulted in the following error when I try to send a message: (index):150 Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. mysite-le-ssl.config: <VirtualHost *:443> ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/me/myproject/myapp> <Files wsgi.py> Require all granted …