Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django UpdateView Creates New Object Instead of Updating the Existing One
I'm having an issue with my Django update view. Although I see the correct data on the update form (i.e. the GET request pre-fills the form with the existing article’s content), when I submit the form the original article isn’t updated—instead, a new article is created with a new uid, and the original still remains with its original uid. I’ve verified that: My update view initializes the ModelForm with the existing instance using the instance parameter. My URL configuration includes the primary key (uid) in the URL. Below is a simplified version of my code. views.py: from django.shortcuts import render, get_object_or_404, redirect from .models import Article from .forms import ArticleForm def ArticleUpdate(request, pk): # Fetch the existing article using the uid passed via URL article = get_object_or_404(Article, uid=pk) if request.method == 'POST': # IMPORTANT: The form is instantiated with the existing instance! form = ArticleForm(request.POST, request.FILES, instance=article) if form.is_valid(): form.save() # Expect this to update, not create a new article return redirect('article-read', pk=article.uid) else: print("Form errors:", form.errors) else: form = ArticleForm(instance=article) context = {'form': form} return render(request, 'blog/article_form.html', context) urls.py: from django.urls import path from blog import views urlpatterns = [ path('articles/create/', views.ArticleCreate, name='article-create'), path('articles/<str:pk>/', views.ArticleRead, name='article-read'), path('articles/<str:pk>/update/', views.ArticleUpdate, name='article-update'), … -
Djoser Activation modification to set other field true instead of is_active
hey I am using the djoser for activation now I want the admin to activate the users from the edit user API in the email activation i want it to be like the email verification like but i want to set the email_verified to true in it instead of the is_active -
django application with firebase authentication
LLMs are failing me on this seemingly simple task, so I'm seeking community advise. I have a django application, which works fine. Both when I develop locally, and in production at https://my.domain Now, I need to add one more page to the application, that will be behind firebase authentication flow. The reason being I've already gotten a pool of users from my mobile application (unrelated to https://my.domain). I want to give access to the same users to their data they generated through my mobile app. My understanding was if they used same firebase ID (either google id, or apple id) as in app, it should be doable. Problems start pretty much off the bat. Here's what I did I've created firebase app and generated config data in firebaseConfig. Since I'm developing locally, I've added localhost to the list of Authorized domains list in firebase console. Google, Apple, Email logins are enabled. As they always were because of my mobile application. Service account credentials file is downloaded, stored, pointed at in django. I ran local server through python manage.py runserver I added login button in my login template. When I hit login (through google popup), list of my google accounts open. … -
Google OAuth2 Signup in Django: 'Bad Request' Error on First Signup Attempt
I'm working on integrating Google OAuth2 login/signup with Django, but I'm encountering an issue during the first signup attempt. The Flow: New User Registration using Google. The user clicks on the "Login with Google" button. The user is redirected to the Google OAuth2 consent screen and logs in. After successful Signup, Google redirects back to my app with a Bad Request - "POST /api/v1/auth/google/ HTTP/1.1" 400 Bad Request : this only happens first time the user tries to sign up, It returns a "Bad Request" error. The issue only occurs during the first signup, even though the user data is added to the database. If I try to login back with the same account using google now then i will be able to Login Successfully. Relevant Code : backend/api/urls.py : path('auth/google/', GoogleLogin.as_view(), name='google_login') backend/api/views.py : from django.conf import settings from django.http import HttpResponseRedirect from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client from dj_rest_auth.registration.views import SocialLoginView class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter client_class = OAuth2Client callback_uri = settings.REDIRECT_URI def get(self, request): return HttpResponseRedirect(redirect_to=settings.GOOGLE_AUTH_URL) backend/api/adapter.py: from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from api.models import User class CustomSocialAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): # Ignore existing social accounts, just do this stuff for new ones if sociallogin.is_existing: … -
Buttons On Click Functioning with same ID different and different attributes
I have an HTML webpage with a sample of buttons as shown part of a Django Application that fills in the name and town after inserting the values: {% for person in page_obj %} <button id="NotifyBtn" name="person.FName" town="person.LName">Press Me</button> {% endfor %} <button id="NotifyBtn" name="Billy" town="Bob">Press Me</button> <button id="NotifyBtn" name="Timmy" town="Tawin">Press Me</button> <button id="NotifyBtn" name="Milly" town="House">Press Me</button> Then I have a JS that does the following: document.getElementById("NotifyBtn").addEventListener("click", function(){ var name = this.getAttribute("name"); var town = this.getAttribute("town"); fetch("{% url 'alert_via_JSON_Response' %}", { method: "POST", headers: { "X-CSRFToken": "{{ csrf_token }}", "Content-Type": "application/json" }, body: JSON.stringify({ message: "Hi there: " + `${name} born in ${town}` }) }).then(response => response.json()) .then(data => alert(data.status)); }); In my Django application I have the following: def alert_via_JSON_Response(request): if request.method == 'POST': data = json.loads(request.body) message = data.get('message', "Error in sending email") return JsonResponse({"status": f"{message}"}) return JsonResponse({"status": f"No Message"}) Right now, when I click on the webpage, only one button works and sends a JSON response to the webpage, it doesn't work if I press another button after pressing the first button. Is there a way to press each button when needed and display the JSON response for each button? -
Dockerized Django app - `gunicorn: command not found` on AWS deployment
I have a Dockerized Django app that is deployed on AWS - after some recent updates to the Debian and PostgreSQL images that I'm using in the Dockerfile, the app is suddenly failing to start running successfully when it hits AWS due to an issue with gunicorn - pyenv: gunicorn: command not found This problem did not occur previously and, if I simply deploy a build based on the previous git commit (prior to making these updates), the app deploys and runs just fine. Furthermore, when I run the app locally via docker-compose up and bash into the container, I can run gunicorn commands no problem, so I'm not quite sure what the issue is - gunicorn is included in the requirements.txt file. Maybe I'll need to provide more info, but for starters, here is the current setup of the Dockerfile and requirements.txt files - I'll note the changes that have been made below them - Dockerfile FROM andrejreznik/python-gdal:py3.11.10-gdal3.6.2 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apt-get update RUN apt-get upgrade -y RUN apt-get install postgresql-15 postgresql-server-dev-15 -y RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ ARG ALLOWED_HOSTS ARG AWS_ACCESS_KEY_ID … -
Django custom filter working in dev but not in prod
I created a custom template filter in django at myapp/templatetags/custom_filters.py. @register.filter(name='indian_number_format') def indian_number_format(value): """ Format the number in Indian style using the locale module (e.g., 1,00,00,000). """ if not isinstance(value, (int, float, Decimal)): print('Not a number', type(value)) return value try: # Set the locale to Indian (Hindi) locale.setlocale(locale.LC_NUMERIC, 'hi_IN') # Format the number using locale formatting formatted_value = locale.format_string("%d", value, grouping=True) return formatted_value except locale.Error: # Fallback in case the locale is not available on the system return value Using it in template like this {% extends "base.html" %} {% load custom_filters %} <p>{{number|indian_number_format}}</p> For example, if the number is 123456, the output should be 1,23,456 and this works fine in dev but the commas do not appear in prod which I have hosted on AWS. Any insight on what might be causing this issue would be helpful. Thanks. -
Deployed django app on apache 2 (403 Forbidden)
I am having trouble deploying my django app onto my linux server running apache2. I already have multiple appas running on this server without issue. I followed the same steps as i usually do, but for some reason, each time i go to the new app url, I am greeted with a 403 Forbidden error. Have checked the apache log and have received this Current thread 0x00007f11d99fcc40 (most recent call first): <no Python frame> [Mon Apr 07 13:34:27.128681 2025] [wsgi:warn] [pid 2703370:tid 139714642299968] (13)Permission denied: mod_wsgi (pid=2703370): Unable to stat Python home /home/tinytoes/surveyV2/venv. Python interpreter may not be able to be initialized>Python path configuration: PYTHONHOME = '/home/tinytoes/surveyV2/venv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/tinytoes/surveyV2/venv' sys.base_exec_prefix = '/home/tinytoes/surveyV2/venv' sys.executable = '/usr/bin/python3' sys.prefix = '/home/tinytoes/surveyV2/venv' sys.exec_prefix = '/home/tinytoes/surveyV2/venv' sys.path = [ '/home/tinytoes/surveyV2/venv/lib/python38.zip', '/home/tinytoes/surveyV2/venv/lib/python3.8', '/home/tinytoes/surveyV2/venv/lib/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Im not entirely sure if the error is relevent. Here are the permissions ive set for the app drwxr-xr-x 8 tinytoes www-data … -
django-x509 library - any way to use certificate authentication only on several pages of application and continue with password for others?
After searcxhing and investigating various X509 libs for django I found this https://github.com/openwisp/django-x509 IMHO looks the best - even CA and certificate generation are present in admin UI. However, thinking now, how to use it the best way in my case - please, see short description and image below Data entry to the site should be done using two ways - automated POST from standalone application using cartificate authentication, and regular https for data watch and manual entry (sorry 4 typo in the image). It's important to remember, that application is standalone - no {% csrf_token %} in it indeed. So, general advice is needed. IMHO, the best way is to use cert autentication on the automated POST URL only, with password for other pages, but how? If mentioned above is not possible - needed to make two apps with sharing data model in common database to x509 app. Found 1 reply for sharing question with -1 rep here, not sure, that workable - advice is welcome. In addition. may happen user management problems in 2 apps etc, I think, that the first method is better. BTW, if the lib authors are here - sample of integraion into existing site … -
Django queryset annotate sum of related objects of related objects
I have class Book(models.Model): title = models.CharField(max_length=32) class Table(models.Model): book = models.ForeignKey(Book, related_name='tables') class TableEntry(models.Model): table = models.ForeignKey(Table, related_name='entries') value = models.FloatField() and want a queryset of books that has annotated the sum of all table entries in a book. I have tried Book.objects.all().annotate(sum=Sum('tables__entries')) but this does not seem to work. -
Making changes to database structure in django
Hi I am looking to get some guidance on how to properly make changes to the models in django. Currently I'm working on an app where I have previously defined models and have uploaded data for these models. However I would like to make some changes to the schema of the database and edit and add/delete some columns of the tables. I am running into some issues with this where django will not allow me to make migrations or migrate after certain changes. If anyone could give me some tips on why this is happening and best practices to follow when I am making changes like this it would be very helpful. Also currently I am using a sqlite3 db. I have tried to delete migrations and the database but had no success and I would also like a solution that is more practical if I wanted to make changes like this when the app in in production -
Error 'RecordSearchForm' object has no attribute 'is_game'
def index(request): game_data = GameDataEntry() update_progress = ProjectProgressEntry() work_hours = WorkHoursEntry() if request.method == "GET": form = RecordSearchForm(data=request.GET) if form.is_game is True: query = request.GET.get('entry_date') object_list = game_data.objects.filter(entry_date=query) return HttpResponse(object_list, content_type='text/plain') if form.is_work is True: query = request.GET.get('entry_date') object_list = work_hours.objects.filter(entry_date=query) return HttpResponse(object_list, content_type='text/plain') if form.is_Progress is True: query = request.GET.get('entry_date') object_list = update_progress.objects.filter(entry_date=query) return HttpResponse(object_list, content_type='text/plain') else: form = RecordSearchForm() return render(request, 'index.html', context={'form': form}) This is my Form class class RecordSearchForm(forms.Form): is_Progress = forms.BooleanField(widget=forms.CheckboxInput( attrs={'class': 'form-check-input', "id": "is_progress_update", "type": 'checkbox'})) is_game = forms.BooleanField(widget=forms.CheckboxInput( attrs={'class': 'form-check-input', "id": "is_game_update", "type": "checkbox"})) is_work = forms.BooleanField(widget=forms.CheckboxInput( attrs={'class': 'form-check-input', "id": "is_work_entry", "type": "checkbox"})) game_name = forms.ModelChoiceField(widget=forms.Select( attrs={'class': 'form-control', "id": "game_name"}), queryset=Games.objects.all()) entry_date = forms.DateField(widget=forms.DateInput( attrs={'class': 'form-control', "id": "date_entry", "type": "date"})) I am trying to make a search function to get the records based on the date of the entry for the models that are either game development, finished updates, or work hours but it's saying that is_game is not an attribute of my form but it's clearly there. can anyone tell me what I'm doing wrong or what I've missed -
Python gunicorn not working with Docker CMD
I have django App that also runs some Javascript templates with node. I'm struggling to run Gunicorn as the CMD of the Dockerfile. Here is my dockerfile: FROM node:22.12.0-alpine3.21 RUN mkdir /app COPY . /app WORKDIR /app/tools RUN npm install --loglevel verbose RUN npm run build WORKDIR /app RUN ls -la # Set environment variable for Python version ENV PYTHON_VERSION 3.10.10 # Install dependencies and Python 3.10 RUN apk update RUN apk update && apk add --no-cache \ build-base \ bash \ libffi-dev \ zlib-dev \ bzip2-dev \ ncurses-dev \ openssl-dev \ sqlite-dev \ readline-dev \ tk-dev \ gdbm-dev \ xz-dev \ libnsl-dev \ curl \ dcron RUN curl -O https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VERSION}.tgz \ && tar -xvf Python-${PYTHON_VERSION}.tgz \ && cd Python-${PYTHON_VERSION} \ && ./configure --enable-optimizations \ && make -j$(nproc) \ && make altinstall \ && cd .. \ && rm -rf Python-${PYTHON_VERSION} Python-${PYTHON_VERSION}.tgz \ && python3.10 --version RUN ln -sf /usr/local/bin/python3.10 /usr/bin/python3 \ && ln -sf /usr/local/bin/pip3.10 /usr/bin/pip3 # Verify Python and pip installation RUN python3 --version && pip3 --version # Install pip and upgrade setuptools and wheel RUN pip3 install --no-cache --upgrade pip setuptools wheel RUN pip3 install -r requirements.txt EXPOSE 8000 ENV PYTHONPATH=/app WORKDIR /app CMD ["python3", "-m", "gunicorn", … -
can't retrieve images from filesystem with Next.js and Django
English is not my native language. I'm trying to deploy three Next.js apps and one Django API app(using Django ninja). the problem is I get "400 bad request" in my browser's console. https://MY_SERVER_DOMAIN/users/_next/image?url=https://MY_SERVER_DOMAIN/media/magazine/thumbnail/Methods-of-using-radish-in-diet.webp&w=1920&q=75 in local I can see the image but on production I get 400. my Nginx config: location /media/ { alias /home/USER/backend/media/; } location /api/v1 { include proxy_params; proxy_pass http://localhost:8000; } location /admin { include proxy_params; proxy_pass http://127.0.0.1:8000; } location / { include proxy_params; proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /doctors { include proxy_params; proxy_pass http://localhost:3001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /users { include proxy_params; proxy_pass http://localhost:3002; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } I saw many errors like this this in /var/log/nginx/error.log: 2025/04/06 13:44:21 [error] 41446#41446: *1 directory index of "/home/USER/users-front/.next/static/media//" is forbidden, client: 5.125.0.145, server: 176.97.218.11, request: "GET /users/_next/image/?url=%2Fusers%2F_next%2Fstatic%2Fmedia%2Fdoctor.07a8ef12.jpg&w=96&q=75 HTTP/1.1", host: "MY_SERVER_DOMAIN", referrer: "https://MY_SERVER_DOMAIN/users" but it should retrieve the image from Django media directory("backend/media") not Next.js! -
CORS headers not being added in django
Preface, I am aware of django-cors-headers not work I am getting the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ... (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 301. Here are the important parts of my settings.py. INSTALLED_APPS = [ ... corsheaders ... ] corsheaders is the last entry in INSTALLED_APPS MIDDLEWARE is: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "allauth.account.middleware.AccountMiddleware", ] So CorsMiddleware is at the top. And for CORS settings: CORS_ALLOW_CREDENTIALS = False CORS_ALLOW_ALL_ORIGINS = True And ALLOWED_HOSTS is: ALLOWED_HOSTS = ['*'] Online, this seems to be all that's needed to get CORS headers, but I am not getting them in the response. How do I fix this? -
Django jalali leap year is wrong for 1403
In my django app. Im using django-jalali-date package with version 1.0.1 but 1403 leap year is wrong and it detect 1404 as a leap year. -
Htmx preload extension not working, default behaviour not firing network request on mouseover (with Django)
Hi anybody here used preload extension with htmx, I am using it with django. But htmx does not fire any request after setting preloading to mouseover (I am using the preload cdn for loading and it seems to be working.) ps. I am using django enter image description here -
Wagtail default template field in_preview_panel is fine in dev but fails in production
In the default template from Wagtail even mentioned online here, there is a part: {# Force all links in the live preview panel to be opened in a new tab #} {% if request.in_preview_panel %} <base target="_blank"> {% endif %} I extend this base template in my other templates. This is fine in dev, but when running the website in production, I face with this error: Exception while resolving variable 'in_preview_panel' in template 'home/home_page.html'. Traceback (most recent call last): File "/home/myusername/.local/lib/python3.12/site-packages/django/template/base.py", line 880, in _resolve_lookup current = current[bit] ~~~~~~~^^^^^ TypeError: 'WSGIRequest' object is not subscriptable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/myusername/.local/lib/python3.12/site-packages/django/template/base.py", line 890, in _resolve_lookup current = getattr(current, bit) ^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'WSGIRequest' object has no attribute 'in_preview_panel' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/myusername/.local/lib/python3.12/site-packages/django/template/base.py", line 896, in _resolve_lookup current = current[int(bit)] ^^^^^^^^ ValueError: invalid literal for int() with base 10: 'in_preview_panel' During handling of the above exception, another exception occurred: ... I have no clue on what in_preview_panel is and why it behaves different in dev and prod. If I remove it, this case of error will be resolved. I have … -
How to display an image as the current value to an ImageField in a DJango app
I have this form in a Django template: <form action="{% url 'MCARS:Service-Record' %}" method="POST"> {% csrf_token %} <div class="box-body"> {% for field in form %} {% if not forloop.counter|divisibleby:2 %} <div class="row"> {% endif %} <div class="col-md-6"> <div class="mb-3 form-element form-control"> {{ field.label_tag }} {% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.ClearableFileInput %} <div> <p>Current Image:</p> <img src="{% static form.instance.avatar.url %}" alt="Uploaded Image" style="max-width: 300px; height: auto;"> </div> {% endif %} {{ field|add_class:'form-control' }} </div> </div> {% if forloop.counter|divisibleby:2 %} </div> {% endif %} {% endfor %} </div> <div class="text-end"> <button type="submit" class="btn btn-primary mt-2"><i class="mdi mdi-content-save"></i> Save</button> </div> </form> using this Model, lass Profile(models.Model): # Managed fields user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) memberId = models.CharField(unique=True, max_length=15, null=False, blank=False, default=GenerateFA) bio = models.TextField(null=True, blank=True) avatar = models.ImageField(upload_to="static/MCARS/img/members", null=True, blank=True) birthday = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=constants.GENDER_CHOICES, null=True, blank=True) and this form class UserProfileForm(ModelForm): class Meta: model = Profile exclude = ('user','memberId','invited', 'registered') There is one field in there called avatar. I get to this one part in the template: {% if field.ClearableFileInput %} <div> <p>Current Image:</p> <img src="{% static form.instance.avatar.url %}" alt="Uploaded Image" style="max-width: 300px; … -
POST 405 (Method Not Allowed) Django REST
The problem is when sending a post request from the client to the django server. Both the client and the server are deployed locally. I've double-checked where the problem might be many times, so I'm attaching the code from the views and settings file. javascript code fetch('http://127.0.0.1:8000/products/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(userData) }) .then(response => response.json()) .then(data => console.log(data.basket)) .catch(error => console.error('Basket get error', error)); python code views: @csrf_exempt def get_all_products(request): if request.method == 'POST': try: data = json.loads(request.body) print(data) except Exception as e: return JsonResponse({'error': str(e)}, status=400) return JsonResponse({'error': 'Invalid request method'}, status=405) settings: ALLOWED_HOSTS = ['localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mini_app', 'corsheaders' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'DELETE' ] CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:5500', 'http://localhost:5500' ] output in the python django console: Method Not Allowed: /products/ [05/Apr/2025 13:05:54] "POST /products/ HTTP/1.1" 405 35 output in the browser console POST http://127.0.0.1:8000/products/ 405 (Method Not Allowed) -
Reportlab cannot open resource when using Minio (S3) pre-signed link
I am using reportlab in a containerized Django project with django-minio-backend for storing user-uploaded images. I want to create a PDF that uses the uploaded image as the background. This is the code used to render the PDF from django_minio_backend import MinioBackendStatic from reportlab.lib.utils import ImageReader def render_pdf(data: dict, image_url: str) -> io.BytesIO: RGB_VAL = 50 # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Register the Open Sans Font font_file = MinioBackendStatic().open("/fonts/OpenSans-Regular.ttf") pdfmetrics.registerFont(TTFont("OpenSans", font_file)) # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer, pagesize=landscape(A4)) image = ImageReader(image_url) # <--------------- Problem Line! p.drawImage(image, 0, 0, width=A4[1], height=A4[0]) # Other Draw operations ... # Close the PDF object cleanly, and we're done. p.showPage() p.save() return buffer The Minio storage backend is running in a different container and returns a URL for the resource something like this. http://localhost:9000/media-root-storage/images/<My-Image-Name>.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credential>&X-Amz-Date=20250405T085308Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=<signature> This is the error that I get Traceback (most recent call last): File "/usr/local/lib/python3.13/site-packages/reportlab/lib/utils.py", line 643, in __init__ fp = open_for_read(fileName,'b') File "/usr/local/lib/python3.13/site-packages/reportlab/lib/utils.py", line 534, in open_for_read return open_for_read(name,mode) File "/usr/local/lib/python3.13/site-packages/reportlab/lib/utils.py", line 532, in open_for_read raise IOError('Cannot open resource "%s"' % name) OSError: Cannot open resource "http://localhost:9000/media-root-storage/images/<My-Image-Name>.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=<credential>&X-Amz-Date=20250405T085308Z&X-Amz-Expires=604800&X-Amz-SignedHeaders=host&X-Amz-Signature=<signature>" I even tried to replace the hostname from … -
Safe keyword usage with Django-summernote inhibits word wrapping even with explicit word wrapping
I am trying to use summernote with django and am encountering this issue where if I paste 200 words of inline lorem ipsum text as a test in the texfield, it correctly shows the text, but in a single line that is too big and goes off screen to the right. Where as if i just paste the lorem ipsum as hard coded in the template, the word wrap works perfectly fine. I use tailwind here: <div class="prose max-w-full break-words"> {{ post.content | safe }} </div> The content field is a is a text field: content = models.TextField() I tried adding the linebreaks keyword and setting the word-wrap to break word but it did nothing: <div class="prose max-w-full break-words" style="word-wrap: break-word;"> {{ post.content | safe }} </div> -
Django ModelForm ensuring FK integrity without using it in the form
I have a User Profile model with a Model Form: class Profile(models.Model): # Managed fields user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE) memberId = models.CharField(unique=True, max_length=15, null=False, blank=False, default=GenerateFA) bio = models.TextField(null=True, blank=True) avatar = models.ImageField(upload_to="static/MCARS/img/members", null=True, blank=True) birthday = models.DateField(null=True, blank=True) gender = models.CharField(max_length=10, choices=constants.GENDER_CHOICES, null=True, blank=True) invited = models.BooleanField(default=False) registered = models.BooleanField(default=False) height = models.PositiveSmallIntegerField(null=True, blank=True) phone = models.CharField(max_length=32, null=True, blank=True) address = models.CharField(max_length=255, null=True, blank=True) number = models.CharField(max_length=32, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) state = models.CharField(max_length=50, null=True, blank=True) zip = models.CharField(max_length=30, null=True, blank=True) facebook = models.URLField(null=True, blank=True) Twitter = models.URLField(null=True, blank=True) LinkedIn = models.URLField(null=True, blank=True) Instagram = models.URLField(null=True, blank=True) Snapchat = models.URLField(null=True, blank=True) website = models.URLField(null=True, blank=True) class UserProfileForm(ModelForm): class Meta: model = Profile exclude = ('user','memberId','invited', 'registered') I don't want user in the form, but remember who the user is, when saving back to the model. How do I ensure that? Without it, the compiler throws a FK integrity error. This is what I have the view: @login_required() def Profile(request, memberid=None): if memberid: user = User.objects.select_related('profile').get(id=memberid) else: user = User.objects.select_related('profile').get(id=request.user.id) errors = None if request.method == 'POST': print('found me') data = request.POST form = UserProfileForm(data) form.user = user if form.is_valid(): form.save() else: print('form is invalid') errors … -
How can I test my Django & React app with massive users efficiently?
I'm working on a Django backend and a React frontend, and I need to test my app with a large number of users. I have used Cypress for UI testing, but it takes too much time to complete the tests I need. My goal is to test two different scenarios: First scenario (8,840 users) Register a user Modify user details Create a contribution Second scenario (~300,000 users) Perform the same process as the first scenario but on a much larger scale I'm looking for a faster and more efficient way to execute these tests. -
Initiate paypal payment post request returning 404 error, but the url mapping in django backend is correct, no syntax errors in React frontend
My React and Django website is deployed on render, when i run the backend service from render the initiate paypal payment url is mapped there, i also checked Django urls its there, but when i send the post request from the frontend, i get a 404 error and iyour text checked properly i have no syntax errors, am sending the correct data to the backend, forward slash is there. Am using Sandbox mode, i removed the client id and secret id from settings.py and i placed them in render's environment variable, so this is how i access them: PAYPAL_CLIENT_ID = os.getenv('PAYPAL_CLIENT_ID') PAYPAL_SECRET_CLIENT = os.getenv('PAYPAL_SECRET_CLIENT') i feel like whenever i click on the 'pay with Paypal button' so as to send the request, something blocks it hence the 404 error. website link, please you can use fake filter extension to login and help me checkout the problem Also : No CORS-POLICY issues the frontend Url is correctly placed in the allowed origins the REACT_BASE_URL is also correctly placed in my settings.py and views.py i just don't no what the problem is, i have so far tried everything, any one who can help me, i appreciate thank you backend code @api_view(['POST']) def …