Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Polars data in Django template html
lets start with their demo. df = pl.DataFrame( { "foo": [1, 2, 3], "bar": [6, 7, 8], } ) df.write_json() '[{"foo":1,"bar":6},{"foo":2,"bar":7},{"foo":3,"bar":8}]' I pass in the df in the from the df.write_json() context = { 'df' : df, } But nothing i am trying in Django is working? the json was the only option i see to pass the data. techinally this is a list of dicts? <ul> {% for i in df %} # tried many option here {{ i.foo }} {% endfor %} <ul> i have tried all sorts of things. for Pandas i would just use df.to_records() what is best way to get Polars data into a Django template to use in things like tables? loving polars so far but getting confused by a few things. Like this one. Thanks! -
Single Click django app installation using kubernates
I have my own CMS written in Django and Python. It uses a PostgreSQL database. For caching, it uses Redis and Memcached, and for scheduled tasks/cron jobs, it uses Celery. I am looking for a solution where, upon signup and payment, customers can deploy the CMS with a single click. Once deployed, it should be accessible under a subdomain like customer1.example.com or customer2.example.com. My Django backend is not configured for multi-tenancy because each customer may have slightly different requirements, especially in terms of functionality. This means the codebase could vary slightly from one customer to another. Additionally, the database and files need to be backed up regularly. I want a cost-effective solution for this setup. I don’t have much knowledge about cloud infrastructure. What would be your best advice for handling such a situation? -
How to boostrap a Django login form
I am writing a library management system in Django for my own personal needs. I have experience in backend,but I lack expertise in frontend. The project makes use of Boostrap 4 and Django's crispy forms. I have a base template templates/base.html from which other children templates inherit from. <!-- templates/base.html --> <!doctype html> <html lang="en"> <head> <!-- required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- boostrap css --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Book manager</title> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4"> <a class="navbar-brand" href="">Books</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> {% if user.is_authenticated %} <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link dropdown-toggle" href="#" id="userMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{user.username}}</a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userMenu"> <a class="dropdown-item" href="#"> Change password</a> </div> </li> </ul> {% else %} <form class="form-inline ml-auto"> <a href="{% url 'login' %}" class="btn btn-outline-secondary">Log in</a> <a href="" class="btn btn-primary ml-2">Sign up</a> </form> {% endif %} </div> </nav> {% block content %} <!-- here goes html content of childs--> {% endblock %} <!-- optional js --> <!-- jquery first, popper then bootstrap --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" … -
How do I save the email address I received from the Kivymd interface in the Django model?
My goal is to save the data I receive from the Kivymd interface in the Django model. Actually, there is no problem in saving many types of data, but the e-mail part caused problems. Below, I have shown the Django models and the operations on the Kivymd side (1. Getting the data from the front; 2. Post processing with DRF). from django.db import models class Model(models.Model): user_mail = Model.EmailField() And the posting progress ... def data(self): email = self.screen.ids.email_id.text requests.post(url, json('user_mail':'email') This is in its simplest form, I can give details if you want... And it returns a request 400 error as output: "POST /users// HTTP/1.1" 400 37 It is worth noting that I received the entered address, but as you can see, an error occurs in the sending part. -
Django - unable to import files in app directory
I am working on tutorial Django app. It is a very basic application, aimed at learning 'sceleton' structure of Django project. The problem - I am not able to do any imports between files in app directory. No imports between files like forms.py, views.py, models.py seem to work. In particular, I am not able to call: 'from models import ModelClass' in my forms.py file. I always get an error: ModuleNotFoundError: No module named ... (name of file here, e.g. 'models'). 'from .models import ModelClass' - (with dot before 'models') doesn't work either - same error. Also, I do have the usual 'init' file in the same directory. Any ideas on how to import model class from models.py into forms.py, both files in same directory? -
Docker Container gets down after an error shows up
I am developing a django project and the server is run by a docker container When there is an error in the code like a "syntax error". Docker logs shows that error and then shuts it self. The problem is until yesterday when I fix the error the docker log was showing "backend-1 | Watching for file changes with StatReloader" and I could still connect the server. How can I fix this problem? -
How to trigger Django task at specific date in model field
I have a model that contains the following field class EventConfig(models.Model): end_date = models.DateTimeField(blank=True, null=True) I have celery installed that's sending periodic emails and triggering other tasks at set time intervals e.g every hour or at 12pm. However, if I want to trigger an email as exactly when 'end_date' is reached, what is the best way to do this? I realise I could set a Celery schedule to run every minute to check the date, but is running a batch job every 60 seconds perpetually, the best approach or would this have drawbacks? Is there a way for example to set the crontab schedule to read from a list of values so that I could so something like schedule_list = EventConfig.objects.all().values_list(end_date, flat=True) or schedule_list.append(self.end_date) whenever a model instance is saved, and have Celery read from 'schedule_list' so the batch jobs then only fire at the correct times? Or is there a better way to do this either with or without celery? -
Merging tags admin action result in TemplateDoesNotExist
Following the docu's step: 3. Use the dropdown action list and select Merge selected tags and then click Go, I get the error below. Any ideas where I should start to investigate? Otherwise taggit works like a charm. django-taggit 6.0 TemplateDoesNotExist at /admin/taggit/tag/merge-tags/ admin/taggit/merge_tags_form.html Request Method: GET Request URL: http://localhost:8001/admin/taggit/tag/merge-tags/ Django Version: 4.2.16 Exception Type: TemplateDoesNotExist Exception Value: admin/taggit/merge_tags_form.html Exception Location: /home/abc/.local/share/virtualenvs/django-xy011hf/lib/python3.8/site-packages/django/template/loader.py, line 19, in get_template Raised during: taggit.admin.merge_tags_view Python Executable: /home/abc/.local/share/virtualenvs/django-xy011hf/bin/python Python Version: 3.8.12 -
Rendering datetime and proper formatting
I have a django project to keep track of tasks in a office enviroment. I have this model for tasks and it has a finish_date attribute that its assigned as soon i acces the route to done the desired task. I'm trying to use datetime and pytz to correctly format the date to the DateTimeField attribute. Here's the view code: task.data_conclusao=datetime.now().astimezone(pytz.timezone('America/Sao_Paulo')) task.save() It's saving the datetime but when i render it on the html, it just doesnt adjust to the timezone i set. Can anyone help me? -
Why am I getting the error (CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.)?
I'm trying to send from React a PUT request to my Django server for updating a Django model field. Here's the code const handleStatusChange = async (projectId, newStatus) => { try { const response = await fetch(`/api/project/${projectId}/status`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value }, body: JSON.stringify({ status: newStatus }) }); if (response.ok) { setProjects(prevProjects => prevProjects.map(project => project.id === projectId ? { ...project, status: newStatus } : project ) ); setStatusDropdown(null); setUpdatingProjectId(null); } else { console.error('Failed to update project status'); } } catch (error) { console.error('Error updating project status:', error); } }; The problem is that the console logs the message 'Failed to update project status' because of the server error: Forbidden (CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.): /api/project/1/status WARNING:django.security.csrf:Forbidden (CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.): /api/project/1/status [06/Dec/2024 17:37:21] "PUT /api/project/1/status HTTP/1.1" 403 2549. I have no clue of what's leading to the error. I applied the same logic to another PUT request in other page and I didn't have the issue. Can somebody explain please how I can manage the csrf token length? I'm not "manually" generating such token. I'll share the complete console error if helps: index.js:25 … -
how to classify based on a column values from database in django
i wanted to classify some data from database and show it in a table this is how get the data <tbody> <tr class=""> {% for c in cluster %} <td>{% if c.hasil_klasifikasi == 'Banyak Terjangkit' %}{{ c.nama_penyakit }}{% endif %}</td> <td>{% if c.hasil_klasifikasi == 'Kurang Terjangkit' %}{{ c.nama_penyakit }}{% endif %}</td> </tr> {% endfor %} </tbody> but the results dont looks right result on the table any help would be very much appreciated, thanks i was trying to classify the data in the table without blank cell like that i want to get the data like this here -
Django gettext translation doesnt work on dinamic translations
Question: I am working on a Django application that supports multiple languages. I am using token-based authentication and trying to change the language for authenticated users based on their preference stored in their profile. However, I am encountering a few issues regarding how the translations are being applied, particularly when it comes to dynamic message translations. What I have: I have set up multiple languages in settings.py (LANGUAGES) and configured the default language to be English (LANGUAGE_CODE = 'en'). I am using token-based authentication (rest_framework.authtoken) to authenticate users. The user’s preferred language is stored in the database as preferred_language. I have added a custom middleware to handle language switching based on the user’s preference, which should be applied as soon as the user is authenticated and the session is set. Problem: Language preference seems to be applied for static content (like templates), but dynamic translations for strings in views (using gettext) are not applying correctly after the user’s preferred language is set. For example, while the language change works partially (like UI content), messages generated using gettext() (like error or success messages) are still showing in the default language (en), not the user's preferred language (e.g., es for Spanish). Here … -
OperationalError. Django tries to access a non-existent table
Building a e-commerce site with django. When I try to add a new element into the products model in the django interface and click the save button, this is what I get(refer to the pic below via the link). It says 'no such table: main.auth_user_old', but I don't know why it tries to access a non-existent, unnecessary table. Help me to solve this issue I tried upgrading the django library, made several migrations and even built the project again from scratch, none of it helped. I've checked the database, the closest thing to the specified table is auth_user and not auth_user_old. Screenshot of the error page -
403 error with CSRF when accesing Django login by axios
await axios.get("http://localhost:8000/get_csrf_token/").then((res)=>{ console.log(res.data.csrf_token); axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; axios.post('http://localhost:8000/login/',{ username:'admin', password:'Kv79NExi' }, { headers: { 'Content-Type': 'application/json', 'X-CSRFToken': res.data.csrf_token, } }) .then((response) => { log("response login",response.data); }); }); I am trying to access django login, however it shows the error like this, <p>Reason given for failure:</p>\n' + ' <pre>\n' + ' CSRF cookie not set.\n' + ' </pre>\n' + It returns 403 error, it looks like sending csrf_token correctly. Where am I wrong? Ran all test suites matching /TopPage/i. node:internal/process/promises:288 triggerUncaughtException(err, true /* fromPromise */); ^ AxiosError { message: 'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: { transitional: { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false }, adapter: [ 'xhr', 'http', 'fetch' ], transformRequest: [ [Function: transformRequest] ], transformResponse: [ [Function: transformResponse] ], timeout: 0, xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFTOKEN', maxContentLength: -1, maxBodyLength: -1, env: { FormData: [Function: FormData] { LINE_BREAK: '\r\n', DEFAULT_CONTENT_TYPE: 'application/octet-stream' }, Blob: [class Blob] }, validateStatus: [Function: validateStatus], headers: Object [AxiosHeaders] { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'X-CSRFToken': '9aSiDra8P3LzU0hMlSFZ9yqX5fllDySQljBRyHM6jjSYfuZ1BWrCUF9blkElzl1v', 'User-Agent': 'axios/1.7.9', 'Content-Length': '42', 'Accept-Encoding': 'gzip, compress, deflate, br' }, withCredentials: true, method: 'post', url: 'http://localhost:8000/login/', data: '{"username":"admin","password":"Kv79NExi"}' }, request: <ref *1> ClientRequest { _events: [Object: null prototype] { abort: … -
Why is related_name required for annotation?
I'm struggling to understand why related_name is required in order to do annotation. When trying to obtain the count of related object as annotation, one could use the below: class ModelA(models.Model): (...) class ModelB(models.Model): model_a_fk = models.ForeignKey(ModelA, related_name="model_bs") ModelA.objects.annotate(num_model_b=Count('model_bs')).order_by('-num_model_b') Why is the related_name required on the model and can't we just use the below? ModelA.objects.annotate(num_model_b=Count('model_a_fk_set')).order_by('-num_model_b') As this yields following error: FieldError: Cannot resolve keyword 'model_a_fk_set' into field. Choices are: id, (...) -
Why is the request URL / HTTP_REFERRER in Django error from an external domain?
TL;DR Was getting a Django error because I wasn't properly redirecting authenticated users making GET requests to my login endpoint (fixed this problem); however, I'd like to understand why the Request URL / HTTP_REFERRER in the error message was an external domain. Background I've been getting a few Django server errors per month in my production web app that list sendgrid.net as the Request URL (as well as the HTTP_REFERRER). I realized that some of my transactional email templates were turning links into strange sendgrid URLs for clicktracking, so I added clicktracking="off" to all the anchor elements in my templates to avoid this. However, the errors have persisted. Current Problem Today I tried navigating to https://example.com/login/ when I was already logged in, expecting it to redirect me to my user profile page but instead it triggered a 500 error. When I looked at the error readout that was automatically emailed to me from my Django app, the Request URL / HTTP_REFERRER was not https://example.com/login/ but rather a subdomain of sendgrid.net (see below). The error was being triggered on my view called CustomLoginView: Exception Type: NoReverseMatch at /login/ Exception Value: Reverse for 'member-detail' with no arguments not found. 1 pattern(s) tried: … -
Files get served when django website is ran locally, but not when run on heroku
When I run my django website locally all my MEDIA files get served via AWS, but I now uploaded my website to heroku, and it keeps trying to load the files locally instead of AWS, how to fix this? Settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" CRISPY_TEMPLATE_PACK = "bootstrap5" LOGIN_REDIRECT_URL = 'home' LOGIN_URL = 'login' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = 'eu-north-1' #change to your region AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' django_heroku.settings(locals()) -
What is the correct AWS policy in order for my app allow users to login at AWS COGNITO?
I am using Django Warrant for IAM: from rest_framework.response import Response from rest_framework.exceptions import AuthenticationFailed from rest_framework.decorators import api_view from django.apps import apps @api_view(['POST']) def login(request): username = request.data.get('email') password = request.data.get('password') if not username or not password: raise AuthenticationFailed('Username and password are required.', code=401) pool_id = getattr(settings, 'COGNITO_USER_POOL_ID', None) app_id = getattr(settings, 'COGNITO_APP_ID', None) region = getattr(settings, 'COGNITO_REGION', None) key = getattr(settings,'COGNITO_AWS_KEY',None) secret = getattr(settings,'COGNITO_AWS_SECRET',None) cognito = Cognito( user_pool_id=pool_id, client_id=app_id, user_pool_region=region, access_key=key, secret_key=secret, username=username ) try: cognito.authenticate(password=password) except Exception as e: print(e) raise AuthenticationFailed(str(e), code=401) # Return tokens return Response({ "access_token": cognito.access_token, "refresh_token": cognito.refresh_token, }, status=201) But despite my authentication being sucessfull: aws cognito-idp admin-initiate-auth --user-pool-id eu-west-1_XXXXXX --client-id XXXXXXXX --auth-flow ADMIN_NO_SRP_AUTH --auth-parameters USERNAME=YTYY,PASSWORD=YYYY Return The nessesary credentials: { "ChallengeParameters": {}, "AuthenticationResult": { "AccessToken": "XXXXXXXXXX...XXXXXX", "ExpiresIn": 3600, "TokenType": "Bearer", "RefreshToken": "XXXDDDXXXX", "IdToken": "XXXSSSXXX" } } But the view above return: { "detail": "An error occurred (NotAuthorizedException) when calling the InitiateAuth operation: Password attempts exceeded" } Responding with a 401, My IAM permissions are: { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowAdminUserPoolActions", "Effect": "Allow", "Action": [ "cognito-idp:AdminInitiateAuth", "cognito-idp:AdminRespondToAuthChallenge", "cognito-idp:AdminGetUser", "cognito-idp:AdminSetUserPassword", "cognito-idp:ListUserPools", "cognito-idp:GetUser", "cognito-idp:ListGroups", "cognito-idp:AdminAddUserToGroup" ], "Resource": "arn:aws:cognito-idp:eu-west-1:962331388720:userpool/eu-west-1_XXXXXX" } ] } What I am missing I suspect my policy is wrong. But … -
AWS Elastic Beanstalk: Connection Refused
I have deployed my django app to AWS Elastic Beanstalk, using the Docker platform. I have created a postgresql database with RDS, issued an EC2 connection from this database to the EC2 instance my Elastic Beanstalk is running on (ensuring it is part of the same VPC and subnets). The root volume for my Elastic Beanstalk container is gp3 with IMDSv1 disabled. I have assigned two security groups, one of them contains the following settings to allow for connections through NGINX and to my database: The other is the default security group. All environment variables are configured, including those required for access to my RDS Database, and AWS Access Keys for S3 buckets. However, when I go to the Elastic Beanstalk provided domain, I am shown a page saying "This site can't be reached. Connection refused". I am unsure if this may be related to my docker-compose file (something to do with networking or ports perhaps) which looks as follows: version: '3.8' services: web: build: context: . dockerfile: Dockerfile restart: always volumes: - media-data:/usr/src/media - static-volume:/usr/src/staticfiles command: gunicorn APPNAME.wsgi:application --bind 0.0.0.0:8000 -w 3 --timeout 120 ports: - "8000:8000" environment: DJANGO_SETTINGS_MODULE: "APPNAME.settings" AWS_REGION: ${AWS_REGION} env_file: .env nginx: build: ./nginx volumes: - … -
How to display 2 featured and 8 organic products per page in Django based on rank and search query?
I’m working on a Django-based e-commerce application where products have fields like is_featured (boolean) and rank (integer). The goal is to create a paginated search results view where: After searched each page displays 10 products in total. The first 2 products should always be featured (is_featured=True) and sorted by their rank. The remaining 8 products should be organic (is_featured=False) and also sorted by their rank. The products must match the search query (e.g., filtering by title or content). Ensuring this logic works efficiently, especially with large datasets. Dynamically adjusting the number of organic products to fill the rest of the page if fewer than 2 featured products are available. I want to do with caching -
html.parser and django issues
I would like to know if there are any known issues using the html.parser with django, readin The Docs and searching internet i've found nothing. I know I should post my code but its long and is spread over multiple modules; views, models, etc. My app is simple, the user uploads html file, the django app parses and writes to database. the parsing app works perfectly locally. If I use lxml parser one of my 3 html test files parses fine, the other two .sourceline returns None. If I use the html.parser or the html5lib parser a different file works, but with the other two I get bad gateway error. Its perplexing because the app works consistently locally -
How to query a reverse foreign key multiple times in Django ORM
Assuming the following models: class Store(models.Model): name = models.CharField(max_length=255) class Stock(models.Model): name = models.CharField(max_length=255) store = models.ForeignKey(Store, on_delete=models.PROTECT) class Consignment(models.Model): cost = models.FloatField() class Order(models.Model): quantity = models.IntegerField() stock = models.ForeignKey(Stock, on_delete=models.PROTECT) consignment = models.ForeignKey(Consignment, on_delete=models.PROTECT) How to create a queryset of all 'consignments' of all instances of a specific 'stores' queryset like so: target_stores = Store.objects.filter(name__startswith="One") consignments = target_stores.consignments.all() -
Migrations not getting applied , deleted the migrations folder in django
I deleted the migrations folder in one of my app folders of the project now when I run makemigrations I am getting No changes detected ..please help I was expecting that migrations folder will be created with the migration files -
Django on PythonAnywhere: ImproperlyConfigured: The SECRET_KEY setting must not be empty
I’m hosting a Django project on PythonAnywhere and encountering the following error when running makemigrations: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. My Setup: Hosting Platform: PythonAnywhere Environment Management: Using a .env file to manage secrets Python Version: 3.10 Django Version: 5.1.2 In my WSGI file, I’ve included the following code to load the .env file: import sys from dotenv import load_dotenv path = '/home/verbsmerch/verbs_backend' project_folder = os.path.expanduser(path) load_dotenv(os.path.join(project_folder, '.env')) In my settings I load the SECRET_KEY like this: SECRET_KEY = os.getenv("SECRET_KEY") What I’ve Tried: Verified that the .env file exists and is located in the correct directory. Checked that the .env file has the correct permissions (chmod 600). Ran a Python shell to debug: from dotenv import load_dotenv import os load_dotenv('/home/verbsmerch/verbs_backend/.env') print(os.getenv("SECRET_KEY")) # This prints the correct key Reloaded the web app from the PythonAnywhere Web tab. Why is Django unable to load the SECRET_KEY when it seems to work in the Python shell? How can I resolve this error? -
Approach for Handling Unfinished Chess Games When Both Players Disconnect
I need to figure out what to do if both players leave the game without finishing it. In this case, I need a solution to preserve the current game state and determine when the game should be considered over. Solution 1: Storing the Game in Redis Store the game state in Redis in case one of the players returns. When a player re-enters the game, check the state. If the time hasn't expired, continue the game; if it has, automatically end it. Solution 2: Timer via Celery Set up a Celery task that starts a timer when both players leave. If neither player returns within the given time, the game is automatically considered finished, and the result is recorded. I would appreciate any recommendations on how to solve this problem more effectively and would like to know how such situations are typically handled in production environments.