Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form field labels are not displaying in the template
whats wrong with this code? labels are not displaying in the 'single-project.html' template. can anyone tell the mistake in this code.what should i correct it to display my labels in my template. My forms file class ReviewForm(ModelForm): class Meta: model = Review fields = ['value', 'body'] labels = { 'value' : 'Place your vote', 'body' : 'Add a comment with your vote' } def __init__(self, *args, **kwargs): super(ReviewForm, self).__init__(*args, **kwargs) for name,field in self.fields.items(): field.widget.attrs.update({'class': 'input'}) My views file def project(request,pk): projectObj = Project.objects.get(id=pk) form = ReviewForm() return render(request,'projects/single-project.html', {'project' : projectObj, 'form':form,}) My template file {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#textarea">{{field.label}}</label> {{field}} </div> {% endfor %} solution to this problem -
REACT Component for Car Dealerships Page Not Visible
I am working through IBM Coursera's Full Stack Developer course and am stuck on the Car Dealership application Capstone Project. Specifically, I am struggling to make the car dealerships visible on the dealers page. A semicolon appears on the page. This makes it seem as though the Dealers.jsx React component is not correctly rendering, but that was provided by IBM so I would not think that contains any errors. Current output of Dealerships page Dealers page output Dealers.jsx React component (provided by IBM) import React, { useState, useEffect } from 'react'; import "./Dealers.css"; import "../assets/style.css"; import Header from '../Header/Header'; import review_icon from "../assets/reviewicon.png" const Dealers = () => { const [dealersList, setDealersList] = useState([]); // let [state, setState] = useState("") let [states, setStates] = useState([]) // let root_url = window.location.origin let dealer_url ="/djangoapp/get_dealers"; let dealer_url_by_state = "/djangoapp/get_dealers/"; const filterDealers = async (state) => { dealer_url_by_state = dealer_url_by_state+state; const res = await fetch(dealer_url_by_state, { method: "GET" }); const retobj = await res.json(); if(retobj.status === 200) { let state_dealers = Array.from(retobj.dealers) setDealersList(state_dealers) } } const get_dealers = async ()=>{ const res = await fetch(dealer_url, { method: "GET" }); const retobj = await res.json(); if(retobj.status === 200) { let all_dealers = Array.from(retobj.dealers) let … -
Failed to execute 'setRemoteDescription' on 'RTCPeerConnection' on webrtc
So I am following the tutorial by TauhidCodes on youtube here: https://www.youtube.com/watch?v=MBOlZMLaQ8g It is a little different because I am using reverse urls for the different room names. I am implementing a video call system that allows more than 3 users and above to join by entering the appropriate url like https://127.0.0.1:8000/video/test/. I open 2 tabs in the same window and press start call for both of them and they both say the error. Error test/:1 Uncaught (in promise) InvalidStateError: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: stable <!DOCTYPE html> <html> <head> <style> button { border: 0; background-color: orange; padding: 10px; color: white; border-radius: 7px; } video { border-radius: 15px; } .videoContainer { display: flex; margin: 20px; width: 640px; } .videoContainer h2 { color: white; position: relative; bottom: -380px; left: -350px; width: max-content; } #meet { display: flex; } #recordButton.recording { background-color: red; } #downloadButton { background-color: #4caf50; } button:disabled { background-color: #cccccc; cursor: not-allowed; } </style> <title>A Free Bird Video Call</title> <script src="https://meet.jit.si/external_api.js"></script> </head> {% load static %} <body> <div id="meet"> <button id="videoOff" onclick="toggleVideoOff()" disabled>Video Off</button> <button id="audioMute" onclick="toggleAudioMute()" disabled>Mute Audio</button> <div id="remote-videos"> <div id="videoContainer"> <video id="localVideo" autoplay playsinline></video> <h2>{{ … -
what has happened to the add view in Wagtail 6.x
Upgrading from Wagtail 5.2.6 to Wagtail 6.3 LTS, I noticed that the methods add and edit that were here are no longer there: wagtail.images.views.images What happened to them? Were they moved or replaced? -
Linked tables/models in Django - more than Foreign Keys
I am designing a Django project, where I need the following (I want to implement something more complex, but simplified here): Table: work_order Columns: owner_id, ..., contract_file_id (maps to 'all_files.id') Table: labour_license Columns: owner_id, ..., license_file_id (maps to 'all_files.id') Table: all_files Columns: id (UUID4Field), category (CharField, 'contract' if linked to 'work_order.contract_file_id', 'labour_lic' if linked to 'labour_license.license_file_id') file (FileField) ... Anytime a file is uploaded to work_order, it should insert a row in all_files with category='contract'; similarly for labour_license. Anytime a file with a particular UUID4 is to be accessed, I would like to query back the owner_id (in work_order table if all_files.category='contract'; similarly for labour_license. I have literally 10s of file fields like this, and I would like to write some kind of Mixin or custom Field, or even a metaclass if required, which I can use for all such file fields. If it is possible, would appreciate some ideas or directions I can look into. -
I am generating the pdf file in django, here i am using @font-face for USPSIPStandard for just one <p> tag, but it is affecting the whole pdf
I am generating the pdf reports for the patient using wkhtmltopdf in Django, and i have to show the patient imb_code in USPSIPStandard font family ,I am using its file in Static folder, when use this @font-face in my html file, this is affecting the tag styling,(not the text showing in USPS format but only the style is changing) but i am not using this font face on this pre tag, <style> @font-face { font-family: 'USPS_IMB_Standard'; src: url("{{ usps_font }}") format('truetype'); } /* Apply only to specific class */ .usps-barcode { font-family: 'USPS_IMB_Standard', sans-serif; } </style> // Here is pre tag <pre style="padding: 10px 5px; font-size: 12px"> {{statement.statement_data}}</pre> // Here using this font family: <div> <p class="usps-barcode" style="font-size: 14px; margin: 5px 5px 0px; padding: 0px; margin-left: 1px;"> {{ patient.imb_encode }} </p> </div> but when i remove this : @font-face { font-family: 'USPS_IMB_Standard'; src: url("{{ usps_font }}") format('truetype'); } it show the pre tag content in proper format,why font-face is affecting the pre tag, altough i am not applying it on pre tag , as i also define the default body and * font-family -
Store ONNX Models in PostgreSQL with Django
I am working on a Django project where I need to store ONNX models in a PostgreSQL database. Currently, I am considering using a BinaryField to store the model files as blobs, but I get a memory error. Is there a more efficient or Django-friendly approach to storing ONNX models in PostgreSQL? -
Looking for Inspiration & Recommendations for My Upcoming POS Project using Django [closed]
👋 I'm planning to build a Point of Sale (POS) system using Django, and I’m looking for recommendations and inspiration. I want to make it efficient, user-friendly, and scalable. Are there any open-source POS projects in Django that you'd recommend for reference? -
In django transactions, what happens if an error is raised in on_commit?
Situation I have a postgres database, and I'm using django transaction's on_commit hook to do something (in this case move a file but it doesn't really matter what for the purposes of the question) once the save of a model has been committed to the database. from django.db import models, transaction def my_oncommit_callback(): # Do something on commit raise ValueError("what if I raise an error") class MyModel(models.Model): def save(self, *args, **kwwargs): transaction.on_commit(my_oncommit_callback) super().save(*args, **kwargs) The Question If my_oncommit_callback raises an error, is the transaction rolled back, or will I get a broken state because my on_commit function hasn't worked as expected? -
pytest_django model class attribute not filled for __init_subclass__
I have a specific problem. class A: SOME_ATTR: int def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) attr = getattr(cls, "SOME_ATTR", None) if not attr: raise TypeError(f"Class '{cls.__name__}' must define 'SOME_ATTR'") classB(models.Model, A): SOME_ATTR = 0 In this case everything works as expected but pytest tests. pytest_django creates: cls = <class 'fake.B'> which has no attribute 'SOME_ATTR' Is there any option to enforce it? I'v tried to add a session scope autouse fixture but it didn't work as it happens before it. -
How to Structure a Django Project for a Multi-questuinnaire System and Import Questions in Bulk?
I'm building a Django project that will host dozens of questionnaires. I have a few architectural and implementation questions: 1)Should I create a separate app for questionnaires and another app for test takers within the main Django projectand put models like User _Answer and Test_Result within the test takers app itself? 2)In the test model, how can I design the database structure to handle different question types? Some questions are only text-based, some are only image-based, and some contain both text and images. 3)Since each test may contain hundreds of questions, manually entering them via the Django admin panel is impractical. Is there a way to bulk import questions from a Word document? I appreciate any insights or best practices for handling these challenges in Django. -
Django TypeError: 'Category' object is not iterable in template loop
1️⃣ Problem Description: I'm working on a Django project where I'm trying to display a category and its associated products. However, I'm getting the following error in my template: 2️⃣ Error Message: TypeError at /category/2/'Category' object is not iterableRequest Method: GETRequest URL: http://127.0.0.1:8000/category/2/Django Version: 5.1.4Exception Type: TypeErrorException Value: 'Category' object is not iterableException Location: C:\Users\brahm\OneDrive\Desktop\Django\one\Lib\site-packages\django\template\defaulttags.py, line 198, in renderRaised during: accounts.views.categoryPython Executable: C:\Users\brahm\OneDrive\Desktop\Django\one\Scripts\python.exePython Version: 3.11.5Python Path: ['C:\Users\brahm\OneDrive\Desktop\Django\one\Scripts\user_authincation','C:\Program Files\Python311\python311.zip','C:\Program Files\Python311\DLLs','C:\Program Files\Python311\Lib','C:\Program Files\Python311','C:\Users\brahm\OneDrive\Desktop\Django\one','C:\Users\brahm\OneDrive\Desktop\Django\one\Lib\site-packages']Server time: Wed, 26 Feb 2025 06:25:55 +0000 3️⃣ My Django View (views.py): `def category(request,id): categories =Category.objects.get(id=id) products=Product.objects.filter(category=categories) context={ 'categories':categories, 'products':products, } return render(request,'category.html',context)` 4️⃣ My Django Template (category.html): {% for category in categories %} <a class="nav-link" href="/category/{{category.id}}/">{{category.name}}</a> {% endfor %} urls.py urlpatterns=[ #path('home',home,name='home'), #path('',register,name='register'), #path('login/',login_user,name='login'), #path('logout/',logout_user,name='logout'), path('category/<int:id>/',category,name='category'), ] models.py class Category(models.Model): name=models.CharField(default='uncategorized',max_length=100) is_active=models.BooleanField(default=True) def __str__(self): return self.name class Product(models.Model): category=models.ForeignKey(Category,on_delete=models.CASCADE,related_name='categories') product_name=models.CharField(max_length=120) img=models.ImageField(upload_to='photos/') created_date=models.DateTimeField(auto_now=True) desc=models.TextField() price=models.CharField(max_length=8) def __str__(self): return self.product_name 5️⃣ Expected Behavior: I want to display the category name and list of products under it. 6️⃣ Issue: Since category is a single object, it is not iterable, but my template uses {% for category in categories %}. 7️⃣ My Question: What is the correct way to access a single object in a Django template? Should I change my view … -
Django-storages inserting bucket name as a folder
I'm migrating to Django 5.1.6 (django-storages 1.14.5) from Django 3.2 using DigitalOcean S3-compatible Spaces and when I run python manage.py collectstatic the bucket name is being inserted as a folder when it used to not be. I want it to be stored in myBucket as /static/myFile.png, but it's being stored as /myBucket/static/myFile.png instead. In my settings.py file: STORAGES = { "default": { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "storages.backends.s3boto3.S3Boto3Storage", "OPTIONS": { "secret_key": "mySecretKey", "access_key": "myAccessKey", "bucket_name": 'myBucket', "endpoint_url": 'https://mySubdomain.sfo2.digitaloceanspaces.com/', "object_parameters": {'CacheControl': 'max-age=86400'}, "location": 'static', "default_acl": 'public-read', }, }, } STATIC_URL = "https://mySubdomain.sfo2.digitaloceanspaces.com/static/" Am I doing something wrong or is this a bug in the django-storages? -
How do I pass data from 2 datasets to a Django view?
I have a simple Django project that consists of 3 datasets: Members --< mem_ev >-- Events such that any Member can go to any number of events and any event can have many members (ie a classic many to many relationship). I have the members, events, members per event and events per member templates working but I want to pass a count of the number of events per member in the main members list (list.html). Given the following file structures how do I capture event_count per Member and how to I pass that to the relavant template (list.html)? My app:urls.py file is: app_name = 'wf' urlpatterns = [ path('',views.members_list,name='member-list'), path('home/',views.members_list,name='member-list'), path('events/',views.events_list,name='event-list'), path('about/',views.about,name='wf-about'), path('event_detail/<int:id>/',views.event_detail,name='event_detail'), path('list_event_members/<int:id>/', views.list_event_members, name='list_event_members'), path('list_member_events/<int:id>/', views.list_member_events, name='list_member_events'), ] My views.py file is: def members_list(request): members = Member.objects.all() event_count = ?? What goes here ?? <------ return render(request,'wf/list.html',{'members':members},{'event_count':event_count}) def events_list(request): events = Event.objects.all() return render(request,'wf/events.html',{'events':events}) def event_detail(request,id): event = Event.objects.get(id=id) return render(request,'wf/event_detail.html',{'event':event}) def about(request): return render(request,'wf/about.html') def list_event_members(request,id): event_members = Member.objects.filter(mem_ev__event_id=id) return render(request,'wf/list_event_members.html',{'event_members':event_members}) def list_member_events(request,id): member_events = Event.objects.filter(mem_ev__member_id=id) return render(request,'wf/list_member_events.html',{'member_events':member_events}) and the relvant template file (list.html) is: {% extends "wf/base.html" %} {% block content %} <h2>Members</h2> <table width="100%" cellpadding=8 style="border:1px solid black;"> <thead class="table-success"> <tr style="border:1px solid black;"> <th … -
django-ckeditor5 showing question mark instead of symbols
hi recently i switched to django-ckeditor5 and in the HTML code I'm using this - my_project/ │── manage.py │── my_project/ │── app/ │ │── models.py ... ... but after saving code it is displaying like this my_project/ ??? manage.py ??? my_project/ ??? app/ ? ??? models.py ... ... why │── is replaced by ?. in development server it is showing correctly but in production there is issue that is coming. -
rerro context_processors in django
dictionary update sequence element #0 has length 0; 2 is required I have a module called context_processors that when enabled does not appear on the login page and gives an error But when I disable it, the login page appears context_processors.py: import datetime from django.contrib.auth.decorators import login_required from permission.models import UserPermission from salemali.models import Salemali from term.models import Term from user.models import Branch @login_required def date_context_processor(request): if request.user.is_authenticated: current_datetime = datetime.datetime.now() term = Term.objects.filter(status=1).order_by('-datestart') salemali = Salemali.objects.all() branch = Branch.objects.all() user_permissions = UserPermission.objects.filter(user=request.user).values_list('permission__name', flat=True) return { 'current_day': current_datetime, 'terms': term, 'salemali': salemali, 'branch': branch, 'user_permissions': user_permissions } setting.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'dashboard.context_processors.date_context_processor', ], }, }, ] -
How can i get the id from request body in django
def index(request): form = Postform() if request.method == 'POST': template_string = request.POST.get("body") >! here i want the id for some reason print("Original", template_string) rendered_content = render_template_content(template_string) print("Rendered", rendered_content) form = Postform(request.POST) if form.is_valid(): post = form.save(commit=False) post.body = rendered_content post.save() form = Postform(initial={'body':rendered_content}) else: form=Postform() return render(request, 'index.html', {"form": form}) I am using CKeditor in the frontend and is sending the whole text area in body {{product.name.1}} i want to extract this id -
How to limit google maps auto complete to only one country?
I have tried everything so my search input only gives autocomplete options from only Dominican Republic but I have not been able to achieve it, anyone here knows how to do this? <input type="text" id="searchInput" class="form-control" placeholder="Search for a location..." > let autocomplete; const input = document.getElementById('searchInput'); autocomplete = new google.maps.places.Autocomplete(input, { types: ['(cities)', 'geocode'], // Allow both city and address searches componentRestrictions: { country: 'do' } }); // Handle place selection autocomplete.addListener('place_changed', function() { const place = autocomplete.getPlace(); if (!place.geometry) { return; } -
django app: how to read a bit of html in javascript
I have a django app that has an design issue I'd like to fix: a script wants to inject a piece of html that contain django tags. What we have now works, but has some unfortunate aspects: Save the script as an html snippet that is nothing but a script: the first line is <script> and the last line closes that script. Pages which use this script import it just like any html snippet. This script sets a local variable to the html bit, as a long string, then finds where the html bit is wanted, and calls insertAdjacentHTML to insert it. So the snippet is an html file that contains nothing but a script, and that script in turn contains hard-coded html as a string. This is confusing to read and prevents our javascript and html linters from working on this snippet. But the code works, and the script can be used by any page by simply importing the one snippet. Is there a cleaner solution? My ideal solution would: Store the html bit in an html file. Store the script in a .js file. Allow pages that use the script to just load the script. I have tried … -
Why isn't the create method in my custom manager working?
I'm trying to create a custom manager for a model class in my Django project. The model classes Story and Plot have a one-to-one relationship. I want a new Plot instance to be automatically created when a new Story instance is created. Right now I do this through the view function, but it fails when testing Story object creation without the view function. I know there are a few ways to accomplish this, but I've decided to use a custom manager to add this post-creation logic by overriding the objects.create method. The relevant code is below: class Story(models.Model): ... other fields objects = models.Manager() class Plot(models.Model): ... other fields story = models.OneToOneField(Story, on_delete=models.CASCADE, null=True, default=None, related_name='plot') class StoryManager(models.Manager): def create(self, **kwargs): story = super().create(**kwargs) plot = Plot.objects.create( ... other kwargs, story_id=story.id ) return story # Assign the story manager to the Story model Story.objects = StoryManager() Now I'm getting the following traceback while running tests that use the Story.objects.create method: File "C:\Users\jacob\documents\programming\story-builder\storybuilder\app\models.py", line 221, in create story = super().create(**kwargs) File "C:\Users\jacob\documents\programming\story-builder\.venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^ File "C:\Users\jacob\documents\programming\story-builder\.venv\Lib\site-packages\django\db\models\query.py", line 669, in create self.model._meta._reverse_one_to_one_field_names ^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute '_meta' I'm new to the concept … -
Read data json in django
I am currently working on a project where users will be able to authenticate themselves thanks to a form that I protected with a csrf token, but for now I only take care of the server side party, here is the code: @api_view(['POST']) @csrf_protect @permission_classes([AllowAny]) def login(request): if request.method != "POST": return JsonResponse({"error": "Seules les requêtes POST sont autorisées."}, status=status.HTTP_405_METHOD_NOT_ALLOWED) try: # Lecture sécurisée des données data = json.loads(request.body) username = data.get("username") password = data.get("password") if not username or not password: return JsonResponse({"error": "Nom d'utilisateur et mot de passe sont requis."}, status=status.HTTP_400_BAD_REQUEST) # Recherche de l'utilisateur dans les deux tables user = None role = None try: user = Administrateur.objects.get(username=username) role = "admin" except Administrateur.DoesNotExist: pass if not user: try: user = Employes.objects.get(username=username) role = "employe" except Employes.DoesNotExist: pass if not user or not check_password(password, user.password): return JsonResponse({"error": "Identifiants incorrects."}, status=status.HTTP_401_UNAUTHORIZED) # Génération des tokens refresh = RefreshToken.for_user(user) # Réponse sécurisée response = JsonResponse({"username": user.username}) # Stocker le JWT dans un cookie HttpOnly sécurisé response.set_cookie( key='access_token', value=str(refresh.access_token), httponly=True, secure=True, samesite='Strict', max_age=3600 ) # Stocker le rôle pour le frontend response.set_cookie( key='user_role', value=role, httponly=False, secure=True, samesite='Strict', max_age=3600 ) return response except Exception as e: return JsonResponse({"error": f"Erreur inattendue : {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) … -
Why I am getting htmx:targetError when calling form.requestSubmit?
I am using htmx to load some content when openning an accordion in my django template. I initially include the cover card partial template and when I close the accordion I remove the whole partial template. Then whenever the accordion opens I dispatch a custom event to trigger the htmx swap and return the same partial template in the response. The code looks like this initially: ... <details open id="cover-card-section" hx-get="{% url 'update-cover-card' object.id %}" hx-swap="outerHTML" hx-target="#temp-cover-card-form" hx-trigger="open-cover-card-section"> <summary > Cover Card </summary> {% include "path/to/cover_card.html" %} {% comment %} Element to be replaced by actual cover card form {% endcomment %} <div id="temp-cover-card-form" style="display: none; align-items: center; justify-content: center; width: 100%; height: 200px;"> <svg width="40" height="40" stroke="rgba(0, 0, 0, 0.5)" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><style>.spinner_V8m1{transform-origin:center;animation:spinner_zKoa 2s linear infinite}.spinner_V8m1 circle{stroke-linecap:round;animation:spinner_YpZS 1.5s ease-in-out infinite}@keyframes spinner_zKoa{100%{transform:rotate(360deg)}}@keyframes spinner_YpZS{0%{stroke-dasharray:0 150;stroke-dashoffset:0}47.5%{stroke-dasharray:42 150;stroke-dashoffset:-16}95%,100%{stroke-dasharray:42 150;stroke-dashoffset:-59}}</style><g class="spinner_V8m1"><circle cx="12" cy="12" r="9.5" fill="none" stroke-width="3"></circle></g></svg> </div> </details> ... The cover card partial template looks like this: <div class="container" id="cover-card-form-container" style="max-width:700px;" puny-settings> <style> ... </style> <div> <form id='image-upload-form' hx-swap="none" hx-encoding='multipart/form-data' hx-post='/en/home/upload-card-image/'> {% csrf_token %} {{ form.image.errors }} {{ form.image.label_tag }} {{ form.image }} <div style="display: none; width: 100%; align-items: center; gap: 8px; margin-bottom: var(--pico-spacing)" id="progress-container"> <progress style="width: 50%; margin-bottom: 0" id="progress-bar" value="0" … -
How to make the function stop immediately, when in websocket stop requested?
I want to stop running the generating function immediately, whenever stop_requested in the websocket. class ImageGeneration(BaseAIGeneration): async def process(self, websocket, prompt): if websocket.stop_requested: return None await super().process(websocket, prompt) if websocket.stop_requested: return None response = await self.generate_image(prompt=prompt, model=self.model, size=size) if websocket_instance.stop_requested or not response: return None if response and isinstance(response, list): image_url = response[0].url return image_url And generate_image function currently is synchronous function async def generate_image( prompt: str, model: str, size: str = "1024x1024" ): response = await client.images.generate( model=model, prompt=prompt, size=size, n=1 ) return response.data Currently it waits until generate_image fully runs, and only then stops. I was thinking of creating a task, that will gonna check if the response: while not task.done(): if websocket_instance.stop_requested: task.cancel() await asyncio.sleep(0.1) But for me this solution looks weird, and I do not think it is the correct way, how to make the function stop immediately, when in websocket stop requested? -
Deploying Django API with Render keeps loging 400 bad request
I am trying to host my Django API with renders free tier I have specified all the env variables including renders domain in allowed origins but I still get 400 Bad Request responses from renders logs. logs: 127.0.0.1 - - [24/Feb/2025:22:47:56 +0300] "HEAD / HTTP/1.1" 400 143 "-" "Go-http-client/1.1" ==> Your service is live 🎉 127.0.0.1 - - [24/Feb/2025:22:48:09 +0300] "GET / HTTP/1.1" 400 143 "-" "Go-http-client/2.0" my settings.py ALLOWED_HOSTS = env.list("ALLOWED_HOSTS") CSRF_TRUSTED_ORIGINS = env.list("TRUSTED_ORIGINS") CORS_ALLOWED_ORIGINS = env.list("CORS_ALLOWED_ORIGINS") all env variables are supplied on renders environment tab but it still fails -
Django/Celery SQLite database locked on concurrent access
I have a local Django 5.1/Celery 5.4 project that is using SQLite. I am the only user. Certain model saves trigger a Celery task that queries (SELECT) for the updated record (using the Django ORM), then runs an API call to update a remote record based on the local data, and then runs another UPDATE locally. The task wraps all this inside of with transaction.atomic():. (The Celery worker is configured to run tasks in serial.) While this task is running, any attempts to write to the database result in a "database is locked" OperationalError. I have configured Django/SQLite with the latest "production-ready" settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': DB_DIR / 'db.sqlite3', 'OPTIONS': { 'init_command': """ PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA busy_timeout = 5000; PRAGMA temp_store = MEMORY; PRAGMA mmap_size=134217728; PRAGMA journal_size_limit=67108864; PRAGMA cache_size=2000; """, 'transaction_mode': 'IMMEDIATE', 'timeout': 20, }, }, } I was under the impression that with these settings, concurrent access was possible. "SQLite in Production" is the latest hotness, and these settings, especially the new-to-Django 5.1 'transaction_mode': 'IMMEDIATE' in OPTIONS, would allow writes to queue. What am I missing?