Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django tornado project structure
I am using tornado with django. Right now, my django project structure is like this. project --apps ----accounts ----billing ----roles --settings ----defaults.py ----development.py ----production.py --__init__.py --asgi.py --wsgi.py --urls.py --celery.py manage.py README.md LICENSE requirements.txt .gitignore Where would I likely insert all of tornado related code? Ideally, I would be having a module called tornado somewhere with handlers and the application. For development, I would be running tornado via a management command. -
Djnago Models Design Database
I am new to Django project and wanted to know what is the best practice for designing models. I am working on creating a small project which will have collections of stories in a category and subcategorical manner. I am tagging it as Django because I wanted to also verify the scope of app. Apps: index, genre Design: Index Genre |-- Story |--Section |-- Chapters |--Paragraph |-- title |-- text |-- highlights genre.models.py class Story(models.Model): stry = models.CharField(max_length=256,unique=True) id =models.AutoField(primary_key=True) def __str__(self): return self.stry class Section(models.Model): stry = models.ForeignKey(Story,on_delete=models.CASCADE) name = models.CharField(max_length=256) desc=models.TextField() id =models.AutoField(primary_key=True) slug = models.CharField(max_length=240, null=True, blank=False) created_at = models.DateTimeField(auto_now_add=True, null=False) updated_at = models.DateTimeField(auto_now=True, null=False) class Chapter(models.Model): sec = models.ForeignKey(Section,on_delete=models.CASCADE) name = models.CharField(max_length=256) desc=models.TextField() id =models.AutoField(primary_key=True) slug = models.CharField(max_length=240, null=True, blank=False) created_at = models.DateTimeField(auto_now_add=True, null=False) updated_at = models.DateTimeField(auto_now=True, null=False) class Paragraph(models.Model): chap = models.ForeignKey(Chapter,on_delete=models.CASCADE) title = models.CharField(max_length=120, null=True, blank=False) subtitle = models.CharField(max_length=180, null=True, blank=False) slug = models.CharField(max_length=240, null=True, blank=False) body = models.TextField() created_at = models.DateTimeField(auto_now_add=True, null=False) updated_at = models.DateTimeField(auto_now=True, null=False) The genre can have many stories, and each section can have many chapters and a similar pattern Question: Is there a better design model that I can work on? Can divide these into different apps or have … -
Adding Foreign Key to Django Import Export
I am trying to import data from a csv using Django_Import Export. I saw other SO posts but they are not helping. Below are the models Models.py class TblSubject(amdl.AagamBaseModel): subject_id = models.AutoField(primary_key=True) subject_name = models.CharField(max_length=20) standard = models.ForeignKey('TblStandard', models.DO_NOTHING) remembrance_credit = models.IntegerField(default=40) applied_knowledge_credit = models.IntegerField(default=30) understanding_credit = models.IntegerField(default=30) subject_credit = models.IntegerField(default=100) class Meta: db_table = 'tblsubject' def __str__(self): return f'{self.subject_name}' class SubjectChapter(amdl.AagamBaseModel): subject_chapter_id = models.AutoField(primary_key=True) subject = models.ForeignKey('TblSubject', on_delete=models.CASCADE) chapter_id = models.IntegerField() chapter_name = models.CharField(max_length=150) remembrance_credit = models.IntegerField() applied_knowledge_credit = models.IntegerField() understanding_credit = models.IntegerField() chapter_credit = models.IntegerField() class Meta: db_table = 'subject_chapter' def __str__(self): return f'{self.chapter_id} {self.chapter_name} : {self.subject}' Here is the admin.py from django.contrib import admin from import_export import resources, fields from import_export.widgets import ForeignKeyWidget from .models import SubjectChapter, TblSubject from import_export.admin import ImportExportModelAdmin class SubjectChapterResource(resources.ModelResource): class Meta: model = SubjectChapter import_id_fields = ('subject_chapter_id',) subject = fields.Field( column_name='subject_name', attribute='subject_name', widget=ForeignKeyWidget(TblSubject, 'subject_id')) class SubjectChapterAdmin(ImportExportModelAdmin): resource_class = SubjectChapterResource admin.site.register(SubjectChapter, SubjectChapterAdmin) And i am getting this below error I am inserting data for SUBJECTCHAPTER from csv where the SUBJECT column is a foreign key from TBLSUBJECT and it contains the name of the TBLSUBJECT. -
Not able to insert data from django to sqlite for face detection
def markAttendance(Name,inTime,InDate): #Creating a cursor object using the cursor() method cursor = connect.cursor() sql = '''INSERT INTO markAttendance(Name,inTime,InDate) VALUES(?,?,?)''' #cur = conn.cursor() val=(Name,inTime,InDate) cur.execute(sql,val) (id,Name,str(crTime),str(crDate))) conn.commit() return cur.lastrowid -
Sending text message with friend request
I am building a Simple SocialMedia AND I am stuck on a Problem. What i am trying to do :- I am trying to send message with friend request . Suppose user_1 send a friend request to user_2 with message like "How are You ?". When receiver saw a request is received then also show the message sent my sender. models.py class FriendRequest(models.Model): to_user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='to_user',on_delete=models.CASCADE) from_user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='from_user',on_delete=models.CASCADE) message = models.CharField(max_length=500,default='',null=True) views.py def send_friend_request(request,user_id): user = get_object_or_404(User,id=user_id) frequest,created = FriendRequest.objects.get_or_create(from_user=request.user,to_user=user) if request.method == 'POST': form = FriendRequestMessage(request.POST,request.FILES) if form.is_valid(): new_post = form.save() new_post.request.user = request.user new_post.save() return redirect('mains:settings') else: form = FriendRequestMessage() context = {'form':form} return render(request, 'send_friend_request.html',context) I have tried to search on SO BUT no one asked it before. Any help would be Appreciated. Thank You in Advacnce. -
AJAX data being passed in URL params
I have an AJAX function which is doing some AJAX stuff obviously. Can someone tell me why the data is exposed and not hidden? "GET /policies/?csrfmiddlewaretoken=8ti8IcJ0MF71GjYZghgWqv9YUQEDCzulFvkf8mnCeY2cLchmDHc6IbkTtX9epwAx&title=No+parent&parent=&groups=4&groups=6&groups=7&groups=3 HTTP/1.1" 200 53099 function addCategory(e) { e.preventDefault(); let post_url = '{% url "policies-categories-form" %}' $.ajax({ url: post_url, type:'POST', data: $('#addCategoryForm').serialize(), success: function(response){ console.log(response); // document.getElementById('editCategoriesContainer').innerHTML = data; }, error:function(){ console.log('Error'); }, }); }; Form: {% load crispy_forms_tags %} <!--Add new category form--> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> {{ form.title|as_crispy_field }} </div> </div> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> {{ form.parent|as_crispy_field }} </div> </div> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> {{ form.groups|as_crispy_field }} </div> </div> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> <button class="btn btn-warning btn-block" id="addCategoryBtn" onclick="addCategory(event)" type="button"> <span class="fas fa-plus"></span> Add Category </button> </div> </div> Thanks! -
Heroku CLI: only the RUN cmd is hanging on "connecting"
I'm facing a problem with Heroku CLI 'run' command, basically when I use the run command in any way or form is just hangs on connecting, for example, I have logged in (Heroku) from my Ubuntu machine and I am trying to launch 'bash' to any app on Heroku using "Heroku run bash -a dummy-app-12345" and all I get is "connecting" forever. Originally, I came across this problem when I was trying to push my dockerized Django app to Heroku using the Build Manifest/heroku.yml build approach and that's where I faced the issue originally GitHub Repo: https://github.com/hannody/django_bookstore_project/tree/main/books, now for any app I create on Heroku I get the same issue with the 'run' command. I also tried to follow this tutorial here https://testdriven.io/blog/deploying-django-to-heroku-with-docker/, but I was unable to complete it due to this 'run' command issue. BTW, I get no error messages or any feedback from the Heroku CLI.' I have consulted the web for this problem and found some similar issues where the developers using 'detach' mode to overcome this problem, however, this helped me only to create the database, but when I try to create a superuser it isn't, $ heroku run python manage.py migrate ( works only … -
Django Many2Many field with user
So what I'm trying to do is I'm having two table(class) in my models both of them have many2many field and it's related to user model what I'm trying to do is whatever user i select in my first table I want the users I select in my first table automatically added to the second table without me having to add it manually I tried to override the save_model method in my admin file but still having the same problem Any advice Thanks -
How to authenticate users in Nodejs with Django authentication
I'm using socket io from Nodejs to create a chat feature in my application which is mainly built using React+Django. I need to use Django's user authentication in Nodejs, so that users are authenticated before they can chat with other users. I couldn't really find much on the internet so I came up with the following method, but I don't know if it's the correct way to do this. When the user opens the chat feature, a post request is sent to the Django server containing the user's id and the user is authenticated. After successful authentication, the Django server sends a code to the Nodejs server, and the same code is sent to the user at the client-side. Now, whenever the user sends a message, the codes are compared in the Nodejs server, and if they match, the message is sent. I'm not a pro in web technologies, and I'm pretty sure there are drawbacks using this method so any help would be appreciated! -
ValueError: The view didn't return an HttpResponse object. It returned None instead. (Django/ImgKit)
ValueError: The view didn't return an HttpResponse object. It returned None instead.(Django/ImgKit) I am trying to use a fetch api to connect what the user selects in the frontend to the backend and then return a json response. For whichever html file they select, i want to convert it into an image to be displayed for them to preview Not sure why i am facing this error: def folder_view(request): if request.method == 'POST': if json.loads(request.body)['template'] == 'template': try: folder = json.loads(request.body)['folder'] templates = Template.objects.filter(user=request.user, folder=folder).values('template_name') user_templates=[] for template in templates: config = imgkit.config(wkhtmltoimage=WKHTMLTOPDF_PATH, xvfb='/usr/bin/xvfb-run') html_img = imgkit.from_url(template.html.url, False, config=config) user_templates.append(html_img) return JsonResponse({'user_templates': user_templates }) except Exception as e: print('test') Error seems to be coming from this line: html_img = imgkit.from_url(template.html.url, False, config=config) Once this line is removed, error wont be seen anymore -
Is there a way to set a default value from Microsoft Graph using Forms.Py?
Previously, I attempted to get Username and Email values from Azure AAD using Microsoft Graph. However this was done in a Html form that was done manually and not through forms.py This was the html that was done manually previously: <div> <input id="name" type="text" name="name_field" value = "{{user.name}}" readonly > </div> <div> <input id="email" type="text" name="email_field" value="{{ user.email }}" readonly> </div> Right now I have created in forms.py: class SaveClaimForm(forms.Form): name = forms.CharField(label='Name', max_length=200, disabled=True) email = forms.EmailField(label='Email', disabled=True) Is there a way to set the values of name and email in such a way that it retrieves the required information from Azure AAD -
How to stop refresh after AJAX to Django form
I have a modal where a user can add a new Category. When the user adds a new Category and receives a response from the AJAX request I would like to use the response data to update some of the existing page data. Problem is that my form is not allowing e.preventDefault() but rather just refreshing the page after it receives a response: JQuery AJAX: function addCategory(e) { let post_url = '{% url "policies-categories-form" %}' $.ajax({ url: post_url, type:'POST', data: $('#addCategoryForm').serialize(), success: function(response){ console.log(response); // document.getElementById('editCategoriesContainer').innerHTML = data; }, error:function(){ console.log('Error'); }, }); }; Form (which is loaded using JQuery, only after a user clicks a button: {% load crispy_forms_tags %} <!--Add new category form--> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> {{ form.title|as_crispy_field }} </div> </div> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> {{ form.parent|as_crispy_field }} </div> </div> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> {{ form.groups|as_crispy_field }} </div> </div> <div class="form-row mt-4 mb-4"> <div class="form-group col-md-12 mb-0"> <button class="btn btn-warning btn-block" id="addCategoryBtn" onclick="addCategory(this)" type="submit"> <span class="fas fa-plus"></span> Add Category </button> </div> </div> View: @login_required def policies_categories_form(request): if request.method == 'POST' and request.is_ajax(): form = PoliciesCategoryForm(request.POST, company=request.tenant) if form.is_valid(): form.save() categories = PoliciesAndProceduresCategory.objects.exclude(parent__isnull=False).values() return JsonResponse({'success': True, … -
In Django, can I do the All-In-One Front-end Integration ready (React, Vue) using Webpack like Laravel Does, creating a wrapper for compiling js?
In PHP Laravel for example I can do this without creating a directory for the Front-end stuff and the traditional and recommended way the RESTFul API or GraphQL method stuff for communication between different programming languages just taking advantage of the already included Axios(npm i = npm run dev = node_modules) in Laravel and its built-in API feature via a Route(api.php) for referencing the URI out of the box. The below code snippet is the example the webpack.mix.js(a modified configured Webpack wrapper support specifically for PHP Laravel). const mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel applications. By default, we are compiling the CSS | file for the application as well as bundling up all the JS files. | */ //Additional Custom Configs implementing Typescript for React and its corresponding modules const webpack = require('webpack'); const path = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') // Try the environment variable, otherwise use root const ASSET_PATH = process.env.ASSET_PATH || `{{ asset('') }}` mix.webpackConfig({ entry: path.resolve(__dirname, '.', './resources/js/src/init.tsx'), resolve: { extensions: ['.css', '.tsx', '.ts', '.js'], }, module: { rules: [ { test: /\.(ts|js)x?$/, /* … -
how can i use path Django for locating and loading templates? Django 3.2
in django3.2 I was trying this to uses for locating and loading templates? but doesn't work with me TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ` [BASE_DIR / 'templates']`, } default setting was like : `from pathlib import Path` # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent Any clue of what might be the problem? -
elasticsearch.exceptions.AuthorizationException: AuthorizationException
elasticsearch error: _request self._raise_error(response.status_code, raw_data) File "/Users/soubhagyapradhan/Desktop/upwork/africa/backend/env/lib/python3.8/site-packages/elasticsearch/connection/base.py", line 315, in _raise_error raise HTTP_EXCEPTIONS.get(status_code, TransportError)( elasticsearch.exceptions.AuthorizationException: AuthorizationException(403, '{"message":"The security token included in the request is invalid."}') ERROR 2021-04-28 03:13:17,280 basehttp 2729 123145562267648 "POST /en/signup HTTP/1.1" 500 53 Django code: awsauth = AWS4Auth( os.environ.get("AWS_ES_ACCESS_KEY"), os.environ.get("AWS_ES_SECRET_KEY"), os.environ.get("AWS_ES_REGION"), os.environ.get("AWS_ES_SERVICE"), ) # Elasticsearch configuration ELASTICSEARCH_DSL = { "default": { "hosts": [ {"host": os.environ.get("AWS_ES_URL"), "port": 443}, ], "http_auth": awsauth, "use_ssl": True, "verify_certs": True, "connection_class": RequestsHttpConnection, "request_timeout": 60, } } Here is my code and error shared. My elasticsearch was working fine but, suddenly got this issues. Please let me know how to solve this. Do i need any token for this ? and how to get that -
How to filter queryset for all subcategories
I have a model: class Category(models.Model): title = models.CharField(max_length=127) # Lookups would be as follows: # cat = Category.objects.get(...) # for sub_cat in cat.sub_categories.all(): parent = models.ForeignKey( "self", on_delete=models.CASCADE, related_name="sub_categories") Obviously in templates I can filter for all the subcategories: {% for sub_cat in cat.sub_categories.all %} I would like to pass the queryset of subcategories to the form: self.fields['parent'].queryset = PoliciesAndProceduresCategory.subcategories.all() But this gives the error: AttributeError: type object 'PoliciesAndProceduresCategory' has no attribute 'subcategories' Is there an easy way to filter for this here or do I have to do something such as defining a Model Method? Thanks! -
Starting Django Project
I'm trying to create a django project with "django-admin.exe startproject mysite ." but I keep getting this error: Fatal error in launcher: Unable to create process using '"c:\users\denni\documents\ecommerce\myvenv\scripts\python.exe" "C:\Users\denni\Documents\Ecommerce_Site\myvenv\Scripts\django-admin.exe" startproject mysite .': The system cannot find the file specified. -
Stripe subscriptions checkout.session.completed resource missing error of invalid_request_error type
I am trying to understand why webhook for checkout.session.completed is crashing when testing it locally with the Stripe CLI. I am using djstripe. My webhook for customer.subscription.created is successful. With the CLI, I am getting the following error: Request failed, status=404, body={ "error": { "code": "resource_missing", "doc_url": "https://stripe.com/docs/error-codes/resource-missing", "message": "No such payment_page: 'ppage_1Il33eAyVjQjzOsRERzYQSbK'", "param": "payment_page", "type": "invalid_request_error" } Is the problem with the success url routing? views.py def create_checkout_session(request): """Create a checkout session for Stripe.""" data = json.loads(request.body) priceId = data.get("priceId") if not Price.objects.filter(id=priceId).exists(): messages.add_message(request, messages.ERROR, "That plan price is not available. Please contact support for help.", ) return HttpResponseRedirect(reverse("users:index")) request.account = OrgMembership.objects.filter(my_identity=request.user).first() sessionId = stripegateway.create_checkout_session(priceId, request) return JsonResponse({"sessionId": sessionId}) stripegateway.py class StripeGateway: """Gateway interacts with the APIs required by Stripe. Credit: Matt Layman""" def create_checkout_session(self, priceId, request): """Create a checkout session based on the subscription price.""" site = Site.objects.get_current() subscription_success = reverse("users:success") stripe_cancel = reverse("users:stripe_cancel") request.account = OrgMembership.objects.get(my_identity=request.user.id) request.org = request.account.my_org # session_parameters = { # "customer_email": request.org.billing_email, # "success_url": f"http://{site}{subscription_success}", # "cancel_url": f"https://{site}{stripe_cancel}", # "payment_method_types": ["card"], # "mode": "subscription", # "line_items": [{"price": priceId, "quantity": 1}], # "client_reference_id": str(request.account.id), # } # checkout_session = stripe.checkout.Session.create(**session_parameters) # return checkout_session["id"] checkout_session = stripe.checkout.Session.create( customer_email = request.org.billing_email, client_reference_id = str(request.account.id), payment_method_types=['card'], line_items=[{ … -
Django redirect URL based on the old URL
I have some urls that was originally in the form of uuid:pk when it is referred to specific post, more specifically path('<slug:slug>/post/<uuid:pk>/', views.post_detail, name='post_detail'), However, I've changed the path to include the post title so that it is more intuitive for the end reader path('<slug:slug>/post/<slug:post_slug>', views.post_detail, name='post_detail'), where post_slug is a contactnation of post.pk and post.title as I have override in the models def save(self, *args, **kwargs): if not self.post_slug: self.post_slug = slugify(str(self.title)+str(self.pk)) return super().save(*args, **kwargs) The issue is that i have send some links to some users that contain the old url format. I am wondering how do I redirect them automatically to the new url link. Thanks! -
how to extract a specific value from json format data for object filtering
{"field_summary": {"sex": "None -> Female", "age": "16-> 25", "status": "None -> active"}} The above json data is data stored in json format in sqlite. I would like to filter objects based on this by extracting the text output after the '->' arrow of status. ex) value.filter(summary='active').count() summary is field name. I succeeded in extracting the value with the sql statement. However, it seems to be a separate problem. For filtering -> How should I print the text after the arrow? SELECT substr(json_extract(summary, '$.field_summary.status'), instr(json_extract(summary, '$.field_summary.status'), '->')+3) AS summary FROM table name; -
I want to add username in Coment Viewsets response in DRF
#models.py class Comment(models.Model): listing = models.ForeignKey(Listing, default = 0, on_delete = models.CASCADE) user = models.ForeignKey(User, default = 0,on_delete=models.CASCADE) comment = models.TextField(max_length=100) class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ["listing", "user", 'comment' ] class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['listing'] def create(self, request): print(request.data) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response( status=status.HTTP_201_CREATED) def perform_create(self, serializer): serializer.save(listing= Listing.objects.get(pk=self.request.data['listing']), user= User.objects.get(pk=self.request.data['user'])) ENDPOINT RESPONSE [ { "listing": 1, "user": 1, "comment": "ddd" }, { "listing": 1, "user": 2, "comment": "good" }, { "listing": 1, "user": 1, "comment": "fff" } ] -
Can't sign in admin in django admin site even though superuser does exist
I'm trying to sign in in the admin website with the credentials that I created as superuser. However, I get the error "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive.". Now, I checked in the shell if the user exist and if it is a superuser and it is. Just in case, I changed its password through the shell again to no avail. I'm not sure why it's not working since the superuser does exist. I only have this in the admin.py: from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import User admin.site.register(User, UserAdmin) I've read the other questions about it but none have helped since my settings already have 'django.contrib.auth.backends.ModelBackend' and I've checked on the shell to see that everything's in order. So what's going on? -
how to manage multiple requests at once in django
I want to manage several event at once in django. for example if 10-people click like button of the post , owner of the post will receive one push-notification that say "10 people liked your post", not 10 push-notifications for each clicks. i can't get a any point to handling this. could somebody help this problem? -
Why does html disappar when trying to iterate using for loop in django
I am having an issue where I have categories for each product, so for my URLs, i have slugs referencing to each category. in the href on my frontpage (HTML pasted down below). I see that when I load the portion of the HTML that has the for loop applied makes it disappear. I have never run into this. Does anybody have any idea what's going on? I'll post the relevant div where this is occurring. I can post additional code if needed. Thanks In this case, the Get covered now button is missing {% extends 'base.html' %} {% block content %} {% load static %} <div id="signup"> {% for category in menu_categories %} <a class="btn btn-lg col-sm-12 slideanim" id="title" href="{% url 'category_detail' category.slug %}"> Get Covered Now! </a> {% endfor %} <a class="btn btn-lg col-sm-12 slideanim" id="title" href="#"> Learn More! </a> </div> -
How to properly end a background Celery worker in Django tests
I need to run a background Celery worker during some Django integration tests. I used the solution proposed here, and everything works fine. However, when running all my tests (which takes a while), I start getting the following error message: [2021-04-27 18:42:41,401: ERROR/MainProcess] Error in timer: AttributeError("'NoneType' object has no attribute 'heartbeat_tick'") Traceback (most recent call last): File "/home/user/.local/lib/python3.7/site-packages/kombu/asynchronous/hub.py", line 145, in fire_timers entry() File "/home/user/.local/lib/python3.7/site-packages/kombu/asynchronous/timer.py", line 68, in __call__ return self.fun(*self.args, **self.kwargs) File "/home/user/.local/lib/python3.7/site-packages/kombu/asynchronous/timer.py", line 130, in _reschedules return fun(*args, **kwargs) File "/home/user/.local/lib/python3.7/site-packages/kombu/connection.py", line 312, in heartbeat_check return self.transport.heartbeat_check(self.connection, rate=rate) File "/home/user/.local/lib/python3.7/site-packages/kombu/transport/pyamqp.py", line 149, in heartbeat_check return connection.heartbeat_tick(rate=rate) AttributeError: 'NoneType' object has no attribute 'heartbeat_tick' It seems that this is caused by trying to send a heartbeat from workers that have been ended. I have searched around and could not find how to end workers more cleanly. Here is a minimal failing example: import time import socket import selenium from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from django.contrib.staticfiles.testing import StaticLiveServerTestCase from celery.contrib.testing.worker import start_worker from celery.contrib.abortable import AbortableAsyncResult from myproject.celery import app from frontend import tasks docker = False # Same result with Docker class TestServer(StaticLiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.host = socket.gethostbyname(socket.gethostname()) if …