Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Products Not Filtering Correctly with AJAX in Django
I'm working on an e-commerce website using Django and jQuery to filter products based on selected criteria (price range, categories, and vendors). While the AJAX request seems to be sent correctly and I receive a response, all products are still displayed on the page, regardless of the selected filters. What I've Implemented: JavaScript (AJAX) Code: $(document).ready(function() { function filterProducts() { let filter_object = {}; // Get price range values let min_price = $("#price-min").val() || 0; let max_price = $("#price-max").val() || 9999999; filter_object.min_price = min_price; filter_object.max_price = max_price; // Get selected categories and vendors $(".filter-checkbox").each(function() { let filter_key = $(this).data("filter"); filter_object[filter_key] = Array.from( document.querySelectorAll('input[data-filter=' + filter_key + ']:checked') ).map(function(element) { return element.value; }); }); // Send AJAX request to filter products $.ajax({ url: '/filter-product', data: filter_object, dataType: 'json', beforeSend: function() { console.log("Filtering products..."); }, success: function(response) { console.log("Products filtered successfully."); $(".showcase").html(response.data); }, error: function(xhr, status, error) { console.error("Error filtering products:", error); } }); } // Event listener for checkbox and filter button $(".filter-checkbox, #filter-btn").on("click", filterProducts); }); HTML Structure: <div class="u-s-m-b-30"> <div class="shop-w"> <div class="shop-w__intro-wrap"> <h1 class="shop-w__h">PRICE</h1> <span class="fas fa-minus shop-w__toggle" data-target="#s-price" data-toggle="collapse"></span> </div> <div class="shop-w__wrap collapse show" id="s-price"> <form class="shop-w__form-p"> <div class="shop-w__form-p-wrap"> <div> <label for="price-min"></label> <input class="input-text input-text--primary-style" type="text" id="price-min" placeholder="Min"> … -
js not loading in html
This is the error that keeps coming up : 2/:47 Uncaught ReferenceError: moveSlide is not defined at HTMLAnchorElement.onclick (2/:47:64) onclick @ 2/:47 2/:48 Uncaught ReferenceError: moveSlide is not defined at HTMLAnchorElement.onclick (2/:48:63) But I just finished my javascript for the control carousel & the buttons but it seems like its not loading htmlwarningsjs I have tried and verified all my code but with no luck to find the issue I have also found something interesting when viewing my sources page in the inspectorhome page sources that shows my js scriptproject page that doesnt show my js in its sources let slideIndex = 1; showSlides(slideIndex) function moveSlide(n) { slideIndex += n showSlides(slideIndex) } function showSlides(n) { let slides = document.getElementsByClassName("carousel-item") if (n > slides.length) { slideIndex = 1 } if (n < 1) { slideIndex = slides.length; } for (let i = 0; i < slides.length; i++) { slides[i].style.display = "none" } slides[slideIndex - 1].style.display = "flex" } {% extends 'base.html' %} {% load static %} {% block title %} Project Page {% endblock %} {% block extrahead %} <link rel="stylesheet" href="{% static 'css/project.css' %}" /> {% endblock %} {% block content %} <div class="project-card"> <div class="project-info"> <h1>{{ project.title }}</h1> <p> … -
Sending array of texts to Django, via POST, cannot get as array, getting string
I'm sending this data to Django, these texts are from multiple CKEditors chk_vals = ["Some text","Other text"]; const data = new URLSearchParams(); data.append("csrfmiddlewaretoken", "{{csrf_token}}"); data.append("tmplData", JSON.stringify(chk_vals)); fetch(uri, { method: 'post', body: data, }) .then(response => response.json()) .then(data => { It's from Chrome's network: tmplData: ["Some text","Other text"] Now Django: data = request.POST templateArr = data.getlist('tmplData') templateList = list(templateArr) And the length of the templateList is 1, it is getting it as one string and I cannot split it with ',' because these texts can contain ',' too. I also tried templateArr = data.getlist('tmplData[]') and sending without JSON.stringify, but nothing works data = request.POST templateArr = data.getlist('tmplData[]') templateList = list(templateArr) and this variable templateArr is empty -
Add primary key for existing table
I have database table core_config and basic model core.Config model connected to it. Initial migration has definition of id AutoField as default, but there is no PRIMARY KEY in database table (I have no idea why), so I can't create relations to it from another tables. Is there any ways to generate migration like 'add_constraint_pk_if_not_exists'? I want to make it with "if_not_exists" because there is a probability of existing PRIMARY KEY in other database mirrors. -
Dockerized Django with Gunicorn not working
I'm attemtping to migrate to Gunicorn WSGI server for a Dockerized Django 5.0.4 Rest API running on 80:8080. Currently it is running with the default WSGI that ships with Django. However, I'm unable to set it up correctly. Definately missing something. Postman response still shows response as: Server : WSGIServer/0.2 CPython/3.10.14 Here is my configuration: Project structure mydjangoblogmain ---mydjangoblog -settings.py -wsgi.py -urls.py wsgi.py inside mydjangoblog """ WSGI config for mydjangoblogmain project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mydjangoblog.settings") application = get_wsgi_application() My Docker File FROM python:3.10.14 RUN apt-get -y update && apt-get -y upgrade && apt-get install -y ffmpeg # Copy any files over COPY entrypoint.sh /entrypoint.sh # Change permissions RUN chmod +x /entrypoint.sh ENTRYPOINT ["/entrypoint.sh"] COPY requirements.txt /requirements.txt RUN pip install -r /requirements.txt VOLUME ["/opt/mydjangoblogmain"] EXPOSE 8080 CMD ["gunicorn","mydjangoblogmain.mydjangoblog.wsgi:application" ,"--bind", "0.0.0.0:8080", "--workers", "4" ] # CMD ["python", "manage.py", "runserver", "0.0.0.0:8080"] #Commented this out and used the CMD command before it. entrypoint.sh #!/bin/bash set -eo pipefail cd /opt/mydjangoblogmain # install pip env deps, run migrations, collect media, start the server pip install -r requirements.txt --quiet python manage.py migrate echo … -
Pros and Cons of Not Using ForeignKey in Django Through Table?
I'm working on a Django project and came across a design pattern that I'm unsure about. I have an intermediary table (through table) that connects Book and Tag. Instead of using ForeignKey fields for the relationships, the table uses plain IntegerField fields to store the IDs of the related models (book_id and tag_id). Here’s what the model looks like: class BookTagType(models.Model): book_id = models.IntegerField(null=True, blank=True) tag_id = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = "book_tag_types" managed = False This model stores just the IDs of Book and Tag, but I’m wondering: Is there any reason or benefit not to use ForeignKey here instead of IntegerField? What are the potential drawbacks or advantages of using IntegerField for these relations compared to using ForeignKey? -
django unresolved tag "load" at DRF api.html
I have the following fully-functioning project/rest_framework/api.html: {% extends 'rest_framework/base.html' %} {% load static %} {% block style %} {{ block.super }} <link rel="stylesheet" href="{% static 'css/General.css' %}"> {% endblock %} the problem is, that load is underlined, commented "unresolved tag 'load'. As well no style changes apear on web page even after restarting the server and shift-f5 reload. -
How to efficiently structure conversion logic between model pairs in Django?
I'm working on a Django app where I need to handle conversions between pairs of models with different units of measurement. These models are like tasks which the user needs to complete, and converting units between two tasks attempts to map the effort of the first task to the second, measured in units. My current approach uses a mapping of model pairs (around 30 possible combinations) and applies one of several calculations to a value associated with the from_model based on the pair and the associated unit. I've been given a predefined list of mappings and calculations on the various units of measurement each task has. Context: For example, here are two tasks: Task A: Writing 1 page by hand using a pencil (this contains a value and unit of measurement). Task B: Typing pages using a computer (this does not contain a value, but does contain the unit of measurement) A conversion from Model A to Model B would need to take the value (e.g., 1 page) and return an equivalent in terms of effort (e.g., typing 3 pages might be considered equivalent to handwriting 1 page). Here's my current implementation: from django.test import TestCase from app.myapp.models import MyModel … -
Cors-erorr occurs when I send a post request, but corsheaders are configured
I want to make a post request for back end from front end, but I get an error in my browser. I tested it through postman - there are no problems with logic on the backend, and I have configured corsheaders correctly, I think. (frontend - Next.js) (backend - Django rest) settings.py CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000", ] CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_WHITELIST = [ "http://localhost:8000", ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] here's my this post request from the front, couldn't seem to find any errors in it either page.js 'use client' import styles from "./page.module.css"; import axios from "axios"; import { useState } from "react"; export default function Home() { const [data, setData] = useState([]); const [postData, setPostData] = useState({ password: "", message: "", }); const handleSubmit = async (event) => { event.preventDefault(); try{ const res = await axios.post("http://127.0.0.1:8000/message-post/", postData, { headers : { 'Content-Type': 'application/json' } }); const data = res.data; setData(data); } catch(error){ console.log(error); } } return ( <div> {data.map((dat, index) => ( <div key={index}> <a>{dat.message}</a> </div> ))} <form className={styles.formdata} method="POST" onSubmit={handleSubmit}> <div className={styles.input_fields}> <a className={styles.textupper}>Chatting anonymously</a> <input className={styles.password} type="text" placeholder="Enter password" value={postData.password} onChange={(e) => setPostData({...postData, password: e.target.value})}></input> <textarea className={styles.message} type="text" placeholder="Massage..." value={postData.message} … -
Issues with Django and MS SQL on Docker
I am trying to connect Django and MS SQL 2022 on Docker but I am getting the following error: 2024-10-12 16:20:30 /usr/local/lib/python3.11/site-packages/django/core/management/commands/makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') django.db.utils.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') Dockerfile (BE) FROM python:3.11.9-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update RUN apk add unixodbc-dev g++ bash gnupg curl #Download the desired package(s) RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/msodbcsql17_17.10.5.1-1_amd64.apk RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/mssql-tools_17.10.1.1-1_amd64.apk #(Optional) Verify signature, if 'gpg' is missing install it using 'apk add gnupg': RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/msodbcsql17_17.10.5.1-1_amd64.sig RUN curl -O https://download.microsoft.com/download/e/4/e/e4e67866-dffd-428c-aac7-8d28ddafb39b/mssql-tools_17.10.1.1-1_amd64.sig RUN curl https://packages.microsoft.com/keys/microsoft.asc | gpg --import - RUN gpg --verify msodbcsql17_17.10.5.1-1_amd64.sig msodbcsql17_17.10.5.1-1_amd64.apk RUN gpg --verify mssql-tools_17.10.1.1-1_amd64.sig mssql-tools_17.10.1.1-1_amd64.apk #Install the package(s) RUN apk add --allow-untrusted msodbcsql17_17.10.5.1-1_amd64.apk RUN apk add --allow-untrusted mssql-tools_17.10.1.1-1_amd64.apk RUN mkdir /code WORKDIR /code ADD . /code/ RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python","/code/manage.py","runserver","0.0.0.0:8000"] Dockerfile DB FROM mcr.microsoft.com/mssql/server:2022-latest ENV ACCEPT_EULA=Y ENV MSSQL_PID=Express ENV SA_PASSWORD=admin123! ENV MSSQL_TCP_PORT=1433 EXPOSE 1433 # Set the working directory inside the container WORKDIR /usr/src/app # Copy the SQL script to the container COPY init-db.sql . # Copy the … -
ListFlowable() causes drawing PDF file to stop using ReportLab in Django
I'm creating a Django project in which I can store recipes. Every recipe has the option to be exported in a PDF file. When creating the PDF file I'm appending every paragraph using Paragraph() to the PDF, except the ingredients part, which should be a list using ListFlowable() . If I append the ListFlowable() to the story list, the exported PDF file stops to be drawn at the moment it is called and no further paragraphs are added to the file (including the ListFlowable()). Yet, if I exclude the ListFlowable() from the story, every paragraph is being rendered in the PDF file. Does anybody know what's causing this to happen? generate_report.py: from io import BytesIO from reportlab.pdfgen import canvas from reportlab.platypus import Paragraph, Frame, ListFlowable, ListItem from reportlab.lib.styles import ParagraphStyle from reportlab.lib.units import mm from reportlab.lib.pagesizes import A4 from .models import RecipeIngredients from django.shortcuts import get_object_or_404 LEFT_MARGIN = 10*mm RIGHT_MARGIN = 10*mm TOP_MARGIN = 20*mm BOTTOM_MARGIN = 20*mm PAGE_WIDTH, PAGE_HEIGHT = A4 TEXT_WIDTH = PAGE_WIDTH - LEFT_MARGIN - RIGHT_MARGIN TEXT_HEIGHT = PAGE_HEIGHT - TOP_MARGIN - BOTTOM_MARGIN HEADING_1 = ParagraphStyle('Heading1', fontName="Helvetica", fontSize=16, alignment=0, spaceAfter=30) HEADING_2 = ParagraphStyle('Heading2', fontName="Helvetica", fontSize=12, alignment=0, spaceAfter=20) NORMAL = ParagraphStyle('Normal', fontName="Helvetica", fontSize=11, alignment=0, spaceAfter=10) def generate_pdf_recipe(recipe_slug): buffer … -
Django datatable: order by the last entry
I have a datatable with 11 columns. The first column is ID (pk) and the table is ordered by this primary key. order: [[1, 'desc']] I want to order all of the entries in my table by the last one added to the first one, as it is now, BUT I don't want some ID's to be skipped if I delete one record. I tried to order them by a column "Date", but this is not what I want. I tried to hide the column ID, but then I can't order by the last one added. Example: Before deletion: ID NAME 1 John 2 Smith 3 Mark 4 Johnny After deleting Smith (2) row: ID NAME 1 John 3 Mark 4 Johnny What I want: ID NAME 1 John 2 Mark 3 Johnny I am thinking about a new custom ID field but I want it to update everytime with the deletion of a middle record. Another way is to hide the column ID, but if I click to sort them by Name, I can't sort them back by ID only if I refresh the page. Do you have any solutions ? Thanks -
Issues with boilerplate HTML in the Django templates folder
"I've tried reinstalling all extensions, adjusting settings, and reinstalling VS Code, but the auto-suggestion of snippets in templates/index.html doesn't work. However, when I move index.html out of the templates folder to ./index.html, the snippets start working again. How can I fix auto-suggestions for snippets inside the templates folder?" What I tried: Reinstalled all VS Code extensions. Changed various settings related to snippets and auto-completion. Reinstalled VS Code entirely. Moved index.html out of the templates folder to ./index.html, which made the snippets work again. What I expected: I expected the auto-suggestion of snippets to work within templates/index.html, just as it does when the file is outside the templates folder. -
When the page is fully loaded, the visibility of the content is cut-off
In the first option - page loading mode - this is if you interrupt it at the loading stage and not completely. The page is not completely loaded. In this case - option - all the content is displayed in the browser - the content that has time to load is loaded accordingly - which had time to load before the interruption. In the second option - page loading - this is if you do not interrupt the loading and the loading is complete. All the content on the page is completely loaded. But at the moment - immediately upon complete loading - there is a cut-off - a reduction in the visibility of the content - you cannot fully view the - seemingly fully loaded page. The content is cut-off. It is possible that something is not working somewhere. Could this be - is it because of the side menu? I'm trying to create a shell for Django Python. And I have a strange thing - visibility - content availability is limited. Although everything seems to load when loading - but then when fully loaded for some reason - there is a limitation - there is no scrolling of … -
Django app on Vercel behaving differently when the DEBUG's value is changed
When I deploy a Django app on Vercel with DEBUG = False, it's showing "maximum unzipped size exceeded," but when I deploy the same Django app with DEBUG = True, it's working fine. Why so? This is the main problem. If more context is required, I will be more than happy to share. Thanks in advance -
ftplib doesn't send files in celery bot
I used a code from here to download files in Selenium Grid VMs, but, when I use FTP, it shows no error and it doesn't send the files. Code from ftp bot def is_connected(ftp): try: ftp.retrlines('LIST') except (socket.timeout, OSError, AttributeError): return False return True @shared_task() def send_binary(file_name : str, file_path): ftp = FTP( FTP_FAT_HOST, FTP_FAT_USER, FTP_FAT_PASSWORD, timeout=30 ) ftp.set_pasv(True) ftp.encoding='utf-8' if(not is_connected(ftp)): ftp.login() upload_to_ftp(file_path, ftp) def upload_to_ftp(local_file, ftp : FTP): try: with open(local_file, 'rb') as file: ftp.storbinary(f'STOR {os.path.basename(local_file)}', file) except Exception as e: print(f'Erro ao enviar {local_file}: {e}') Code I use to download pdf e txt files from my sources def __download_file(self, file_name: str, target_directory: str) -> None: if not os.path.exists(target_directory): os.makedirs(target_directory) contents = self.driver.execute(Command.DOWNLOAD_FILE, {"name": file_name})["value"]["contents"] zip_target_file = os.path.join(target_directory, f"{file_name}.zip") with open(zip_target_file, "wb") as file: file.write(base64.b64decode(contents)) with zipfile.ZipFile(zip_target_file, "r") as zip_ref: zip_ref.extractall(target_directory) os.remove(zip_target_file) Does anyone know another way to make it work ? I tried creating a bot in celery just to ftp, before this it was inside my main code. I tried change the ftp server, I tried change the ftp passiveness and timeout. Nothing changed. -
How to reset Django admin action page after returning a FileResponse
I have a Django Admin action that creates and downloads a file in response to a data export request from the user. The file download works fine, but the admin page is left in the same state as when the user first initiated the request, with the row that's being exported still ticked, and the export option still visible in the Admin action dropdown. How to I return a Django FileResponse, but also return a response that will reset the page? Can I return the FileResponse as part of a HttpResponseRedirect(request.get_full_path()) or something?? @admin.action(description="Export data for this edition") def export_edition_action(self, request, queryset): buffer = io.BytesIO() buffer.write(export_edition(queryset[0])) buffer.seek(0) response = FileResponse(buffer, as_attachment=True, filename=f'export.json') return response -
how celery flowers connect to redis throught ssh tunnel
I'm using ssh tunnel to connect to redis on remote host, but when I use ssh -L localport:target_remote_host:target_remote_port username@medium_remote_host to forwarding local request, I can connect to target remote redis by redis-cli. But when I start flower, It failed. Is there any wrong step? And I can start flower when the target host is medium host. -
Convert Django JSON field to Text in subquery
I have two models Assignment and Application. Assignment has meta field which has uuid data that is used to match uuid field on Application. My goal is to join assignee information when I query applications. I have some code like this using subquery. assignment_subquery = Assignment.objects.filter( meta__uuid=Cast(OuterRef('uuid'), TextField()) ).values('assignee__username')[:1] # Query applications and annotate them with the assignee's username applications_with_assignee = Application.objects.annotate( assignee_username=Subquery(assignment_subquery) ) It produce SQL like this SELECT "application"."id", "application"."uuid", (SELECT U1."username" FROM "assignment" U0 INNER JOIN "auth_user" U1 ON (U0."assignee_id" = U1."id") WHERE (U0."meta" -> 'uuid') = ("application"."uuid")::text LIMIT 1) AS "assignee_username" FROM "application"; It is almost correct except U0."meta" -> 'uuid' instead of U0."meta" ->> 'uuid', which I believe extracts the value associated with the specified key as text. I can't figure out how to get it to generate the right query. Thank you very much for helping. -
How to fix Console Error "CSS Stylesheet not loaded due to 'text/html' MIME mismatch" in Django 4.2?
I was just working on my website, and everyday the grand stylings worked fine and everything was up to good shape. But today, I went on Chrome and loaded my website first offline using the Django default server and it showed no styles, and I thought that it was just a WIFI issue. Once I connected, I saw the stylings didn't change and there are 2 MIME errors in my consoles for all the 3 browsers I tried it with (Microsoft Edge, Firefox, and Chrome). My static directories are setup properly, but for some reason when I tried to visit the stylesheet link to get a CSS file, I got 404 instead. I really don't know why this is happening. I tried doing some simple changes to my stylesheet, like removing any comments, and I even removed the rel='stylesheet' attribute to see what happened. Nothing worked. I went and did many Google searches, and even used the AI preview there, browsed through Stack Overflow, and read the documentation. I tried all their recommendations but nothing worked. Here is the code snippet for my tags and static setup in settings.py. <!-- HTML HEAD --> <head> {% block ex_head %} {% endblock … -
Django enable Multi-Tenant Social Login (tenants provide their own OAuth2 credentials)
I have a multi-tenant Django app created using the django-tenants package. My social login is handled by python-social-auth (more precisely drf_social_oauth2). I'd like to allow tenants to provide their own OAuth2 credentials (client_id & client_secret) and authenticate through their own Google / Azure apps. Is there any way I can inject tenants' OAuth2 credentials in ConvertTokenView() based on what schema the request is made from? Alternatively, I was thinking about dynamically modifying the following two settings.py settings: # these are global, but i'd like each tenant to have their own creds SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "<google_client_id>" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "<google_client_secret>" This alternative method does not work, because these settings are only read on Django server startup. -
Exclude objects with a related date range
Using these (simplified of course) models: class Person(models.Model): name = models.CharField() class InactivePeriod(models.Model) person = models.ForeignKeyField(Person) start_date = models.DateField() end_date = models.DateField() class Template(models.Model): day = models.CharField() #choices = monday, tuesday, etc... person = models.ForeignKeyField(Person) class TheList(models.Model): person = models.ForeignKeyField(Person) date = models.DateField(default=datetime.today) attended = models.BooleanField(default=False) I have a workflow where people call in to sign up for a daily event (there will be no online registration). Originally my users were going to enter each attendee manually each day as they call by creating a TheList record, and then check off if they attended. However, as each event has regulars that typically come on the same days. It was decided that I would provide a Template table, where the user could designate that 'Mike' is a regular on 'Monday' and then I would use a cronjob to automatically populate the TheList table with records for people who were regulars for that day. Then, my user interface is going to automatically filter the TheList list view down to the current day's attendees, and then my users can make any changes as necessary. It just reduces the amount of input they need to do. The wrinkle is that my users requested that … -
Django ModuleNotFoundError: No module named 'storages' despite package being installed
I'm encountering a persistent ModuleNotFoundError when trying to run my Django project, even though the package is installed. Here are the details: Problem When I run: python3 manage.py runserver I get the following error: CopyModuleNotFoundError: No module named 'storages' Environment: Windows 10 Python 3.10 Django (version unspecified) Virtual environment (houseVenv) What I've tried: 1 - I've confirmed that django-storages is installed: (houseVenv) PS C:\path\to\project> pip3 list | findstr storage django-storages 1.14.4 However, when I try to import it manually, it fails: Traceback (most recent call last): File "<string>", line 1, in <module> ModuleNotFoundError: No module named 'storages' 2 - I've tried uninstalling and reinstalling django-storages. 3 - I've verified that I'm in the correct virtual environment. 4 - I've checked that 'storages' is in my INSTALLED_APPS in settings.py. Why is Python unable to find the 'storages' module even though it's installed, and how can I resolve this issue? -
Error when deploying Django/DRF backend on Google Cloud: No matching distribution found for Django==5.0.4
I am trying to deploy my Django backend (using Django Rest Framework) on a Google Cloud VM instance. However, when I run pip install -r requirements.txt, I encounter the following error: Here are the steps I performed cd Project_Backend python3 -m venv env sudo apt-get install python3-venv python3 -m venv env source ./env/bin/activate pip install -r requirements.txt I am running Ubuntu on my Google Cloud VM. How should I resolve this issue and successfully deploy my Django application? -
Django ORM - .exclude Q vs exclude(ids_in=ids) with Subquery, annotate
Django Queryset exclude() not working as expected with Q expressions I'm trying to exclude some Project objects from my queryset using two different methods: one based on IDs and the other using a Q expression on annotated data. However, I'm getting different results from each approach, and I can't figure out why. The version with the Q expression returns an empty queryset, even though it shouldn't. Here's the relevant code: def check_exclusion(): # Subquery to get the latest active ReportCalculation message for each project latest_calc_message = ReportCalculation.objects.filter( project=OuterRef('pk'), is_active=True ).order_by('-id').values('message')[:1] # Annotate projects with the latest calculation message projects_with_messages = Project.objects.annotate( latest_message=Subquery(latest_calc_message) ).filter( end_date__lt=date.today(), # Project must have ended is_active=True # Project must be active ).distinct() # Exclude based on latest_message excluded_projects = projects_with_messages.filter( Q(latest_message__in=("Scheduled.", "Finished successfully.", "Processing ...")) | Q(latest_message__startswith="Error") ).distinct() ids = excluded_projects.values_list("id", flat=True) # Exclude using Q expression directly on the annotated field remaining_projects = projects_with_messages.exclude( Q(latest_message__in=("Scheduled.", "Finished successfully.", "Processing ...")) | Q(latest_message__startswith="Error") ).values('id', 'latest_message') # Get IDs and messages for verification print(projects_with_messages.exclude(id__in=ids)) # First method using IDs print(remaining_projects.values_list("id", flat=True)) # Second method using Q expression return list(excluded_projects), list(remaining_projects) What I'm observing: When excluding projects by IDs (i.e., exclude(id__in=ids)), the exclusion works as expected. When using the …