Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
no html element seems to stretch the whole height of my page
i want to apply a background colour but the html, body and my containers dont seem to stretch the whole height of the page. this image demonstrates my problem demonstration why doesnt any element seem to stretch over my whole page? how can i apply a background colour with a gradient over the whole page without it repeating? #################################### below is my html if that helps this is a django site made of 2 html elements, i cant tell if the problem is due too the fact my body is declared in 1 html page, but contains things from another.... repeated_stuff.html <!DOCTYPE html> {% load static %} <html lang="en" style="height: 100%"> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" type="text/javascript"></script> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body style="background: linear-gradient(135deg, #ff9a75, #e8f9fd, #59ce8f); height: 100%; margin: 0;"> <div class="container text-center" id="main_container"> {% block content %} {% endblock %} </div> </body> </html> and heres my main content {% extends "repeated_stuff.html" %} {% block content %} {% load static %} <link rel="stylesheet" href="{% static 'carousel.css' %}"> <link rel="stylesheet" href="{% static 'quick_skills.css' %}"> <link rel="stylesheet" href="{% static 'layout_helper.css' %}"> <div class="row"> <div class="col" > <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="false" style="height :70vh; margin-left:15%; … -
Manager isn't accessible
**** view in the model***** class detail(DetailView): model = Requisicao context_object_name = 'requisicao' template_name = 'detail.html' pk_url_kwarg = 'pk' class itemManager(models.Manager): def get_queryset(self): return super(itemManager, self).get_queryset() First of all, thank you for your time and help. I'm trying to bring the items from this queryset but it's showing this error in my browser. I would like to know how to solve it. -
How to use the User built in model as a default value of another form?
I am working on a project that is dealing with the built-in User model. I have a class that showed me how to use the User model...Registering, Login/Logout, Dashboard, Being able to update the profile of a user, and Deleting an account. But I can't get it to click on using the logged in User in other ways. Such as a value in another form and Sorting based on user. The goal of the app is to A logged in user is able to 'create' a deck and the 'User' field is auto set to the logged in user A logged in user is able to only see the decks they have The user can edit/delete a deck owned by them views.py def my_decks(request): # this is me trying to get all decks owned by logged in user but doesn't work deck_list = Deck.objects.get(user=request.user) # Currently this creates a deck object but leaves the user field null if request.method == "POST": deck = DeckForm(request.POST, instance=request.user) if deck.is_valid(): deck.save() return HttpResponseRedirect('/my-decks') else: deck = DeckForm() context = {'deck': deck, 'deck_list': deck_list} return render(request, 'gametracker_app/my-decks.html', context=context) def update_deck(request): if request.method == 'POST': deck = UpdateDeckForm(request.POST) if deck.is_valid(): deck.save() return redirect('my-decks') else: deck … -
Celery redis reduce freqeuncy of BRPOP messages
I'm running my worker with the following arguments --without-gossip --without-mingle --without-heartbeat with Redis as my celery broker I can see my redis instance is frequently receiving messages (once a second) that look as follows: 1700056088.098427 [0 [::1]:45462] "BRPOP" "celery" "celery\x06\x163" "celery\x06\x166" "celery\x06\x169" "1" 1700056089.104080 [0 [::1]:45462] "BRPOP" "celery" "celery\x06\x163" "celery\x06\x166" "celery\x06\x169" "1" 1700056090.109984 [0 [::1]:45462] "BRPOP" "celery" "celery\x06\x163" "celery\x06\x166" "celery\x06\x169" "1" 1700056091.115298 [0 [::1]:45462] "BRPOP" "celery" "celery\x06\x163" "celery\x06\x166" "celery\x06\x169" "1" 1700056092.122189 [0 [::1]:45462] "BRPOP" "celery" "celery\x06\x163" "celery\x06\x166" "celery\x06\x169" "1" 1700056093.126348 [0 [::1]:45462] "BRPOP" "celery" "celery\x06\x163" "celery\x06\x166" "celery\x06\x169" "1" This amount of traffic means I can't use certain free-tiers in cloud providers. Realistically I only need to run a single periodic task every hour (like a cronjob). Is there a way to reduce the frequency / interval of these messages? -
Websocket not receiving messages from Django Channels server
I'm currently working on a project using Django Channels for WebSocket communication. However, I'm facing an issue where the WebSocket connection is established successfully, but messages are not being received on the client side. WebSocket connection is established without errors. I've verified that the Django Channels server is sending messages. However, the client-side WebSocket does not seem to receive any messages. my asgi.py is import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from channels.security.websocket import AllowedHostsOriginValidator import transposys_main.routing import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'transposys_main.settings') django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( URLRouter( transposys_main.routing.websocket_urlpatterns ) ), }) my consumer.py is import json from channels.generic.websocket import AsyncWebsocketConsumer import logging logger = logging.getLogger(_name_) logger.setLevel(logging.DEBUG) class DepartmentCreatedConsumer(AsyncWebsocketConsumer): async def connect(self): logger.info(f"WebSocket connected: {self.channel_name}") await self.accept() async def disconnect(self, close_code): logger.info(f"WebSocket disconnected: {self.channel_name}") async def receive(self, text_data): logger.info(f"WebSocket message received: {text_data}") try: text_data_json = json.loads(text_data) message_type = text_data_json.get('type') message = text_data_json.get('message') if message_type == 'department.created': logger.info(f"New Department: {message}") except json.JSONDecodeError as e: logger.error(f"Error decoding JSON: {e}") async def department_created(self, event): try: logger.info(f"Department created event received: {event['message']}") await self.send(text_data=json.dumps({ 'type': 'department.created', 'message': event['message'], })) except Exception as e: logger.error(f"Error sending WebSocket message: {e}") routing is from django.urls import re_path from … -
TemplateDoesNotExist error in Django Webapp
I am getting this error when i try to use the default django login page: TemplateDoesNotExist at /login/ registration/login.html this is my urls file: from django.urls import path from django.urls import path, include from . import views urlpatterns = [ path("", views.home, name="home"), path("main-page/", views.main_page, name="main-page"), path("kick-page/", views.kick_page, name="kick-page"), path('', include("django.contrib.auth.urls")), # add django auth pages for login ] this is my views file: from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth import login, authenticate from .forms import * #import all the forms from forms.py def home (response): form = SignIn() return render(response, "main/home.html", {"form": form}) #need a page to select site/microtik, and add/remove microtiks def main_page (response): return render(response, "main/main_page.html", {}) #Need a page that shows the selected mictotik and a form to enter MAC of device to kick def kick_page (response): return render(response, "main/kick_page.html", {}) and this is my directory structure: C:. └───microsite │ db.sqlite3 │ manage.py │ ├───main │ │ admin.py │ │ apps.py │ │ forms.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ __init__.cpython-311.pyc │ │ │ ├───templates │ │ … -
Django "request.user" always returns "AnonymousUser" even though sessionid gets added and is valid
So I made a discord oauth2 login without using a User model like AbstractUser or AbstractBaseModel, when I first made it a month ago, it worked fine and the login worked flawlessly! (Profile loaded, username shown, etc.) I don't know what I changed a week ago, but it no longer works. The custom authentication works and authenticate() returns a new DiscordUser model, then it gets passed to login() with the custom backend argument. The sessionid gets saved in the cookie storage when I check it. When I also check the DB, the sessionid is there and therefore a valid sessionid. Yet when I print out the request.user or request.user.is_authenticated I always get AnonymousUser and False. I don't understand. I followed this video: https://www.youtube.com/watch?v=KKJyU7JGuVk&list=PLwu1p7jK5YEUhRNJpzLYa8nhWRnJdPR6p auth.py: from django.contrib.auth.backends import BaseBackend from .models import DiscordUser class DiscordAuthenticationBackend(BaseBackend): def authenticate(self, request, user) -> DiscordUser: try: user = DiscordUser.objects.get(pk=user["id"]) return user except DiscordUser.DoesNotExist: new_user = DiscordUser.objects.create_discord_user(user) new_user.save() return new_user managers.py from django.contrib.auth import models from datetime import datetime from utils.cipher import XChaCha20Manager from base64 import b64encode class DiscordUserOAuth2Manager(models.UserManager): def create_discord_user(self, user): # encrypt tokens with the same nonce encrypted_access_token, nonce = XChaCha20Manager().encrypt(user["access_token"].encode()) encrypted_refresh_token, _ = XChaCha20Manager(nonce=nonce).encrypt(user["refresh_token"].encode()) new_user = self.create( user_id=user["id"], username = f"{user["username"]}", avatar = … -
Sending the output of two filters in one querystring to filter a django model
I have two filters. I have used pokemon as the example: Filter A: filters the pokemon trading card sets e.g. Base set, Fossil, Jungle Filter B: Filters the pokemon stats, e.g. pokemon types, name of pokemon. Those two filters have two submit buttons, I want them to work together. If I hit the submit for filter B it sends: ?name=Bulbasaur&type= If I hit the submit for filter A it sends: ?sets=Jungle What I want is: ?name=Venusaur&type=&sets=Fossil I'm using the module django-filters, I construct a FilterSet class for each filter that I initiate in the view. pokemon_sets = PokemonSets.objects.all() pokemon_filter = PokemonSetsFilter(request.GET, queryset=pokemon_sets) sets = pokemon_filter.qs.values_list('key_id', flat=True) pokemon = PokemonDatabase.objects.filter(sets__in=sets) pokemon_filter = PokemonFilter(request.GET, queryset=listings) Any insight will help greatly! I tried filtering the pokemondatabase model to the output of the filter to chain the filters to filter the model, but only one filter works at a time. -
How to dynamically set the access token expiration in Django Rest Framework Simple JWT?
I am working on a restful web application using Django Rest Framework and need to implement a mechanism to check every 15 minutes if the user has been active in order to extend their token expiration. If the user has not been active, their access token should become invalid. I am using Djoser in conjunction with Simple JWT as the authentication backend. Can someone provide guidance on how to achieve this? Thank you. I have tried creating a custom middleware to track the user's activity for the last 15 minutes but do not know how to effectively manage the user's jwt access token based on the user activity. -
Run Tests with Coverage "TypeError: Parameters to Generic[...] must all be type variables"
When running tests with coverage using PyCharm on django (python) project, im having the following error: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2023.1.2\plugins\python\helpers\pycharm\django_test_manage.py", line 6, in <module> from django.core.management import ManagementUtility File "C:\Users\User\Project\Code\venv39-master\lib\site-packages\django\core\management\__init__.py", line 13, in <module> from django.apps import apps File "C:\Users\User\Project\Code\venv39-master\lib\site-packages\django\apps\__init__.py", line 1, in <module> from .config import AppConfig File "C:\Users\User\Project\Code\venv39-master\lib\site-packages\django\apps\config.py", line 7, in <module> from django.utils.deprecation import RemovedInDjango41Warning File "C:\Users\User\Project\Code\venv39-master\lib\site-packages\django\utils\deprecation.py", line 5, in <module> from asgiref.sync import sync_to_async File "C:\Users\User\Project\Code\venv39-master\lib\site-packages\asgiref\sync.py", line 130, in <module> class AsyncToSync(Generic[_P, _R]): File "C:\Program Files\Python39\lib\typing.py", line 277, in inner return func(*args, **kwds) File "C:\Program Files\Python39\lib\typing.py", line 997, in __class_getitem__ raise TypeError( TypeError: Parameters to Generic[...] must all be type variables class SimpleTest(TestCase): def test_basic_addition(self): self.assertEqual(1 + 1, 2) According to what i have read, its probably a version conflict between typing and asgiref. Here are the versions I'm using: typing_extensions 4.8.0 asgiref 3.7.2 Python 3.9.13 Django 3.2.20 Whats weirder is that running the the same test with coverage (using lib coverage.py) from terminal, everything works. coverage run ./manage.py test -v 3 According to Jetbrains, the PyCharm IDE uses the exact same library for coverage...What could be the solution? -
Django 4.2 , GenericIPAddress and CIDR
Im updating a project from: Python 3.9 + Postgres 13 + Django 4.0.6 + psycopg2 TO Python 3.11 + Postgresql 15 + Django 4.2 + psycopg3 I have a big problem with GenericIPFields. It seems that it doesn't support cidr anymore. When I try to save an ORM with a cidr, I get: ValueError: '10.255.96.48/28' does not appear to be an IPv4 or IPv6 address I need that INET FIELD on DB with cidr to make queryes like: Subnet.objects.filter().extra(where = [ "cidr::inet >>= inet '"+self.ip_address+"'" ]) and other cidr related queries. -
How can I define multiple URL patterns in Django?
Could anyone tell me how to define multiple URL patterns in Django? On YouTube, I watched a few videos, but they didn't help me and I found a lot fo mistakes in it. Thank you for helping to define multiple URL patterns in Django. -
Create a watch list feature
The user can add that product to the watch list by clicking on the add button, and then the add button will change to Rimo. And this time by clicking this button, the product will be removed from the list. There should be a link on the main page that by clicking on it, all the products in the watch list will be displayed, and by clicking on the detail button, you can see the details of the product, and by clicking on the remove button, you can remove them from the list. models.py class User(AbstractUser): pass class List(models.Model): choice = ( ('d', 'Dark'), ('s', 'Sweet'), ) user = models.CharField(max_length=64) title = models.CharField(max_length=64) description = models.TextField() category = models.CharField(max_length=64) first_bid = models.IntegerField() image = models.ImageField(upload_to="img/", null=True) image_url = models.CharField(max_length=228, default = None, blank = True, null = True) status = models.CharField(max_length=1, choices= choice) active_bool = models.BooleanField(default = True) views.py: def product_detail(request, product_id): product = get_object_or_404(List, pk=product_id) comments = Comment.objects.filter(product=product) if request.method == 'POST': # comment if 'comment' in request.POST: user = request.user if user.is_authenticated: content = request.POST.get('content') comment = Comment(product=product, user=user, content=content) comment.save() context = { 'product': product, 'comments': comments, } return render(request, 'auctions/product_detail.html', context) from .forms import AddWatchlist def … -
Retrieving files using django rest Framework and postman
I am making a secure file storage system In this for the decryption process user is giving the file_id and key as an input. The program finds the file, reads it's data and decrypts it using the key and rewrites the file data of the file with the new encrypted data and return the file. I'm using django rest framework for this. The code for the view is given below: class Decryption(APIView): def post(self, request, *args, **kwargs): file_id = request.data.get('file_id') key = request.data.get('key') try: if not key: return Response({"error": "Key is required"}, status= status.HTTP_400_BAD_REQUEST) try: encrypted_file = EncryptedFile.objects.get(id = file_id) except EncryptedFile.DoesNotExist: return Response({'detail': "The requested File doesn't exist"}, status= status.HTTP_404_NOT_FOUND) encrypted_data = encrypted_file.file.read() cipher = Fernet(key) decrypted_data = cipher.decrypt(encrypted_data) encrypted_file.file.seek(0) #encrypted_file.file.write(decrypted_data) response = Response() response['Content-Disposition'] = f'attachment: filename = {encrypted_file.file_name}' response.write(decrypted_data) return response except Exception as e: return Response({'details': e}, status= status.HTTP_400_BAD_REQUEST) I was expecting a file as a result. But I got a blank screen when I made an API call using postman -
Failed authentication for Google Sheet and Django running in Apache server
I'm implementing a Django application that uses a Google Sheet as database, and is hosted with Apache in a Rocky Linux server. To test the integration between Django and Google Sheet, I have followed Tom Dekan Tutorial. And to configure the Django application to run with Apache, I have followed the official Django Tutorial. However, when I try to access the page, I receive an Internal Server Error. Checking the error logs, I receive the following message: [Thu Nov 16 11:44:34.203173 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] mod_wsgi (pid=150297): Failed to exec Python script file '/opt/dashbea/TesteGSheet/core/core/wsgi.py'. [Thu Nov 16 11:44:34.203297 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] mod_wsgi (pid=150297): Exception occurred processing WSGI script '/opt/dashbea/TesteGSheet/core/core/wsgi.py'. [Thu Nov 16 11:44:34.203791 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] Traceback (most recent call last): [Thu Nov 16 11:44:34.203866 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] File "/opt/dashbea/TesteGSheet/core/core/wsgi.py", line 22, in <module> [Thu Nov 16 11:44:34.203876 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] application = get_wsgi_application() [Thu Nov 16 11:44:34.203885 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] File "/opt/dashbea/TesteGSheet/my_env/lib64/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Thu Nov 16 11:44:34.203893 2023] [wsgi:error] [pid 150297:tid 150433] [remote 143.106.120.120:51686] django.setup(set_prefix=False) [Thu Nov 16 11:44:34.203902 2023] [wsgi:error] [pid 150297:tid … -
Pytest and Selenium in Docker : wrong database used for the test suite?
I'm struggling to setup my test runner for a new Django project. I want to use these libraries : Django 4.2 pytest-django 4.6.0 pytest-splinter 3.3.2 And I want it to work with Docker. I got a head start with that answer : https://stackoverflow.com/a/58447497/3219759 but I can't make it work. Here is my docker-compose.yml : version: '3.3' services: web: build: jam restart: always command: python manage.py runserver 0.0.0.0:8000 environment: - USE_DOCKER=True env_file: - .env ports: - "127.0.0.1:8000:8000" volumes: - .:/code links: - db depends_on: - db - selenium db: image: postgres environment: - POSTGRES_USER=xxx - POSTGRES_PASSWORD=xxx - POSTGRES_DB=xxx ports: - "127.0.0.1:5432:5432" volumes: - pg_data:/var/lib/postgresql/data selenium: image: selenium/standalone-firefox:4.9.1 ports: - "4444:4444" # Selenium - "5900:5900" # VNC volumes: pg_data: And to finish the setup, I have these fixtures in the conftest.py file : @pytest.fixture(scope='session') def test_server() -> LiveServer: addr = socket.gethostbyname(socket.gethostname()) server = LiveServer(addr) yield server server.stop() @pytest.fixture(scope='session') def splinter_webdriver(): return 'remote' @pytest.fixture(scope='session') def splinter_remote_url(): return 'http://selenium:4444/wd/hub' and this in settings.py: if env('USE_DOCKER') == 'yes': import socket ALLOWED_HOSTS = [socket.gethostbyname(socket.gethostname())] I have a basic view that list all the profiles, and a template to match. This feature is working on my local server. The corresponding test: @pytest.mark.django_db class TestIndexPage: def test_profile_list(self, browser, … -
Email simulation with Django
This project should be able to simulate email. The program runs successfully and I can write the email, but the email is not sent and it gives this error. what is the problem؟ in terminal: [16/Nov/2023 17:35:46] "GET /emails/inbox HTTP/1.1" 200 2 in console: MLFormElement. (inbox.js:10:7) code: document.addEventListener( "DOMContentLoaded",function () { const form = document.querySelector("#compose-form"); const msg = document.querySelector("#message"); form.addEventListener("submit", (event) => { event.preventDefault(); to = document.querySelector("#compose-recipients"); subject = document.querySelector("#compose-subject"); body = document.querySelector("#compose-body"); if (from.length == 0 && to.length == 1000) return; fetch("/emails", { method: "POST", body: JSON.stringify({ recipients: to.value, subject: subject.value, body: body.value, }), }) .then((response) => response.json()) .then((result) => { console.log(result.status); if (result.status == 201) { load_mailbox("sent"); } else { msg.innerHTML = `<div class="alert alert-danger" role="alert"> ${result.error} </div>`; } }); }); }, false ); -
How do I change the default buttons in django?
In django admin, models have default buttons, how can I change the name of these buttons? enter image description here -
how to create djagno notification system like instagram?
I am creating APIs for an Instagram-like application using Django (Celery). I have implemented a notification system for whenever a like is performed on a post, but I want notification aggregation similar to Instagram ('user1 and 23 others liked your post'). I tried to create it, but I couldn't wrap my head around it. -
Load variables from a virtual env for a cron task on Azure web app server
I have a python (Django) web app running on Azure App Service. Despite everything I tried from other SO threads, I can't figure out how to have the environment variables accessed from my cron tasks. It may be caused by how Azure duplicates the venv into a weird antenv. More on that later. What I really want is to use Django commands in cron, like ./manage.py some_command. However, I quickly realized that the Django virtual env is not loaded properly in cron. So I decided to go step by step and see how to access the virtual env from cron. What I have tried Initial implementation I am testing my setup using Azure App Service SSH console available at https://{my-app-name}.scm.azurewebsites.net/webssh/host. Script I created a script /home/scripts/log-env.sh to test the water: #!/bin/bash trace=/home/scripts/trace path=$(...) # Some command that locates the venv directory echo "src path: ${path}" > ${trace} # I can see ${path} is set correctly echo "MY_VAR before source: [${MY_VAR}]" >> ${trace} source ${path}/antenv/bin/activate; echo "MY_VAR same command line as source: [${MY_VAR}]" >> ${trace} echo "MY_VAR after source: [${MY_VAR}]" >> ${trace} Output When I run the script in the terminal, it shows that I don't even need to source the … -
How to split development env file and production env file with docker compose?
I have dockerized django application with nginx. And I have two env files: one for development and one for production. The contents of the env files are the credentials of the database. But apparently, the credentials that are inside the prodduction env file are not executed. My folder structure looks like this: root - welzijn -admin So when I put the env files with names: .env and prod.env in the root folder, it doesn't work. But when I put the .env file with the credentials of production in the welzijn folder it works. And even when I put the file prod.env in the folder welzijn it also doesn't work I really scratch my head over this. So this is the dockerfile: # pull official base image FROM python:3.9-alpine3.13 # ENV PATH="/scripts:${PATH}" # set work directory # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./scripts /scripts WORKDIR /usr/src/app EXPOSE 8000 # install psycopg2 dependencies ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client jpeg-dev && \ apk add --update --no-cache --virtual .tmp-build-deps \ build-base postgresql-dev musl-dev zlib zlib-dev linux-headers && \ /py/bin/pip install -r … -
OperationalError: (1317, 'Query execution was interrupted') during migration
I'm encountering a problem with Django migrations, specifically encountering an OperationalError (1317, 'Query execution was interrupted') during the migration process. This issue arises when executing the python manage.py migrate command. It's worth noting that this problem doesn't occur locally; rather, it's specific to the production environment during migration. The process seems to get stuck at the migration for approximately 1 minute before ultimately raising the error outlined below. Applying accounts.0049_userprofile_description... Traceback (most recent call last): File "/home/ubuntu/venv/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/venv/lib/python3.11/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/venv/lib/python3.11/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) ^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/venv/lib/python3.11/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/home/ubuntu/venv/lib/python3.11/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb.OperationalError: (1317, 'Query execution was interrupted') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/ubuntu/****/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/ubuntu/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/ubuntu/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/venv/lib/python3.11/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/venv/lib/python3.11/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/venv/lib/python3.11/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/venv/lib/python3.11/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state … -
Can I force Django to load images with space in the filename?
I have a folder with image files. Unfortunately, some files contain a space in their name. Django is able to load these images if I run the app on the development server (via python manage.py runserver) but not if I run it in production. The reason is that Django converts " " to "%20". For example, if my folder contains the following files: image1.png image2 test.png image3%20test.png (just to understand what is happening) ... then this code will have the following result: # In settings.py MEDIA_URL = '/media/' MEDIA_ROOT = ('D:/Data/Images') # In the HTML template <img src="/media/image1.png"/> # image loads on the development and production server <img src="/media/image2 test.png"/> # image loads only on the development server <img src="/media/image3 test.png"/> # image loads only on the production server I could of course rename all image filenames that contain space characters by replacing the spaces with underscores. But that's a bit awkward as a chemical analysis system is constantly feeding new image files to the folder and the system's software will occasionally introduce spaces in the filenames. I do not have control over this. So is there a way to force Django to load images even if they contain space … -
Django update method for incrementing is super slow
I have a model using json fields, while this works like a charm 99% of times I now have a kinda annoying issue, execution time. I need to increment a LOT of records using Django's ORM update method, I don't know how fast it should be if the db was using something else than json fields, but basically here's some examples of time I'm facing: 4000 records update for just a +1 in a json field took 20 seconds 6000 records update took almost 2 minutes Those were small ones, I expect some update to have more than 100000 records, could even reach a million. For the technical side of what I am exactly doing: I use filter on a range inside the jsonfield values to extract records that requires an update, this runs perfectly fine, after getting the queryset I use update to increment one of the jsonfield value by 1. This behavior is very specific and probably not the most optimal but this is what I have for now, to do it I make a raw sql query using RawSQL, for reference here is the function that generate the said query: def jsonfield_increment(field_name: str, key: str, increment_by: int … -
How to find out the Python representation of Django fields?
For example I have this code: class SomeModel(models.Model): instance_name = models.UnknownField(max_length=255) instance_id = models.IntegerField() I want to have the model name (SomeModel) and field name (for ex. instance_name) as an input, and the, and the output will be the python representation of that field (for ex.: srt, int, float...) So it will be something like this: def find_out_the_field_python_type(model: Model, field_name: str) -> type: # For example model = SomeModel, field_name = instance_id # return int return I have tried this: instance_id_field = SomeModel._meta.get_field('instance_id') # Determine the Python representation of the field python_representation = instance_id_field.get_internal_type() print(python_representation) # returns 'IntegerField' But the problem that it returns not the python representation, but the type of Django field.