Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Javascript-Django: add atribute to signup form
I am working on a signup form in Javascript within a Django project. I have the following script: <div class="form-row"> <div class="col-md-6"> <div class="form-group"> <label class="large mb-1">First Name</label> {{ form.first_name }} </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="large mb-1">Last Name</label> {{ form.last_name }} </div> </div> </div> At this point I would like to add another input, e.g. phone number. So I was trying a wild guess such as: <div class="form-group"> <label class="large mb-1">Phone</label> {{ form.phone }} </div> But obviously it doesn't work. Any suggestion? Thank you! -
Why are we seeing incorrect timings in Datadog APM tracing for simple actions like a Redis GET?
We have Python Django application deployed to AWS EKS on EC2 instances. We use Gunicorn as our web server, although we recently ran Apache + wsgi and saw the same issues. The EC2 instances are m6a.xlarges, the containers themselves have 1500m CPU and 2048MB memory. We use Datadog APM tracing and we're tracking Redis calls. Occasionally we'll see a slow request, and when we look deeper we'll see in the trace a simple Redis GET query take 2.8 seconds! I've used Redis for years and I've never had a problem with it. It's lightening fast. And our platform produces very little load (CPU is around 2% on a small instance). I enabled slow logging in ElastiCache and we're seeing no results, so I know it isn't the Redis instance itself. What could be causing this? I know the timings in APM are based on ddtrace's own in-Python timings, so maybe our Python processes are getting bogged down somehow? CPU usage on the EC2 instances in general is very low, 10% tops. Memory usage is also low. I'm at a loss. We don't have over allocation, so I don't think it's that. -
Deploying Django + xlwings library
I'm trying to deploy a Django app which uses the xlwings dependency (windows only) on a server. Tried on Linux, but it does not support xlwings. So, now looking out for an easy way to set up the Deployment with Windows instead. Until now, I've really only been using PaaS offerings for deployment which did the work for me. Would appreciate it if somebody could describe the general approach (preferably on Azure) for making such a deployment as easy as possible. I've tried looking around various threads and google, but I fear this is not a common requirement. Thank you! -
How can I create a table or form with the addition of values from another table based on the selected values?
Good day! I have several model tables. And each subsequent table in the conditional hierarchy is one step lower than the previous one. I have one model that is planned to be filled from the form in the database. And I plan to create another table that will be filled based on the data from the first model. I plan to select an element from the form in the list - the first field and based on the selected value in the first field --->>> --->>> accordingly copy some values of the corresponding fields from the corresponding row of the model table. When selecting a certain field, take values from other fields of the same row and send them to another table of the model. Send them to another table of the model with the addition of other data. Conventionally speaking, this is like reproducing the first table into several. The second table can have 20 times more rows than the first. How can I create a table or form with the addition of values from another table based on the selected values? class CreateNewGPR (models.Model): name_object = models.IntegerField(verbose_name="Наименование объекта") name_working = models.CharField(verbose_name="Наименование работы") type_izm = models.CharField(choices=TYPE_IZMERENIYA, verbose_name="Единицы измерения") value_work … -
Can I use my DjangoCMS template in my AppHook application?
Context: I am trying to integrate an application in my djangocms website. As i want it seems totally integrated, i want my appHooked application to use the same template as my main DjangoCMS template (I am using an extends of djangocms-frontend/bootstrap5) Everything seemed OK, until my first POST. Problem: When i just go to an URL of my AppHook everything is fine. But if, inside a view, i try to redirect to another page of this same AppHook, the response is put inside an iframe, so i get my header, footer and menu doubled. You can see it on the screenshot.As it does not happen if i click on a link, this problems seems to be only on POST response. Am i wronf trying to use the same template ? Can we make an actual app, with post and response, to looks like it is a content on the CMS page ? To be clear : I would hope to continue to see the menu and footer when i am on my AppHooked application. Here is a bit of my code : ---- main_app(djangocms)/template/base.html --- {% extends "bootstrap5/base.html" %} [...] {% block content %} {% placeholder "Page Content" %} {% … -
Cloudinary image upload isssu with python, Django and DRF
I am trying to upload my produts image to cloudinay, I setting all thing correctly adding middleware but always my image saevd in locally -
How to update removed model choices in Django without breaking existing database values?
I'm working on a Django project where we use models.TextChoices for fields like current_status. Our client requested wording updates — for example, renaming "Contacted" to "Contacted for assessment", "Booked" to "Assessment booked", and so on. Previous Enum: class ClientStatus(models.TextChoices): CONTACTED = "Contacted" BOOKED = "Booked" Updated Enum: class ClientStatus(models.TextChoices): CONTACTED_FOR_ASSESSMENT = "Contacted for assessment", "Contacted for assessment" ASSESSMENT_BOOKED = "Assessment booked", "Assessment booked" Problem We already have hundreds of users in the database with: current_status = 'Contacted' Since "Contacted" no longer exists in the model choices: Will migrations fail or behave unexpectedly? Will the Django Admin or API views break when encountering these legacy values? What is the correct way to rename choice values without leaving inconsistent data? Constraints We want to avoid creating unnecessary migrations. We want this to work for all environments (dev/staging/production). We'd prefer not to break the Admin panel or serializers. Question What is the safest and most Django-idiomatic way to rename or remove enum values when old data already exists in the database? Is it okay to do manual SQL updates? Or is there a recommended Django migration approach? What I've Tried Ran python manage.py makemigrations and migrate. Migration did not fail. Admin view throws … -
React doesn’t receive API tokens after Google OAuth redirect via social_django/drf-social-oauth2
I'm implementing Google OAuth2 for my Django REST API with a React frontend. The basic flow is set up correctly. I have routes for: urlpatterns = [ path("admin/", admin.site.urls), path("api/v1/", include((v1_patterns, "v1"))), path("api/v1/auth/", include("social_django.urls", namespace="social")), path("api/v1/auth/token/", include("drf_social_oauth2.urls", namespace="oauth2")), ] Also I have: INSTALLED_APPS = [ ... "drf_yasg", "social_django", "oauth2_provider", "drf_social_oauth2", ... ] SOCIAL_AUTH_URL_NAMESPACE = "social" AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "social_core.backends.google.GoogleOAuth2", "drf_social_oauth2.backends.DjangoOAuth2", ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config("GOOGLE_OAUTH_CLIENT_ID") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config("GOOGLE_OAUTH_CLIENT_SECRET") SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ["email", "profile"] SOCIAL_AUTH_GOOGLE_OAUTH2_EXTRA_DATA = [ "email", "first_name", "last_name", "picture", ] LOGIN_REDIRECT_URL = "http://127.0.0.1:5173" # REST Framework general settings REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "drf_social_oauth2.authentication.SocialAuthentication", ) } For login, I sent a GET request from browser to http://localhost:8000/api/v1/auth/login/google-oauth2/ After sending the request, in the console I get: api_container | [24/Jun/2025 13:04:19] "GET /api/v1/auth/login/google-oauth2/ HTTP/1.1" 302 0 api_container | [24/Jun/2025 13:04:20] "GET /api/v1/auth/complete/google-oauth2/?state=KYTUm5yi1NheUmc095zaRqIc3mZjsOLp&code=4%2F0AUJR-x4dcWMTghJHjPc1QbiPrCFo5lo2u9l1cYJ47F61fB0kIkQe4I0DFAt33UZOPBBI8g&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&authuser=0&prompt=none HTTP/1.1" 302 0 After a successful login, I get redirected to my React app (127.0.0.1:5173) — but the problem is, no tokens (access or refresh) are passed to the client. I don’t know how to retrieve or send them so that React can authenticate future API calls. I can confirm that after login, the database records email, picture, first_name, last_name, and an access token (from Google), but React … -
How can I load values into the form from the desired table row by clicking?
Good day! I plan to build a mini application. Which consists of one page (the main one) - a template. And also one secondary page - on the second page I fill in information into the model table through a form. On the other page (the main one) - I display information in the form of a table. I plan to place the form next to the table. The most difficult thing is that in this form I would like to receive data and write/send data from a specific table row. For example, I click on an element in a table row and information appears in the form - the contents of this row that I clicked or pressed. Information appears loaded in the form, values from the table row - which can then be edited and the data can be written back into the table model. Can you think of something about this? I would be very grateful for any tips and help. <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>title</title> </head> <body> <div> <h4>Мероприятия</h4> </div> <br/> <div> <form method="GET" action="{% url 'table' %}"> {{ form.as_p }} <input type="submit" value="Submit" class="button" /> </form> </div> <br/> <div> <table style="font-family: Arial, … -
How to display a friend request button on each post?
I'm trying to make each post from all users have a friend request button for each specific user who uploaded post on homepage. This code below is what I have tried but friend request button is not displayed on each post. I have also tried using a boolean field but still same problem. What could I have been doing wrong? class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) class Post(models.Model): poster_profile = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, blank=True,null=True) caption = models.TextField(blank=True, null=True) class FriendRequest(models.Model): from_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='from_user') to_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='to_user') def ForYouView(request): page_title = "For You" poster_profile = Post.objects.all() all_profile_users = [] button_status_list = [] for user_obj in p: u = user_obj.user all_profile_users.append(u) # sent_friend_requests = FriendRequest.objects.filter(from_user=u) # rec_friend_requests = FriendRequest.objects.filter(to_user=u) friends = Profile.objects.filter(user=request.user, friends__id=user_obj.id).exists() button_status = 'none' if not friends: button_status = 'not_friend' if len(FriendRequest.objects.filter( from_user=request.user).filter(to_user=u)) == 1: button_status = 'cancel_request_sent' if len(FriendRequest.objects.filter( from_user=u).filter(to_user=request.user)) == 1: button_status = 'follow_back_request' button_status_list.append(button_status) context = { 'page_title': page_title, 'poster_profile': poster_profile, 'profile_and_button_status': zip(p,button_status_list), 'u': all_profile_users, } return render(request, 'foryou.html', context) {% if poster_profile %} {% for user in poster_profile %} <div>{{ user.poster_profile }}</div> {% if not user == request.user %} {% for user in profile_and_button_status %} {% if user.1 == 'not_friend' %} <a href="" class="friend-request"> <button type="button" class="btn"> … -
I have this while running django
error faced (venv) PS C:\Users\Personal\Desktop\Onblu_VW1_API\api_vw1> python manage.py makemigrations Traceback (most recent call last): File "C:\Users\Personal\Desktop\Onblu_VW1_API\api_vw1\manage.py", line 22, in <module> main() File "C:\Users\Personal\Desktop\Onblu_VW1_API\api_vw1\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\Personal\Desktop\Onblu_VW1_API\venv\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Personal\AppData\Local\Programs\Python\Python312\Lib\importlib\__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 991, in exec_module File "<frozen importlib._bootstrap_external>", line 1129, in get_code File "<frozen importlib._bootstrap_external>", line 1059, in source_to_code File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed SyntaxError: source code string cannot contain null bytes -
How to send OTP to Gmail using Django Rest Framework? [closed]
I'm trying to implement an OTP verification system using Django Rest Framework (DRF). The goal is to send a 6-digit OTP to the user's Gmail address during registration or login. Here's what I've done so far: Generated a random 6-digit OTP using Python. -
How to pass pk to form (ForeignKey) and views - from template when following link?
How to pass pk to the form (ForeignKey) and views - from the template when clicking on a link? Good day! I have a model. Which is displayed in the template. And the transition to another template is configured by a link. But my form is not displayed there. I also wanted to ask how I can pass (pk) to the form in order to enter data only for the object by which the transition was made by the link? I click on the link and get to a specific object. I wanted to fill in its properties through the form. How can I fill in specifically for the object by (pk) that I clicked on the link to the view and form? For some reason, my form is not displayed. class ArkiObject_1 (models.Model): city = models.CharField(choices=TYPE_CITY, verbose_name="Городской округ") nameobject = models.TextField(verbose_name="Наименование объекта") typeobject = models.CharField(choices=TYPE_OBJECT, verbose_name="Тип объекта") param_1 = models.FloatField(verbose_name="Мощность котельной, МВт") param_2 = models.FloatField(verbose_name="Диаметры трубопроводов, мм") def __str__(self): return self.nameobject class ArkiGpr (models.Model): name = models.ForeignKey(ArkiObject_1, on_delete=models.CASCADE) work = models.TextField(verbose_name="Наименование работы") peoples = models.IntegerField(verbose_name="Количество людей") --- class FormOne (forms.ModelForm): class Meta: model = ArkiObject_1 fields = "__all__" class Form_GPR (forms.ModelForm): class Meta: model = ArkiGpr fields = "__all__" … -
Best practice to create a django user connected to a stripe customer
I'm trying to create a simple website for selling a digital good. Frontend is html/js, backend is django (using allauth, with simple email registration and a Custom User model) and I'm using stripe to handle payments. I've implemented a checkout workflow where a (anonymous) user can order via the hosted stripe checkout. However in order to properly handle the user's access to the digital goods, I need to somehow sync the stripe customer to a django user. The workflow, respectively best practice for this is unclear to me. Should I create a checkout session for the anonymous user and then use the stripe webhook confirmation to create a user (maybe sending the user a login link)? (What if the email has a typo?) Should I create a local user first, then via strip API a stripe customer (mapping the id as meta-data) and include the customer_id in the checkout? (seems clunky with multiple steps for the user, when they don't have an account yet) Something else from the stripe API (PaymentIntent)? ...? What are best practices for this? What are advantages / disadvantages of the respective approaches? I'm aware that this is a bit vague and will depend on the … -
Routing Problem from sign in page to a users account
The Issues is routing a user after creating an account on the webapp platform to the users dashboard created for the user. I can provide with the sign in and authcontext.js page which helps with this. signin.js import React, { useState, useEffect } from 'react'; import { Link, useNavigate, useLocation } from 'react-router-dom'; import { useAuth } from '../../../contexts/AuthContext'; import './Login.css'; const Login = () => { const [formData, setFormData] = useState({ email: '', password: '' }); const [error, setError] = useState(''); const [loading, setLoading] = useState(false); const { login, isAuthenticated } = useAuth(); const navigate = useNavigate(); const location = useLocation(); // Redirect if already logged in useEffect(() => { if (isAuthenticated) { const from = location.state?.from?.pathname || '/'; navigate(from, { replace: true }); } }, [isAuthenticated, navigate, location]); const handleChange = (e) => { const { name, value } = e.target; setFormData(prev => ({ ...prev, [name]: value })); // Clear error when user starts typing if (error) setError(''); }; const handleSubmit = async (e) => { e.preventDefault(); setError(''); setLoading(true); try { const { email, password } = formData; const result = await login(email, password); if (result.success) { // Redirect to the dashboard or previous page const from = … -
Can users and superusers have the same email/username in a Django application?
I have a CustomUser class for my users which is as follows. class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=150, unique=True, null=True, blank=True) email = models.EmailField(max_length=240, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = models.CharField(max_length=30, blank=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'password'] class Meta: verbose_name = 'user' It works pretty much as expected, I am able to signup, signin with normal users. The issue is when I try to create a superuser with the same email/username. I encounter the following error,django.db.utils.IntegrityError duplicate key value violates unique constraint "accounts_customuser_email_key". I understand that there is a uniqueness constraint on the username and email field, but shouldn't a user be able to create a user and an admin account with the same credentials ideally? I have a user with the following username and email. username: test_user email:test_user@test.com, I decided to create an admin with the same email and usernames. Doing so leads to a unique constraint violation. I expected that Django would internally handle this. -
Indexing multiply nested models with django_elasticsearch_dsl
I'm trying to use Elasticsearch in my Django app. I have Lemma models that can have multiple Forms with one citation form that can, in turn, have multiple Spellings. I'm trying to execute a search on (1) the Lemma's citation form, (2) any Lemma's Form's citation form, or (3) any Lemma's Form's Spelling's Latin character spelling. The structure in my models.py: class Lemma(models.Model): cf = models.CharField(max_length=200) pos = models.ForeignKey(Pos, blank=True, null=True, on_delete=models.SET_NULL) notes = models.TextField(blank=True) sortform = models.CharField(max_length=200) class LemmaDef(models.Model): lemma = models.ForeignKey(Lemma, on_delete=models.CASCADE, related_name="definitions") definition = models.TextField() class Form(models.Model): lemma = models.ForeignKey(Lemma, on_delete=models.CASCADE, related_name="forms") cf = models.CharField(max_length=200, blank=True) formtype = models.ManyToManyField(FormType, blank=True) class Spelling(models.Model): form = models.ForeignKey(Form, on_delete=models.CASCADE, related_name="spellings") spelling_lat = models.CharField(max_length=200) spelling_cun = models.CharField(max_length=200, blank=True) note = models.CharField(max_length=200, blank=True) In documents.py, I've got: from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from .models import Lemma, Pos, LemmaDef, Form, Spelling @registry.register_document class LemmaDocument(Document): pos = fields.ObjectField(properties={ "term": fields.TextField() }) definitions = fields.ObjectField(properties={ "definition": fields.TextField() }) forms = fields.ObjectField(properties={ "cf": fields.TextField(), "spellings": fields.ObjectField(properties={ "spelling_lat": fields.TextField() }) }) class Index: name = "lemma" settings = { "number_of_shards": 1, "number_of_replicas": 0 } class Django: model = Lemma fields = [ "id", "cf", "sortform", "notes", ] related_models = [Pos, LemmaDef, Form, Spelling] … -
In django which logout option is best custom logout or LogoutView?
Actually i'm using django 5.2.3 in that version LogoutView is always gives error. Any other way is there for LogoutView because i try all the way?............................................................................................................................................ -
How can I make GrapesJS pages dynamic with real-time data from a Django backend in a React app?
I’m building a page builder application using GrapesJS, React, and Django (as the backend). I’ve successfully integrated GrapesJS into the React frontend, and I can design and save pages. However, I’m struggling to figure out how to make the created pages dynamic — meaning, I want the content to be fetched from the backend (Django) in real time so that it reflects live data (e.g., from a database or API). My goals: Make parts of the GrapesJS-generated pages update dynamically using backend data. Possibly insert dynamic components or placeholders in GrapesJS that get populated with real data on render. What I’ve tried: Saving and rendering raw HTML from GrapesJS. Embedding static content works, but it doesn’t update with backend data. I considered injecting React components into GrapesJS, but I’m not sure how to wire that with Django data properly. What I need help with: A general approach or architecture to achieve dynamic pages with GrapesJS. How to integrate real-time (or at least live) data from Django into the pages built with GrapesJS. Any open-source examples or patterns that solve this. Any guidance or resources would be much appreciated! -
Django static files not loading for one app when DEBUG=False
I'm working on a Django project with multiple apps (Home, student, login, etc.). When I set DEBUG = False in settings.py, the static files (CSS and JS) from my Home app load fine, but the static files from the student app return 404 errors in the browser console like: GET /static/student/css/dashboard.css 404 (Not Found) GET /static/student/js/dashboard.js 404 (Not Found) However, the static files from the Home app still load correctly. Here's what I've already done: My student app has this structure: student/ ├── static/ │ └── student/ │ ├── css/ │ │ └── dashboard.css │ └── js/ │ └── dashboard.js I'm using {% load static %} in the template and referring like this: <link rel="stylesheet" href="{% static 'student/css/dashboard.css' %}"> <script src="{% static 'student/js/dashboard.js' %}"></script> In settings.py DEBUG = False ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' I ran python manage.py collectstatic, and it successfully copied all static files into the staticfiles/ directory. I also added this in urls.py: from django.conf import settings from django.conf.urls.static import static if not settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My Question: Why are the static files from the Home app working, but the ones from student are not, even though both … -
How to change django default files storage to cloudinary storage for media files?
I am working on django project. It is working fine with local storage and decided to use cloudinary for media storage then for some reason the file storage is not changing to cloudinary media storage. Here's my settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "listings", "rest_framework", "rest_framework_simplejwt", "corsheaders", 'django_filters', 'cloudinary_storage', 'cloudinary', ] # Cloudinary config CLOUDINARY_STORAGE = { "CLOUD_NAME": config("CLOUDINARY_CLOUD_NAME"), "API_KEY": config("CLOUDINARY_API_KEY"), "API_SECRET": config("CLOUDINARY_API_SECRET"), } cloudinary.config( cloud_name = config('CLOUDINARY_CLOUD_NAME'), api_key = config('CLOUDINARY_API_KEY'), api_secret = config('CLOUDINARY_API_SECRET') ) DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' model.py file: class Amenity(models.Model): name = models.CharField(max_length=100, unique=True) icon = models.ImageField(upload_to='amenity_icons/', null=True) I tried to upload with admin panel. It stores locally despite settings DEFAULT_FILE_STORAGE to 'cloudinary_storage.storage.MediaCloudinaryStorage' The environment configuration is loaded properly (I checked by printing). Here's debugging shell output: >>> from django.conf import settings >>> from django.core.files.storage import default_storage >>> print(settings.DEFAULT_FILE_STORAGE) cloudinary_storage.storage.MediaCloudinaryStorage >>> print(default_storage.__class__) <class 'django.core.files.storage.filesystem.FileSystemStorage'> I will work if I manually specify storage in every image field in every model. from cloudinary_storage.storage import MediaCloudinaryStorage class Amenity(models.Model): name = models.CharField(max_length=100, unique=True) icon = models.ImageField( upload_to='amenity_icons/', null=True, storage=MediaCloudinaryStorage ) -
Django - S3: collectstatic does not create new folder, even with all permissions and write privileges
Cursor ai called it a "strange problem", so we're back to the original home of solutions. I upgraded django from 2.2 to 5.2, and upgraded my storages, tinymce,.. etc modules along with it. STORAGES = { 'staticfiles': { 'BACKEND': 'storages.backends.s3boto3.S3Boto3Storage', 'OPTIONS': {'location': 'static'}, }, 'default': { 'BACKEND': 'storages.backends.s3boto3.S3Boto3Storage', 'OPTIONS': {'location': 'media'}, }, } i added a new app after the upgrade, and everything worked well in development. The issue is, when i run collectstatic in production, the static and media files that have already been synced from previous deployments remain available, but some of the static and media subfolders/files from recent upgrades do not get uploaded - even as they are all have the same static and media root directory. How is it that django-storages can "pick and choose" the folders to create within an identified static or media directory? i'm not sure what other code to include to explain this further, but if anyone needs to see something else, let me know and i'll add code snippets. Thanks. -
Performance Degradation & Timeouts Since Django & Stack Upgrades
We’ve been experiencing significant performance issues and intermittent timeouts on our app ever since we upgraded: Django from v2.x to v4.2 Heroku stack from 20 to 22 Prior to these upgrades, our response times were solid and timeouts were virtually non-existent. Over the past week, we’ve noticed: a) Longer page-load times (up to 5–10 seconds on endpoints that were previously sub-second) b) Occasional H12 request timeout errors during moderate traffic spikes c) Increased memory usage and dyno restarts that correspond to those timeouts We’ve checked our application logs, continue to optimize database queries, and temporarily scaled up our dynos, but the root cause still seems tied to the upgrades themselves. I) Have you experienced similar behavior when upgrading to Django 4.2 or the Heroku-22 stack? II) Any learnings, recommendations or best practices for tuning our configuration to restore performance to pre-upgrade levels? If there are known workarounds — whether it’s specific buildpack versions, config vars, or tweaking dyno settings — any guidance would be helpful. -
Integrating New Google Maps Autocomplete API into Django Project
I'm using the new Google PlaceAutocompleteElement() API function (not the legacy google.maps.places.Autocomplete) and would like help integrating it into my Django project. Specifically, I want to add an address search bar to my application.html template. I've tried connecting the initMap() JavaScript function to the form in several ways, updating all the corresponding files below, but the form submission always fails, and the data never reaches the database. Here's more information about the this Google API: Place Autocomplete Element Take a look of my attempt before the address implementation: models.py class Applicant(models.Model): Name = models.CharField(max_length=101) DOB = models.DateField() High_School = models.CharField(max_length=100) Major = models.CharField(max_length=100) SSN = models.CharField(max_length=11) Phone = models.CharField(max_length=15) def __str__(self): return self.Name views.py def application_page(request): form = ApplicationForm() return render(request, "DunesApp/application.html", { 'form': form, 'google_maps_key': settings.GOOGLE_MAPS_API_KEY }) def submit_application(request): if request.method == "POST": form = ApplicationForm(request.POST) if form.is_valid(): form.save() return JsonResponse({"status": "success"}) return JsonResponse({"status": "error"}) forms.py class ApplicationForm(forms.ModelForm): class Meta: model = Applicant fields = "__all__" script.js (called inside layout.html) function submitApplication() { const form = document.getElementById('application-form'); const formData = new FormData(form); fetch('/submit_application/', { method: 'POST', body: formData, headers: { 'X-CSRFToken': formData.get('csrfmiddlewaretoken') } }) .then(response => response.json()) .then(data => { const messageBox = document.getElementById('application-message'); if (data.status === 'success') { … -
Celery healthcheck fails in `set -e; cmd1;cmd2` and functions in `set -e; cmd1 && cmd2`
Problem docker compose fails app container for django celery app only in one of the 4 potential use cases. macos: set -e; cmd1;cmd2 or set -e; cmd1 && cmd2 work identically ubuntu: set -e; cmd1;cmd2 fails, set -e; cmd1 && cmd2 works In the failure case we see that django call to celery health check times out. I don't understand how set -e and && result in different behaviors given the following entry-point scripts Failing ubuntu case set -e ... python my_django_app.py start celery-worker celery-beats celery-healthcheck-worker daphne -b 0.0.0.0 -p 8000 my_django_app.asgi:application Passing all cases set -e ... python my_django_app.py start celery-worker celery-beats celery-healthcheck-worker && daphne -b 0.0.0.0 -p 8000 my_django_app.asgi:application Puzzle In my understanding , the set -e with cmd1; cmd2 and set -e with cmd1 && cmd2 should result in the identical behavior but it doesn't seem to. The fact that the error is around a call celery -A my_django_app status make me suspect the relationship of django, celery to daphne and suggests some kind of race condition but this seems like it should not be so Again, given that set -e is set, 1st failure terminates the entry point. There's a relationship change introduced by && but …