Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send CSRF token using Django API and a Flutter-web frontend ? HeaderDisallowedByPreflightResponse
I have a python/django web API with a single endpoint, let's call it /api/v1/form. That API is called from a Flutter-web frontend application. I currently use the following configuration that disables CSRF token verification, and it works : requirements.txt Django==5.1.7 django-cors-headers==4.7.0 webserver/settings.py ... ALLOWED_HOSTS = ["localhost"] CORS_ALLOWED_ORIGINS = ["http://localhost:8001"] # flutter dev port INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'webserver', ] ... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... webserver/urls.py from django.urls import path import webserver.views urlpatterns = [ path('api/v1/form', webserver.views.api_v1_form, name="api_v1_form"), ] ... webserver/views.py from django.http import HttpResponse, HttpResponseBadRequest def api_v1_form(request): if request.method == "POST": process_request(request.body) return HttpResponse("request successfully processed.") return HttpResponseBadRequest("Expected a POST request") flutter/lib/page_form.dart Future<int> sendForm(MyData data) async { final response = await http.post( Uri.parse("http://localhost:8000/api/v1/form"), body: data.toString(), ); return response.statusCode; } Here is what I don't understand : if I disable to the CORS package in order to simply use a vanilla Django server, then I find myself capable of sending requests to the API but unable to receive an answer. Why is that the case ? The following is the configuration used to get the CSRF token and use it in the requests. settings.py ALLOWED_HOSTS = ["localhost"] … -
Django with chartjs > 2.9.3
I'm using version Django==5.0.6 and attempting in integrate charts using chartjs and plugin datalabels. When I use the charts render without issue, but I'm not able to see any datalabels. If I try to add Chart.register(ChartDataLabels); the graph no longer renders. I've also tried Chart.plugins.register(ChartDataLabels); I'd like to be able to use the most updated version of chartjs but when I change the chart version to anything other than 2.9.3, the graphs don't render. base.html <!DOCTYPE html> <html> {% load static %} {% load django_bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} <head> <title>{{ template_data.title }}</title> <link rel= "stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"> <link href= "https://fonts.googleapis.com/ css2?family=Poppins:wght@300;400;500;600;700&display= swap" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0-rc"></script> </head> ... data.html {% extends "base.html" %} {% load django_tables2 %} {% block head %} <p><h3>Job data</h3>{{year}}</p> {% endblock head %} {% block content %} <canvas id="chart" style="position: relative; height:100vh; width:100vw"></canvas> <script> let ctx = document.getElementById("chart").getContext('2d'); /* Chart.register(ChartDataLabels); Chart.plugins.register(ChartDataLabels); */ let chart = new Chart(ctx, { type: "horizontalBar", data: { labels: [{% for data in labels %} '{{data}}', {% endfor %}], datasets: [ { label: "Job Week 13", backgroundColor: "#2d9f42", borderColor: "#030202", data: [{% for data in week13_count … -
Which is better: using Django Constraints or raising a ValueError in the save method?
I’ve come across two ways to enforce a condition in Django models: Using the save method with a ValueError: class MyModel(models.Model): field_name = models.CharField(max_length=100) def save(self, *args, **kwargs): if not self.field_name: # Example condition raise ValueError("Field name cannot be empty.") super().save(*args, **kwargs) Using Django's Constraints (like CheckConstraint): from django.db import models from django.db.models import Q class MyModel(models.Model): field_name = models.CharField(max_length=100) class Meta: constraints = [ models.CheckConstraint( check=~Q(field_name=""), # Example condition name="field_name_not_empty", ) ] I know both approaches can enforce conditions, but I’m wondering: Which approach is more efficient? Which one is generally better to use in real-world scenarios? -
Calling a Django Management Command from a Celery Task and Redirecting Logs
I'm trying to call a Management Command with call_command within a Celery task. The management command writes logs in different ways: through print statements, self.stdout.write, or using the logger defined at the script's module level. I want to capture all these log messages in the Celery logger to make them visible in Datadog. Is this possible? I tried the worker_redirect_stdouts_level option, but it impacts the global Celery logging configuration. -
Django formset with nested single inline form of each formset object(form)
I'm trying to figure out the logic of building such structure: class Order(models.Model): id = ... class OrderItem(models.Model): order = FK(Order) quantity = CharField() category = CharField(choices=..) class OrderItemSchema(models.Model): class Meta: abstract = True order_item = OneToOneField(OrderItem) brand = CharField() model = CharField() class SomeProduct1Schema(OrderItemSchema): size = PositivieIntegerField() class SomeProduct2Schema(OrderItemSchema): weight = CharField() type = CharField() Let's assume some customer has created new Order which "Company" has to produce. There are different types of products (not much: 2-10) which may not have even single common parameter/field but still be placed withing one Order. The question is: How to manage FormSet (or there is another way?) of OrderItem elements where each element may has different fields? Example: OrderItem: [SomeProduct1Schema] \ category \ quantity \ brand \ model \ size OrderItem: [SomeProduct2Schema] \ category \ quantity \ brand \ model \ weight \ type So far I've added OrderItem inline formset to Order and both SomeProduct1Schema \ SomeProduct2Schema inline formsets attached to OrderItemFormSet as nested form. But it's works well with single nested formset class and becoming mess when need to handle multiple dynamically. Now I'm thinking to make SomeProduct1Schema classes to inherit from OrderItem directly using multi-table inheritance. Performance is not … -
Django decorator import issue: 'cannot import name' when used in views.py
when trying to start the server it cannot find the decorator from django.contrib.auth.decorators import login_required, user_passes_test, staff_member_required ... @staff_member_required def delete_service_view(request, service_id): service = get_object_or_404(Service, pk=service_id) service.delete() return redirect('index') @staff_member_required def toggle_trusted_from_service_view(request, user_id): if request.method == 'POST': try: user = User.objects.get(pk=user_id) user.isTrusted = not user.isTrusted user.save() return redirect('service_detail', service_id=request.POST.get('service_id')) except User.DoesNotExist: return HttpResponseForbidden("User not found.") else: return HttpResponseForbidden("Invalid enquiry method.") When i try python manage.py runserver File "C:\Users\alexe\djangoshop\dshop\main\views.py", line 3, in <module> from django.contrib.auth.decorators import login_required, user_passes_test, staff_member_required ImportError: cannot import name 'staff_member_required' from 'django.contrib.auth.decorators' (C:\Users\alexe\djangoshop\dshop\dshop_new_env\Lib\site-packages\django\contrib\auth\decorators.py) I've already recreated the environment and reinstalled all dependencies -
Apps aren't loaded yet
I'm using Visual Studio 2022 as the IDE. It has 2 projects: CLI - A Python Application Common - A Blank Django Project The classes are created in Common > app > models.py. app is a Django app CLI is the startup project, and cli.py is its startup file. Common project is referenced in CLI. When I Start the CLI app in debug mode, there is an error for the Question class. -
Django-Simple-History: Avoid Redundant History Records & Track Generic Relations
We are using django-simple-history to track changes in our models, including many-to-many (m2m) relationships and generic relationships. Model: class BandProfile(BaseModel): class Meta: db_table = "band_profiles" name = models.CharField(max_length=255) types = models.ManyToManyField( Choices, related_name="types", limit_choices_to={"category": "type"}, blank=True, ) description = models.TextField(null=True, blank=True) history = HistoricalRecords( table_name="history_band_profiles", history_user_setter=set_historical_user_from_request, history_user_getter=get_historical_user_from_request, history_user_id_field=models.CharField(max_length=36, null=True), m2m_fields=[types], # Many-to-many tracking ) def __str__(self): return f"Band Profile for {self.name}" Serializer: def create(self, validated_data): """ Create method for BandProfile with handling for related fields. """ types = validated_data.pop("type_ids", []) band_profile = BandProfile.objects.create(**validated_data) band_profile.types.set(types) Issues: When creating or updating resources, django-simple-history is generating multiple redundant history entries, which results in incorrect historical tracking. Below shows the redundant records. See the redundant records Expected Response Format: We need a structured response that includes the historical records of the resource, its many-to-many relations, and generic relations, like this (Field names are examples): [ { "id": 101, "name": "Resource A", "history_date": "2025-03-20T10:00:00Z", "change_type": "update", "types": [ { "id": 201, "name": "Sector X", "history_date": "2025-03-19T15:00:00Z", "change_type": "create" }, { "id": 202, "name": "Sector Y", "history_date": "2025-03-20T16:00:00Z", "change_type": "update" } ], "generic_relation": [ { "id": 301, "type": "Document", "title": "Policy Document A", "history_date": "2025-03-18T11:00:00Z", "change_type": "create" }, { "id": 302, "type": "Document", "title": "Policy Document … -
Django + python --> problem with polish characters like "ą" "ę" "ł"
Ciao! I am a beginner in Django & Python. I want to create a simple blog. I followed a step-by-step tutorial from this video → [YouTube link]https://www.youtube.com/watch?v=2MkULPXXXLk&t=865s and I have issue. When I create a category with Polish characters like "ą", "ę", it works. However, when I try to assign a post to this category, it doesn’t work. I spent some time trying to fix it but had no success. If I understand correctly, Python compares the category name "Łódź" with "Łódź" after URL transformation or something like that. For example: Łódź == odz → False Because of this, I can't see posts in the "Łódź" category. Here is my GitHub repo: [GitHub link] https://github.com/marekpno/problem MD -
Specifying get methods for nested serializers
In the case of nested serializers, is there a way to specify a method that will get the data? class AuthorSerializer(ModelSerializer): .... class BookSerializer(ModelSerializer): authors = AuthorSerializer(many=True) .... In this example, I would like to intercept and modify how BookSerializer gets the authors. How do I accomplish this? -
Django error with SSL and Azure Flexible MySQL
I'm doing a MySQL migration to an Azure MySQL Server. Which I don't have the control on the configuration. I managed to connect to it with a simple python script, but faking the TLS flag with pymysql. from azure.identity import ManagedIdentityCredential import pymysql # Get Managed Identity Token credential = ManagedIdentityCredential() token_msi = credential.get_token( "https://ossrdbms-aad.database.windows.net/.default" ).token deploy_env = "dev" application_name = "my_app" # Define connection parameters connection = pymysql.connect( host="xxxxxxxxxxxxxxxxxxxx.mysql.database.azure.com", user=f"{application_name}_{deploy_env}", password=token_msi, db=f"{application_name}_{deploy_env}", ssl={"fake_flag_to_enable_tls": True} ) # Execute a query query = "SHOW DATABASES" with connection.cursor() as cursor: cursor.execute(query) print(cursor.fetchall()) So this works. I managed to dump my old database and import it to the new one using the mysql cli. But now I'm trying to make my Django app connect to it. In my Django settings.py: deploy_env = "dev" application_name = "my_app" DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": f"{application_name}_{deploy_env}", "USER": f"{application_name}_{deploy_env}", "PASSWORD": None, # Token will be assigned dynamically "HOST": f"xxxxxxxxxxxxx.mysql.database.azure.com", "PORT": 3306, } } get_db_token() Here is the get_db_token function: import os import django.conf as conf from azure.identity import ManagedIdentityCredential def get_db_token(): azure_credential = ManagedIdentityCredential() token = azure_credential.get_token( "https://ossrdbms-aad.database.windows.net" ).token conf.settings.DATABASES["default"]["PASSWORD"] = token When making a test with python manage.py dbshell I can see all my … -
Using pghistory with custom event table names
I'm currently testing pghistory for our Django project. I set up a few models to be tracked. As a convention our model names are different from the actual table names - these are defined in the Meta class like so: class Delivery(models.Model): created = models.DateTimeField(auto_now_add=True, editable=False) creator = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='deliveries', on_delete=models.PROTECT, editable=False) ... class Meta: db_table = 'ep_delivery' When I decorate the model with @pghistory.track() the resulting event table is called as the model, which is DeliveryEvent in this example. But I would rather have it being named ep_delivery_event to be in accordance with our conventions. How can I achieve this? -
How to use multiple database connections in Django TestCase
I'm writing a testcase to reproduce deadlock in my service. After I use multiprocessing to create a two thread, I found they use the same database connection. So I can't reproduce the deadlock scenario in testcase. How do i resolve this issue? My code is as belows: @transaction.atomic() def process_1(): change = Change.objects.select_for_update().get(id="1") time.sleep(5) change = Change.objects.select_for_update().get(id="2") @transaction.atomic() def process_2(): change = Change.objects.select_for_update().get(id="2") time.sleep(5) change = Change.objects.select_for_update().get(id="1") p1 = Process(target=process_1) p2 = Process(target=process_2) p1.start() p2.start() p1.join() p2.join() self.assertEqual(p1.exitcode, 0) self.assertEqual(p2.exitcode, 0) -
Unable to Import 'celery' When Running pylint, but Django Runs Fine
I am working on a Django project and using uv as the package manager. My dependencies are managed in pyproject.toml, and I have the following setup: pyproject.toml (Relevant Parts) [project] name = "port-backend" version = "0.1.0" description = "Backend service for port.az" readme = "README.md" requires-python = ">=3.12" dependencies = [ "celery>=5.4.0", "django==4.2", "djangorestframework>=3.15.2", "djangorestframework-simplejwt>=5.5.0", "drf-spectacular>=0.28.0", ] [dependency-groups] dev = [ "pylint>=2.0.0", ] [tool.pylint.MASTER] ignore-paths = ['.venv/'] disable = [ 'C0415', # Import outside toplevel 'E0401', # Import error ] Steps Taken I ran uv sync, which created a new .venv and installed dependencies. VS Code detected the new environment and asked if I wanted to use it. I selected "Yes" and ensured the virtual environment was activated. Running uv run manage.py runserver works without issues, meaning Django and Celery are installed correctly. However, running uv run pylint . gives these errors: ************* Module manage manage.py:12:8: C0415: Import outside toplevel (django.core.management.execute_from_command_line) (import-outside-toplevel) ************* Module config.celery_app config/celery_app.py:3:0: E0401: Unable to import 'celery' (import-error) What I Have Tried Verified that Celery is installed in the .venv by running uv pip list, and celery is present. Checked that the .venv is activated in VS Code (terminal shows (port-backend) ➜ port_backend). Tried running uv … -
TemplateSyntaxError : Could not parse the remainder
Using easy-thumbnails package. Getting the error for the template file below. Cant seem to figure out what the syntax issue is. i.image is of type ImageFileField **Could not parse the remainder: ' i.image 320x260' from 'thumbnail i.image 320x260' ** for i in image_page.object_list %} <div class="col-6 mb-4 grid-item" style="display: none;"> Image thumbnail for gallery --> <div> <img class="img img-responsive" src= if i.image.thumbnail != null %} i.image.thumbnail }} else %} thumbnail i.image 320x260 }} endif %} " alt="{{ lot.product.title }}" data-toggle="modal" data-target="#lightboxModal" data-image-url="{{ i.image.url }}" data-pk="{{ i.pk }}" style="cursor: pointer;"> comment %} object-fit: contain; background-color: #f5f5f5; {% endcomment %} </div> </div> endfor %} Trying to conditionally render image thumbnail if already available in object or generate and save it if the thumbnail is not available. -
/bin/bash: line 1: gunicorn: command not found in railway
I am trying to host the Django backend of my website on railway, however when I try and deploy the server, I get: /bin/bash: line 1: gunicorn: command not found error in logs I've followed all the steps of creating a requirements.txt file, and a Procfile, but I still get the same error. -
How to design a Django database schema for tracking user-item interactions (with quantities) to enable analytics and reporting?"
I'm building a Django web app to manage item stock, where authenticated users can "take" items from inventory (I'm not using djangos authentication system, is more like the user enters a code and the app checks in SQL Server if exists then saves the session info). I need to store user interactions to later analyze and visualize data such as: Recent items taken Most popular items User-specific activity Date-filtered interactions Total quantities taken per item Full interaction history, etc. Im thinking each interaction should record: User who performed the action Items taken (multiple items per interaction) Quantity taken per item Timestamp The current structure I have is Users and Items Users (Django's built-in User model) Items (Model with fields like name, stock_quantity, etc.) -
Other users cannot connect to the server on the websocket
I have a server on AWS EC2 with port 8001 open with a websocket application. The application itself is written in Django Channels and uses a daphne server. The problem is that I myself can connect to the websocket server, but other users do not have such an opportunity for some reason The script I'm using to connect const socket = new WebSocket("ws://54.145.126.99:8001/ws/chat/first_user=19628&second_user=19629", ["Bearer", token]); socket.onopen = function () { console.log("✅ connected to WebSocket server"); }; local application use http://127.0.0.1:5173/, application that use frontend dev also use http://localhost:5173/ and runs on React. So, i don`t which info i need to provide that you can understand problem, becouse i have no idea where that error could be. If you need some information, write i provide all. -
How to parse api request to defined model?
I'm new with python, I'm trying to parse api request to a defined model, so how to fix below code? class PersonSerializer(serializers.Serializer): name = serializers.CharField() class APIJustTest(APIView): parser_classes = (JSONParser,) @swagger_auto_schema(request_body=PersonSerializer) def post(self, request, *args, **krgs): serializer = PersonSerializer(data=request.data) serializer.is_valid() nameOK = serializer['name'].value #dictionary works but I prefer defined model nameError = serializer.name #this is defined model but will cause server error return JsonResponse({}) -
Cannot assign "": "" must be a "User" instance
I'm making a project using the Django framework and is creating a website and is encountering this error: Cannot assign "<User: >": "Booking.teacher" must be a "User" instance. this is my models.py for the booking: class Booking(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) teacher = models.ForeignKey(User, on_delete=models.CASCADE, limit_choices_to={'role': 'teacher'}) date = models.DateField() start_time = models.TimeField() end_time = models.TimeField() purpose = models.CharField(max_length=255, blank=True, null=True) class Meta: unique_together = ('room', 'date', 'start_time', 'end_time') def __str__(self): return f"{self.room.name} - {self.date} ({self.start_time} to {self.end_time})" this is my forms.py: class BookingForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['teacher'].queryset = User.objects.filter(groups__name='teacher') # Filter teachers class Meta: model = Booking fields = ['room', 'date', 'start_time', 'end_time', 'teacher'] widgets = { 'date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}), 'start_time': forms.TimeInput(attrs={'type': 'time', 'class': 'form-control'}), # Updated to start_time 'end_time': forms.TimeInput(attrs={'type': 'time', 'class': 'form-control'}), # Added end_time 'room': forms.TextInput(attrs={'class': 'form-control'}), 'teacher': forms.Select(attrs={'class': 'form-control'}), } def clean(self): cleaned_data = super().clean() room = cleaned_data.get('room') date = cleaned_data.get('date') start_time = cleaned_data.get('start_time') end_time = cleaned_data.get('end_time') # Check for booking conflicts if Booking.objects.filter(room=room, date=date, start_time=start_time, end_time=end_time).exists(): raise ValidationError('This room is already booked for the selected date and time.') return cleaned_data and this is my views: def booking_calendar(request): rooms = Room.objects.all() # Fetch all rooms for the dropdown bookings = … -
Django template nested for loop from 2 different lists
I have 2 lists (if that is what django calls them) containg an id and a key/value pair e.g. [{'id': x, 'string': 'string'}] one list assigned to variable 'periods' the other assigned to 'paydates'. I am trying to loop through each list and display the value from each in an HTML element, using DTL. I have the DTL in the HTML page {% for ... in ... %} one inside the other. The outer for loop from list 'periods' is working correctly, the inner for loop from list 'paydates' is not displaying anything at all, it doesn't throw an error either. The blue date in the pic is from the 'periods' list and is working correctly, the date from the 'paydates' list is supposed to show underneath 'Pay Date'. I cannot separate the for loop code because of the way i want my html page displayed. I am not sure what options I have to rectify the issue. My code follows: home.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script src="https://unpkg.com/@tailwindcss/browser@4"></script> <link rel="stylesheet" href="{% static 'appmain/style.css' %}" /> <title>Payslip Data</title> </head> <body> <div class="container mx-auto my-10 border rounded-2xl border-4 border-purple-200 … -
Adding HTTPS to django app on VM(Windows OS) Production level
We are developing react native app with django as a backend. We deployed django on VM(which we bought it has Window OS) and there git pulled and running django server by just uvicorn backend.asgi:application --host 0.0.0.0 --port 8000, we want to add https in it how can we do it? we don't have a domain just public IP address, please reply if u have helpful information -
run one time for Django model calculated property
class Company_Car(models.Model): @property def days_left(self): print("RUNNED PROPERTY") if self.date_valid is not None and self.date_valid >= datetime.datetime.now().date(): return (self.date_valid - datetime.datetime.now().date()).days added = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) company = models.ForeignKey(Company, on_delete=models.DO_NOTHING) date_valid = models.DateField(null=True, blank=True) Each time when i ask this property for same record it executes and it's not good My goal - property should run only once and return calculated data How it can done? -
Django: How to dynamically update stock quantity when selecting a product variation?
I am working on an e-commerce project where a product has multiple variations (like different colors, sizes, etc.), and each variation has its own stock. When a user selects a variation, I want to update the displayed stock dynamically, but it is not working correctly. Here’s my ProductStock model: class ProductStock(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="stocks") variation = models.ForeignKey(Variation, on_delete=models.CASCADE, blank=True, null=True) uploaded_stock_quantity = models.PositiveIntegerField(default=0) stock_quantity = models.PositiveIntegerField(default=0) reserved_stock = models.PositiveIntegerField(default=0) # For pending orders def available_stock(self): return self.stock_quantity - self.reserved_stock In my HTML template, I display variations as radio buttons: {% for v in variations %} <div class="variation__radio"> <input type="radio" id="variation_{{ v.id }}" name="variation" onclick="updateStock(this);" value="{{ v.id }}"> <label for="variation_{{ v.id }}">{{ v.name }}</label> </div> {% endfor %} <div class="stock-info"> <span id="uploaded-stock">-</span> in stock, <span id="remaining-stock">-</span> left </div> And my JavaScript function to update stock dynamically: function updateStock(element) { var variationId = element.value; var stockData = JSON.parse('{{ size_stock_data|safe }}'); // Pass stock data if (stockData[variationId]) { document.getElementById("uploaded-stock").textContent = stockData[variationId].uploaded_stock_quantity; document.getElementById("remaining-stock").textContent = stockData[variationId].stock_quantity; } else { document.getElementById("uploaded-stock").textContent = "-"; document.getElementById("remaining-stock").textContent = "-"; } } Issue The stock does not update when selecting a variation. Sometimes, it shows incorrect values or does not change at all. -
Is there any way to serve a Django application using preload, ASGI, and SO_REUSEPORT?
I can't find a way to serve our large Django application using all three of preload, ASGI, and SO_REUSEPORT. Without preload and fork we use much more memory (gigabytes). Without ASGI we can't serve websockets (and starting another server just for websockets would violate our memory constraints). Without SO_REUSEPORT we can run multiple preloaded/forked workers but traffic biases heavily (70%) to one worker, negating much of the benefit. We currently use gunicorn + uvicorn workers to achieve preload + ASGI. Gunicorn has an unreleased reuse_port mode that doesn't seem to do anything when using gunicorn + uvicorn. We looked at using granian or uvicorn itself as the process manager, but neither support preload/fork and so won't work due to our memory constraints.