Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
sort and search functionality not working together
i have the following search and sort functions in my javascript file and the following html file Javascript file document.addEventListener('DOMContentLoaded', function () { const csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0]?.value; const resultsListFW = document.getElementById('list-results-fw'); const listFW = document.getElementById('list-fw'); const searchInputFW = document.getElementById('search-input-fw'); function renderFWData(data) { resultsListFW.innerHTML = ''; // Clear previous results let counter = 1; data.forEach(item => { const row = ` <tr> <td>${counter}</td> <td>${item.customer}</td> <td><a href="detail/${item.pk}" target="_blank">${item.name}</a></td> </tr> `; resultsListFW.insertAdjacentHTML('beforeend', row); counter++; }); listFW.classList.add('not-visible'); resultsListFW.classList.remove('not-visible'); } // FW: Perform search function performFWSearch(query) { fetch('/fw_search', { method: 'POST', headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded', 'X-CSRFToken': csrfToken }, body: new URLSearchParams({ fw: query }) }) .then(response => response.json()) .then(data => { renderFWData(data.data); }) .catch(error => { console.log('Error fetching FW data:', error); }); } }); document.addEventListener('DOMContentLoaded', () => { const table = document.getElementById('fw-table'); const headers = table.querySelectorAll('th[data-sort]'); const tbody = table.querySelector('tbody'); headers.forEach(header => { header.addEventListener('click', () => { const sortKey = header.getAttribute('data-sort'); const rows = Array.from(tbody.querySelectorAll('tr')); // Determine sorting order const order = header.dataset.order === 'asc' ? 'desc' : 'asc'; header.dataset.order = order; // Sort rows rows.sort((a, b) => { const aText = a.querySelector(`td:nth-child(${header.cellIndex + 1})`).textContent.trim(); const bText = b.querySelector(`td:nth-child(${header.cellIndex + 1})`).textContent.trim(); if (!isNaN(aText) && !isNaN(bText)) { // Numeric comparison return order === 'asc' … -
Django How to update the session cart icon after admin delete a product
I have two apps in my project one is call store and the other is call cart in store I have all the models and in cart I have all the cart functionality. The call is handle using session when admin delete a product the cart icon count is like if the product has not been deleted from the session however the summary html show up the rights products in the cart (it doesn't include the deleted one but the cart icon show up a quantity that is wrong). how can I update the icon with the right quantity once admin delete the product, the cart need to be refresh and I have used a post_delete signal for this but it seems not to be working. this is my code cart/signals.py from django.db.models.signals import post_delete from django.dispatch import receiver from store.models import Product from django.contrib.sessions.models import Session @receiver(post_delete, sender=Product) def update_cart_on_product_delete(sender, instance, **kwargs): # Get all sessions sessions = Session.objects.all() for session in sessions: cart = session.get_decoded().get('cart', {}) if cart: # Check if the deleted product is in the cart if str(instance.id) in cart: del cart[str(instance.id)] # Save the updated cart back to the session session.get_decoded()['cart'] = cart session.save() -
Error: connect ECONNREFUSED ::1:8000 in Nuxt 3
I’m working on a Nuxt 3 project and encountering the following error: [nitro] [unhandledRejection] connect ECONNREFUSED ::1:8000 This error occurs when I try to make API requests to my backend during development. I suspect it’s related to the frontend (Nuxt 3) server not running or being misconfigured, but I’m not sure how to resolve it. It happen when I try to get tokens from the backend when the app start. So I try to call the backend in middleware/auth.global.ts and in plugin/initail.ts like this to make sure that user token is set to the state (I am using Pinia for state management) import useAuthStore from "~/store/useAuthStore"; export default defineNuxtRouteMiddleware(async () => { const authStore = useAuthStore(); if (!authStore.isAuthenticated) { // Call the backend here await authStore.checkAuthState(); } }); import useAuthStore from "~/store/useAuthStore"; export default defineNuxtPlugin(async (nuxtApp) => { const authStore = useAuthStore(); authStore.checkAuthState(); }); My checkAuthState() is like this : try { // Attempt to refresh the token if access is empty const axiosApi = axios.create({ baseURL: "http://localhost:8000/api", headers: { "Content-Type": "application/json", 'Accept': 'application/json', }, withCredentials: true, withXSRFToken: true, timeout: 10000, }); await await axiosApi.post('/token/refresh/'); } catch (error) { console.error("Error refreshing token:", error); this.authenticated = false; return; } Here’s some … -
Cuncurrency, mutex, semaphores on django and a cron job
I want to create a critical section in django provide controlled section. One of this is in one of the django channels consumers handling the websocket connections and the other is in a cron process implemented with cron tab, not celery. I would like these both critical sections to have a lock. How would I implement this in django. I know there is python Value,Semaphores, Mutexs but I can not pass the Value to cron job. So Can I use some sort of a file lock. Maybe interprocess communication lock, if that exists. Anythoughs on how to archive this in Django -
Coverage: How to gracefully stop a Django development server that runs on a Github Action Instance
I am testing some API endpoints of my Django app by running Playwright separately on a Ubuntu machine on my Github Action instance. Since I also want to get the coverage of the tests, I am starting my server this way: - name: run backend server run: poetry run coverage run ./manage.py runserver --no-reload This results in a single process being started. Now, in order to collect the coverage data, I need to gracefully stop my django server, as force killing the process would also interrupt coverage and executing coverage combine would produce an error. I have tried the following commands, but they all fail to stop the server kill -SIGINT $DJANGO_PID kill -SIGTERM $DJANGO_PI pkill -f "./manage.py runserver" python -c "import os; import signal; print(os.kill($DJANGO_PID, signal.SIGTERM))" Is there a different approach I can use ? or maybe I am starting the server the wrong way? -
TemplateSyntaxError at / Could not parse the remainder: '(item.star)' from 'range(item.star)'
This my code I wanna added star on my shop {% with '' |center:item.star as range %} {% for _ in range %} <div class="bi-star-fill"></div> {% endfor %} {% endwith %} And django error says TemplateSyntaxError at / Could not parse the remainder: '(item.star)' from 'range(item.star)' Wanna added star between 5 /1 -
How do I update a Django field in an HTML template
I have a Django app that among other things wants the user to enter a date of birth or their age. Upon the entry of one, the other should be calculated and when the form is saved, the database should be updated with both values. Unfortunately it does not appear that the modified data is seen when the form is submitted. If the birthday is entered and the age calculated, clean() will indicate that age is None. When the age is entered and the birthday calculated everything seems to work correctly. I am assuming that it has something to do with changing the disabled property, but have been unable to find anything to support this. I have also seen similar results with other fields where I change the disabled flag. Excerpt from models.py: class Patient(models.Model): birthday = models.DateField(_('Birthday'), blank=True) age = models.IntegerField(_('Age'), blank=True) Excerpt from forms.py class PatientCreateForm(forms.ModelForm): birthday = forms.DateField(widget=DateInput(attrs={'type': 'date'}), required=True) age = forms.IntegerField(required=True) class Meta: model = Patient fields = [ 'birthday', 'age', Excerpt from views.py def createpatient(request): if not request.user.is_authenticated: logger.debug(f'no user is logged in') login_url = reverse("login") next_url = reverse("create-patient") redirect_url = f'{login_url}?next={next_url}' logger.debug(f'redirect to {redirect_url}') return redirect(redirect_url) # value of patient_id is calculated here … -
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYT
as i made to apps accounts and core . in accounts model i have created custom user and in core i made userpreference model i want to import accounts.models customuser but it gives error above mention i have tried the name in install app as accounts and not resolve -
What strategies can I use to handle occasionally long running blocking database tasks in Django
I have a scientific data submission validation interface on my website. It essentially does a dry run load of the data and reports whether the dry run load succeeds and if it does not, it gives a report on errors and warnings that occurred during the dry run load. All of this is done inside an atomic transaction. So if two users submit data to validate at the same time, one of the processes will be blocked until the first one finishes. Most such tasks will take a handful of seconds, so it's not a big deal, but occasionally a user will submit a large amount of data for validation, and it can take just shy of a minute to do all of the processing in the worst case, in which case any other validation submission would encounter a timeout. I am currently considering my options for mitigating or solving this issue. Ideally, there would be some way for me to tell the database that all of this work will not be committed and to ignore any other concurrent database operations because all of this work will get thrown away anyway. I'm sure that this capability does not exist, but … -
django-tables2: hyperlink in cells
I have a view named events displaying two columns. One eventType and a second eventDates, listing dates. It looks like this: eventType eventDate foo 1900-01-01, 2010-02-02 bar 2000-01-01, 2010-02-02, 2010-03-03 The code for the view and the table looks like: def events(request, pk): data = some_module.get_data(pk) data_table = MyTable(data) return render(request, "app/events.html", {"table": data_table}) Where data is a list of dictionaries and MyTable is a class inheriting from django_tables2.Table: class MyTable(tables.Table): eventType = tables.Column() eventDates = tables.Column() A cell in the column eventDate can be either empty or containing several dates. It depends on pk. I can display that table. Now, I would like each date to be an hyperlink redirecting to another view. This view would be like that: def event_details(request, eventtype=et, eventdate=ed): data_event = some_module.get_event data(eventtype, eventdate) return render(request, "app/events_details.html", {"data_event ": data_event }) And here are my issues. First, I have not been able to have a dynamic number of hyperlink, varying from cell to cell. Second, the url should include the eventType and its date. E.g. taking the exemple above, cliking on 2010-02-02 should redirect to either: eventtype=foo_eventdate=2010-02-02 or eventtype=bar_eventdate=2010-02-02, depending on which 2020-02-02 I clik on. I have first tried to have several links in … -
Making an AI security app using django and react-native, but the output that is sent by django does not show on android and ios but does show on Web
Making a security app that will using a classification model detect who is at my door (members of my family for now) and show it on an App that i am making in react-native. Ive got most of the code figured out but the problem i am now facing is that when django sends the feed (image by image im presuming) the mobile apps dont show the feed (using expo go) but the web app does. Views.py: from django.shortcuts import render from django.views.decorators import gzip from django.http import StreamingHttpResponse import cv2 import threading import numpy as np from tensorflow.keras.models import load_model # Load the face recognition model model = load_model('./final_face_recognition_model.keras') # Define class labels class_labels = ["person1", "person2", "person3"] # Load OpenCV's pre-trained Haar Cascade for face detection face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') # Define a function to preprocess frames for the model def preprocess_frame(frame, x, y, w, h): """ Extract the face region, resize, normalize, and reshape it for the model. """ face = frame[y:y+h, x:x+w] input_size = (160, 160) # Model's input size resized_face = cv2.resize(face, input_size) normalized_face = resized_face / 255.0 # Normalize pixel values reshaped_face = np.expand_dims(normalized_face, axis=0) # Add batch dimension return reshaped_face class VideoCamera(object): … -
no domain link when ı launched my website on aws elasticbeanstalk
ı get some errors on aws elastic beanstalk and ı can not get domain link, my website contains data but ı didnt use database when ı do configurations but errors are not about database? also ı get this error November 19, 2024 11:34:18 (UTC+3) INFO Environment health has transitioned from Pending to No Data. Initialization in progress (running for 16 minutes). There are no instances``` -
State is lost following Apple login via python social auth (AuthStateMissing)
I've added apple-id to a django project that already has facebook & twitter login implemented & working. From the application you can get to apple, login and then you come back to the /player/social/complete/{backend}/ path. Here there's an AuthStateMissing: Session value state missing exception. Sessions are using signed_cookies, SESSION_COOKIE_SAMESITE is currently "Lax" but I've tried to set that to None with no change. Besides the client/team/key settings I have also defined the following for Apple ID SOCIAL_AUTH_APPLE_ID_SCOPE = ["email", "name"] SOCIAL_AUTH_APPLE_ID_EMAIL_AS_USERNAME = ( True # If you want to use email as username ) I've tried various bits that I've found suggested on here and github issues, like specifying the state field for session storage. But nothing seems to resolve this issue and I'm not familiar enough with how this library works - I'd hoped it'd "just work" like apple usually suggest! -
Apple signin/login with django and flutter problem - invalid_client response
I'm having an issue with implementing Apple Sign-In/Login in my Django + Flutter application. Here's the flow I'm using: On the Flutter side, I'm using the following code to get credentials from Apple: SignInWithAppleButton( onPressed: () async { final credential = await SignInWithApple.getAppleIDCredential( scopes: [ AppleIDAuthorizationScopes.email, AppleIDAuthorizationScopes.fullName, ], ); print(credential); // Now send the credential (especially `credential.authorizationCode`) to your server to create a session // after they have been validated with Apple }, ); This returns information like identity_token and authorization_code. For test purposes, I send the authorization_code in a POST request to the endpoint https://appleid.apple.com/auth/token with the following details: Headers: { "Content-type": "application/x-www-form-urlencoded" } Body: { "client_id": "com.example.myapp", "client_secret": "example_client_secret", "grant_type": "authorization_code", "code": "my_example_authorization_code" } For generating the client_secret, I use the following Python script: # Load the private key with open(PRIVATE_KEY_PATH, "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend() ) header = { "alg": "ES256", "kid": KEY_ID, } payload = { "iss": TEAM_ID, "iat": int(time.time()), "exp": int(time.time()) + 15777000, "aud": "https://appleid.apple.com", "sub": APP_ID, } client_secret = jwt.encode( payload, private_key, algorithm="ES256", headers=header ) print(client_secret) After all that steps, every time I send the POST request to Apple's /auth/token endpoint, I get the following response: {"error": "invalid_client"} Is there … -
get_absolute_url django admin session id missing
I'm using Django's "View on site" feature to navigate from the Django admin to a specific page in my application for a model instance. On this page, a GET request is made to retrieve data using a Django ModelViewSet. The issue is that even though I'm logged into the Django admin, when I visit the application page via "View on site," it says I'm "unauthenticated." Upon inspecting the request headers, I noticed that the session ID is not being sent. Here’s how I’ve implemented the get_absolute_url method: return ( reverse("website:emi_calculator") + f"?snowflake={self.snowflake}" ) Any help or guidance would be greatly appreciated! -
django docker poetry mysql driver problem
I'vse used django a milion times and docker half a million times but this time i can't get it to work Image: FROM python:3.11.5-slim-bookworm AS python-base Dockerfile: apt-get install --no-install-recommends -y python3-dev default-libmysqlclient-dev build-essential pkg-config Poetry mysqlclient = "^2.2.6" Django settings: 'ENGINE': 'django.db.backends.mysql' django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Yes ... i did ... There is a lot of threads regarding this, i tried many variations but solutions from 2013 don't seem to work any more ... -
How to create a Django Admin link with preselected objects and a pre-filled action?
I am trying to generate a link that takes users to the Django Admin page for a specific model, with certain objects already selected and an action pre-filled in the dropdown menu. Here’s what I’ve tried so far: def get_admin_action_link(record, action): app_label = record._meta.app_label model = record._meta.model_name id = record.id env = f"{settings.env}.myurl.com" if settings.env else "http://localhost:8000" return f"{env}/admin/{app_label}/{model}?action={action}&_selected_action={id}" The generated link looks like this: http://localhost:8000/admin/app/mymodel?action=process&_selected_action=591 However, when I click on the link, it only takes me to the changelist view of the model in the admin. The objects aren’t selected, and the action isn’t pre-filled. -
How to Run Functions in Parallel or in the Background in Django Without Using Celery/Redis?
I have a use case in my Django application where I want to run two functions in parallel or execute a process in the background. I don't want to use third-party tools like Celery, Redis, or similar services for this. What I want to achieve: Safely execute tasks in parallel or in the background. Avoid slowing down the main request-response cycle. I've heard that making internal API calls via HTTP (e.g., calling Django endpoints from within the same project) can be a faster alternative. Is this true and safe? I don't want this to effected by the GIL in python -
Django API with Redis Cache Not Updating Immediately After POST/PUT/DELETE Requests
I'm developing a Django REST API using Django, Redis, and SQLite. The goal is to cache data for GET requests to improve performance, using Redis as the caching layer. Issue: When I create, update, or delete Category or Product instances, the changes are reflected in the database (as seen on the Django admin page), but not immediately in subsequent GET requests. The GET responses only reflect the changes after I restart the server. However, creating a new category with the same name is prevented, indicating the API can still read existing data from the database. app/views.py from django.shortcuts import render from django.core.cache import cache from rest_framework import viewsets, status from rest_framework.response import Response from rest_framework.decorators import action from .models import Category, Product from .serializers import CategorySerializer, ProductSerializer from django.conf import settings CACHE_TTL = getattr(settings, 'CACHE_TTL', 5) class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer def list(self, request, *args, **kwargs): cache_key = 'store:categories' data = cache.get(cache_key) if not data: # Serialize the queryset to JSON before caching data = self.get_serializer(self.queryset, many=True).data cache.set(cache_key, data, CACHE_TTL) print('Cache set') print('Cache retrieved') return Response(data) def create(self, request, *args, **kwargs): cache.delete('store:categories') print('cache deleted') return super().create(request, *args, **kwargs) def update(self, request, *args, **kwargs): cache.delete('store:categories') return super().update(request, *args, … -
Caching daily data in Django, and caching more on request
I'm currently building a website where I each day want yesterday's financial data cached for the full day, to be quickly available to users. I also want to cache older data on request, e.g. if a user looks at data for some date in 2023, I also want to cache that, although for a shorter time (say maybe 1 h). Being new to Django, I've tried to read up on the different caching solutions that Django offers, but I'm a bit confused as to which would server me well. Does Django offer a solution fit for this purpose? Would it be easier to set up a manual caching process, which fetches cached data if it exists, and otherwise retrieves and caches it for a specfied time period? If so, what would such a solution look like? Thank you. -
Django all-auth extended SignupForm is valid but save method is not called
I am using Django all-auth in conjunction with django. I am also extending their default signup form. The form renders correctly, fields are validated correctly, the form returns as valid if checked but the save method isn't even called. These are my settings, When the submit button is pressed, the form posts fine. But then no user is created and through some testing the save method on the form just isn't called. forms.py class CustomSignupForm(stupidform): agreed_to_TC = forms.BooleanField(required=True) agreed_to_PA = forms.BooleanField(required=False) agreed_to_updates = forms.BooleanField(required=False) email = forms.EmailField(required=True) password = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) def clean_password(self): password = self.cleaned_data["password"] password2 = self.cleaned_data.get("password2") if password and password2 and password != password2: raise ValidationError("Passwords don't match") return password def save(self, request): user = super(CustomSignupForm, self).save(request) user.email = self.cleaned_data["email"] user.agreed_to_ads = self.cleaned_data["agreed_to_PA"] user.agreed_to_TC = self.cleaned_data["agreed_to_TC"] user.save() return user settings.py AUTH_USER_MODEL = 'dashboard.UserProf' ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' SECURE_SSL_REDIRECT = False ACCOUNT_DEFAULT_HTTP_PROTOCOL = "https" ACCOUNT_EMAIL_REQUIRED = True # ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_FORMS = { 'signup': 'wishfor.forms.CustomSignupForm', } urls path('accounts/', include('allauth.urls')), -
WebSocket Connection Failure and Unexpected Socket Closure in Django Channels
I'm experiencing issues with establishing and maintaining a WebSocket connection in my Django project using Django Channels. I've set up a notification system that uses WebSockets to broadcast messages to connected clients. However, I'm encountering two errors: "WebSocket connection to 'ws://127.0.0.1:8000/ws/notification/broadcast/' failed" "Chat socket closed unexpectedly" Here's my code: routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/notification/(?P<room_name>\w+)/$', consumers.NotificationConsumer.as_asgi()), ] views.py: def notification_view(request): return render(request,'person/notification.html',{'room_name': "broadcast"}) settings.py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } consumer_context_processor.py: from notification_app.models import BroadcastNotification def notifications(request): allnotifications = BroadcastNotification.objects.all() return {'notifications': allnotifications} models.py: class BroadcastNotification(models.Model): message = models.TextField() notification_image=models.ImageField(upload_to="notification",default="notification.jpg",blank=True,null=True) notification_link = models.URLField(max_length=10000, help_text="Add a valid URL",blank=True,null=True) broadcast_on = models.DateTimeField() sent = models.BooleanField(default=False) class Meta: ordering = ['-broadcast_on'] @receiver(post_save, sender=BroadcastNotification) def notification_handler(sender, instance, created, **kwargs): # call group_send function directly to send notificatoions or you can create a dynamic task in celery beat if created: schedule, created = CrontabSchedule.objects.get_or_create(hour = instance.broadcast_on.hour, minute = instance.broadcast_on.minute, day_of_month = instance.broadcast_on.day, month_of_year = instance.broadcast_on.month) task = PeriodicTask.objects.create(crontab=schedule, name="broadcast-notification-"+str(instance.id), task="notifications_app.tasks.broadcast_notification", args=json.dumps((instance.id,))) task.py: @shared_task(bind = True) def broadcast_notification(self, data): print(data) try: notification = BroadcastNotification.objects.filter(id = int(data)) if len(notification)>0: notification = notification.first() channel_layer = get_channel_layer() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(channel_layer.group_send( "notification_broadcast", … -
Inline Serializer for Request Body Not Displaying in DRF Spectacular Documentation
I am working on a Django REST Framework (DRF) project using DRF Spectacular for API documentation. My ViewSet does not use a serializer because the logic does not require one, but I need to describe the request body shape in the API documentation. To achieve this, I am using DRF Spectacular's inline_serializer to define the request body schema dynamically. Here’s an example of how I’ve implemented it: from drf_spectacular.utils import extend_schema, inline_serializer from rest_framework import serializers from drf_spectacular.types import OpenApiTypes from rest_framework.response import Response class ExampleViewSet(viewsets.ViewSet): @extend_schema( request=inline_serializer( name="InlineFormSerializer", fields={ "str_field": serializers.CharField(), "int_field": serializers.IntegerField(), "file_field": serializers.FileField(), }, ), responses={200: OpenApiTypes.OBJECT}, # Placeholder for actual response schema ) def create(self, request, *args, **kwargs): # Business logic here return Response({"message": "Success"}) While the schema generation works without errors, the request body schema described via inline_serializer does not appear in the frontend API documentation (e.g., Swagger UI). The rest of the API is documented correctly. Steps I've Taken Confirmed that DRF Spectacular is installed and properly configured in settings.py REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', } Verified that the schema generation command runs without issues Confirmed that inline_serializer is being used as per the documentation. Ensured the swagger-ui is accessible and displays other endpoints … -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc2 in position 61: invalid continuation byte
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc2 in position 61: invalid continuation byte помогите решить проблему я хочу сделать миграцию бд в проекте в джанго с sqlite на postgres и при команде python manage.py возникает такая ошибка в чем проблема и как ее решить больше важнее как ее решить +- разобрался в чем конкретно проблема а вот как решить нигде не могу найти помогитее все перепробовал -
Django unit test with parallel db accesses giving database locked error
I am writing some Django unit tests to validate the behavior of my application when multiple clients access it at the same time. I have done this by writing tests like this: from django.test import TestCase from django.db import connection from django.db import transaction class ApplicationTestCase(TestCase): def test_parallel(self): @transaction.atomic def local_provision(i): with connection.cursor() as cursor: # Some SQL commands that read and write the person table. # These commands take less than one second. return f"done with {i}" with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: futures = [executor.submit(local_provision, i) for i in range(5)] for future in concurrent.futures.as_completed(futures): print(future.result()) When I run this unit test I get an immediate error: django.db.utils.OperationalError: database table is locked: person I tried changing the timeout in the settings.py file but that did not make any difference. Why isn't SQLite waiting until the file is unlocked and then retrying? How can I get SQLite to retry?