Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python app Showing index of page on cPanel
Website When I opening my website, it showing index of page instead of showing thenpython application. Permission: 777 for passenger_wsgi file (Tried 755 also). This index of page showing a cgi_bin page, and htaccess file is also as expected as well. I don't understand what's going on here :") I tried but it keeps showing this page. -
LCP Issue in Django Project - Render Delay Caused by Backend-Generated Text Element
I'm currently working on a website built with Django and I'm having trouble with the Largest Contentful Paint (LCP). According to Google PageSpeed Insights, the LCP time is 5,070ms with a significant 88% render delay (4,470ms), and it identifies a <p> element as the LCP element. It seems that the issue is caused by dynamically generated text from the backend. The LCP element is being delayed, most likely due to render-blocking resources or inefficient processing of HTML above the fold. Here’s the snapshot from PageSpeed Insights: I’ve tried: Minifying and deferring non-critical JS. Removing unsued JS and CSS. Using font-display: swap; Ensuring images are optimized (though the LCP element is not an image). Also I tried to defer non critical css (even though the it is a critical and only used css file) by applying the following pattern from this article: <link rel="preload" href="{% static "css/city/city-critical.min.css" %}" as="style" onload="this.onload=null;this.rel='stylesheet'"> <noscript><link rel="stylesheet" href="{% static "css/city/city-critical.min.css" %}"></noscript> Any methods or ideas on how to fix it? -
How to save data into two related tables in Django?
I'm new to Django and I'm following a tutorial to create a school system. I have a CustomUser that is related to three different tables by a OneToOneField(), when registering a user, depending on the type (HOD, teacher, student), I create two signals with @receiver to create an instance of the POST request and then save it in its respective table. Problem: When I try to save the data, I use a CustomUser object and call the create_user() class that I save in a user variable, but when I use that object to save other data from the table I need (Teachers in this case) the user is not created: def create_teachers(request): if auth_user(request) == True: # Do something for authenticated users. if request.method == 'GET': return render(request, 'create_teachers.html') else: try: user = CustomUser.objects.create_user( password='defaultPass', first_name=request.POST.get('first_name'), last_name=request.POST.get('last_name'), email=request.POST.get('email'), user_type=2, ) user.Teachers.address=request.POST.get('address') user.save() print('Professor created successfully') return redirect('/auth/create_teachers') except: print('Error creating teacher') return redirect('/auth/create_teachers') else: return redirect('../login') Error creating teacher [27/Sep/2024 13:46:14] "POST /auth/create_teachers HTTP/1.1" 302 0 [27/Sep/2024 13:46:14] "GET /auth/create_teachers HTTP/1.1" 200 34724 [27/Sep/2024 13:46:14] "GET /static/css/dist/styles.css?v=1727459174 HTTP/1.1" 200 54543 # admin.py class UserAdmin(BaseUserAdmin): ordering = ('email',) admin.site.register(CustomUser, UserAdmin) # managers.py class CustomUserManager(BaseUserManager): """ Custom user model manager where email … -
Why does my Celery task not start on Heroku?
I currently have a dockerized django app deployed on Heroku. I've recently added celery with redis. The app works fine on my device but when I try to deploy on Heroku everything works fine up until the Celery task should be started. However nothing happens and I don't get any error logs from Heroku. I use celery-redis and followed their setup instructions but my task still does not start when I deploy to Heroku. Here is my code: heroku.yml: setup: addons: - plan: heroku-postgresql - plan: heroku-redis build: docker: web: Dockerfile celery: Dockerfile release: image: web command: - python manage.py collectstatic --noinput run: web: gunicorn mysite.wsgi celery: celery -A mysite worker --loglevel=info views.py: from celery.result import AsyncResult task = transcribe_file_task.delay(file_path, audio_language, output_file_type, 'ai_transcribe_output', session_id) task.py: from celery import Celery app = Celery('transcribe')# @app.task def transcribe_file_task(path, audio_language, output_file_type, dest_dir, session_id): print(str("TASK: "+session_id)) #rest of code return output_file celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") app = Celery("mysite") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() I ensured that my CELERY_BROKER_URL and CELERY_RESULT_BACKEND are getting the correct REDIS_URL from environment variables by having it printing it's value before the task is to be started. So I … -
How to make a logout model that redirects the user to the homepage while keeping the language of the user. For example: /home/fr/ instead of/home/en/?
How to make a logout model that redirects the user to the homepage while keeping the language of the user class LogOut(Page): def serve(self, request): # Redirect to home page return HttpResponseRedirect('/home/') -
How to bundle all necessary dependencies in pyinstaller .exe file?
I have a typing game that is made using django and websockets ,I want to make ".exe file" to run this game on another pc that does not even have python installed !! I tried this code below and it worked only in my current working pc. Here is a Runner.py code that i used in the pyinstaller cmd import subprocess import time # Start the Django server subprocess.Popen(["python", "manage.py", "runserver"], shell=True) # Wait for the server to start time.sleep(5) # Open the webpage in Chrome chrome_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe" # Adjust if necessary subprocess.Popen([chrome_path, "http://localhost:8000"]) # Adjust URL if necessary in the target pc only chrome opens but the server doesnt run thus python manage.py runserver is not working maybe cause the target pc doesnt even have python nor django installed ? and it cant find the manage.py file? so what im thinking is i need a way to bundle everything in a way that it workes on any device. Note : the pyinstaller cmd is pyinstaller --onefile --noconsole runner.py -
What would you say will be the best way to separate two different type of users to two different types of frontend/GUI?
So currently I am developing a project called manage+ using Django+React, I want to redirect them to different type of frontend?GUI based on their different type of roles, now what would you suggest I should do, do I make two completely different type of frontend, or any other idea or anything that you would suggest? I tried making two different frontend, and also did one logic which fetches the type of user from backend and then load the different frontend based on that user using some logic in frontend itself, but I think it is not very ethical or I should say it makes it slow I guess. -
how to show database data on a separate page
I am working on an activity tracker for my web development class and we're working with django. I'm trying to add a page that shows the activity details on a separate page by passing it's id into the url to display the activity info specific to that database object (similar to news articles on websites) I think the problem lies in my views page. I need help writing how to properly get the info from the database to pass over to the html form. The page loads fine with the id attached to the url but no info is showing views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpRequest from . models import Activity # Create your views here. def index(request: HttpRequest): activites = Activity.objects.all() return render(request, "activity/index.html", {"activites" : activites}) def new_activity(request: HttpRequest): if request.method == 'POST': params = request.POST activity = Activity( activity_name = params.get("activity_name") ) activity.save() return redirect("/") return render(request, "activity/new_activity.html") def activity(request: HttpRequest, id): id = Activity.objects.get(id=id) return render(request, "activity/activity.html") Here's what I have for the html page (open to renaming the data passed if necessary) activity.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>{{ activity.activity_name }}</h1> … -
Error 'CLR20r3' calling external aplication
I have a portal in Python 3.11 and Django 5.0.8 this portal in some point calls a external app developed in vb.net, this is the way i call the vb.net app subprocess.call('C:\\some\\Direction\\ExternalApp.exe', 'parameter1', 'parameter2', 'parameter3', 'parameter4', ...), i have tried the portal with IIS 10 on windows 11 and the python server and works fine, but when use in the IIS 10 on windows server 2022 standard gives me error, and using the python server on WS 2022 works fine, this is the error that shows me the event viewer: Aplicación: ExternaApp.exe Versión de Framework: v4.0.30319 Descripción: el proceso terminó debido a una excepción no controlada. Información de la excepción: System.IndexOutOfRangeException en System.Data.DataView.GetRow(Int32) en System.Data.DataView.get_Item(Int32) en ExternalApp.cls.function(Int32, Int32, Int32, System.String, System.String, System.String, System.String, System.String) en ExternalApp.DM1.Main() Nombre de la aplicación con errores: ExternalApp.exe, versión: 1.0.0.0, marca de tiempo: 0x66f5c058 Nombre del módulo con errores: KERNELBASE.dll, versión: 10.0.20348.2227, marca de tiempo: 0xe95c736c Código de excepción: 0xe0434352 Desplazamiento de errores: 0x000000000003f19c Identificador del proceso con errores: 0x3804 Hora de inicio de la aplicación con errores: 0x01db113917154b04 Ruta de acceso de la aplicación con errores: C:\some\direction\ExternalApp.exe Ruta de acceso del módulo con errores: C:\Windows\System32\KERNELBASE.dll Identificador del informe: c2dd5273-2d2d-4f89-9f3c-136d4f99f49a Nombre completo del paquete con … -
How to arbitrarily nest some data in a django rest framework serializer
An existing client is already sending data in a structure like… { "hive_metadata": {"name": "hive name"}, "bees": [{"name": "bee 1", "name": "bee 2", ...}] } For models like: class Hive(models.Model): name = models.CharField(max_length=32, help_text="name") class Bee(models.Model): name = models.CharField(max_length=32, help_text="name") hive = models.ForeignKey( Hive, help_text="The Hive associated with this Bee", on_delete=models.CASCADE ) The code that makes this possible manually iterates over the incoming data. I would like to rewrite it using a django rest framework serializer; however, the fact that hive_metadata is nested itself has stumped me so far. If I write class BeesSerializer(ModelSerializer): class Meta: model = models.Bee fields = ("name",) class PopulatedHiveSerializer(ModelSerializer): bees = BeesSerializer(many=True, source="bee_set") class Meta: model = models.Hive fields = ("name","bees",) would produce { "name": "hive name", "bees": [{"name": "bee 1", "name": "bee 2", ...}] } readily enough. I had hoped I could solve it with a reference to a sub-serializer, something like class HiveMetaDataSerializer(ModelSerializer): class Meta: model = models.Hive fields = ("name",) class PopulatedHiveSerializer(ModelSerializer): bees = BeesSerializer(many=True, source="bee_set") hive_metadata = HiveMetaDataSerializer(source=???) class Meta: model = models.Hive fields = ("hive_metadata","bees",) but I can't seem to figure out what to put in the "source" so that the same object is passed through the outer serializer into … -
How do I tell mypy that except() will bail a pytest test?
The following code works, but I fell like I shouldn't have to write it: def test_transaction(self, the_client): [...] transaction: Transaction = transactions.filter([...]).first() # NOTE: this is stupid and unnecessary just to satisfy mypy. # the next expect() will bail if this test is true, # so this if statement is completely superfluous if transaction is None: raise AssertionError("missing transaction") # I want to tell mypy this works like the above if statement expect(transaction).not_to(be_none()) # if the if statement above isn't there, it tells me # None | Transaction doesn't have the property "client" expect(transaction.client).to(equal(the_client)) [...] Is there an easier way to do this that will satisy mypy? I have 1000+ tests like this and I don't want to add 2000+ more lines of completely unnecessary, useless code just to make a freaking code checker happy. I have the django and drf stubs installed. -
Issue with Django and Cross-Origin Request Blocked
i'm having issues with an API i have on docker it works with Django, I can access from other PCs on my network, however everytime i try to log in from any other PC that's not Mine i get the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/users/login. (Reason: CORS request did not succeed). Status code: (null). Right now my code is like this: `ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", 'django.middleware.common.CommonMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:3001', 'http://localhost:3000', 'http://127.0.0.1:3001', 'http://127.0.0.1:3000', ] CORS_ALLOW_CREDENTIALS = True` I have tried Everything CORS_ORIGIN_ALLOW_ALL = True Doesn't work CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:3001', ) Doesn't work Either CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True Doesn't work I even tried CORS_ALLOW_METHODS = ( "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ) according to the documentation on here -
Django: Middleware for JWT Token Encryption and Cookie Setting
I'm working on implementing JWT token encryption in my Django application using rest_framework_simplejwt. I've created a custom middleware TokenEncryptionMiddleware that encrypts access and refresh tokens before setting them as cookies. However, the client-side seems to receive the unencrypted response from TokenObtainPairView. What am I missing here? Are there any interactions between rest_framework_simplejwt and custom middleware that I need to be aware of to ensure my encryption works as intended? Here's my middleware code: """ Middleware for crypting the JWT tokens before setting them as cookies. """ from base64 import urlsafe_b64encode from cryptography.fernet import Fernet from django.conf import settings from django.utils.deprecation import MiddlewareMixin class TokenEncryptionMiddleware(MiddlewareMixin): """ Middleware to encrypt the JWT tokens before setting them as cookies. """ def process_response(self, request, response): """ Encrypts the JWT tokens before setting them as cookies. """ if response.status_code == 200 and ( "access" in response.data and "refresh" in response.data ): base_key = settings.JWT_KEY.encode()[:32] cipher = Fernet(urlsafe_b64encode(base_key)) encrypted_access_token = cipher.encrypt( response.data["access"].encode() ).decode() encrypted_refresh_token = cipher.encrypt( response.data["refresh"].encode() ).decode() del response.data["access"] del response.data["refresh"] response.set_cookie( "access_token", encrypted_access_token, httponly=True, secure=True, samesite="Strict", ) response.set_cookie( "refresh_token", encrypted_refresh_token, httponly=True, secure=True, samesite="Strict", ) return response Middleware order 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", "middlewares.crypter.TokenEncryptionMiddleware", ] Expected behavior: The client … -
I am getting Django and s3 bucket error even though I have set correct Django secret key
This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>SignatureDoesNotMatch</Code> <Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message> <AWSAccessKeyId>AKIA34AMDD2GCZQZATNN</AWSAccessKeyId> <StringToSign>AWS4-HMAC-SHA256 20240927T153821Z 20240927/ap-south-1/s3/aws4_request b957e2f91638df2b469e164c9eb7821fa8cb2d5ba935f28f00d0fcd763ac0ee5</StringToSign> <SignatureProvided>191d810fd975c25775820bc612d854fbc85bbcf7590e6c4b1fe0bda07ff399f4</SignatureProvided> <StringToSignBytes>41 57 53 34 2d 48 4d 41 43 2d 53 48 41 32 35 36 0a 32 30 32 34 30 39 32 37 54 31 35 33 38 32 31 5a 0a 32 30 32 34 30 39 32 37 2f 61 70 2d 73 6f 75 74 68 2d 31 2f 73 33 2f 61 77 73 34 5f 72 65 71 75 65 73 74 0a 62 39 35 37 65 32 66 39 31 36 33 38 64 66 32 62 34 36 39 65 31 36 34 63 39 65 62 37 38 32 31 66 61 38 63 62 32 64 35 62 61 39 33 35 66 32 38 66 30 30 64 30 66 63 64 37 36 33 61 63 30 65 65 35</StringToSignBytes> <CanonicalRequest>GET /products/Screen_Shot_2024-07-25_at_18.30.09.png X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIA34AMDD2GCZQZATNN%2F20240927%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20240927T153821Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host host:sellxmedia.s3.ap-south-1.amazonaws.com host UNSIGNED-PAYLOAD</CanonicalRequest> <CanonicalRequestBytes>47 45 54 0a 2f 70 72 6f 64 75 63 74 73 2f … -
Need help on running the server of a django proyect connected with postgreSQL
When executing 'runserver' of manage.py, this error happens: System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1045, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2544.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 982, in run self._target(*self._args, **self._kwargs) File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run self.check_migrations() File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\base.py", line 581, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\migrations\recorder.py", line 89, in applied_migrations if self.has_table(): ^^^^^^^^^^^^^^^^ File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\migrations\recorder.py", line 63, in has_table with self.connection.cursor() as cursor: ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\backends\base\base.py", line 320, in cursor return self._cursor() ^^^^^^^^^^^^^^ File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\backends\base\base.py", line 296, in _cursor self.ensure_connection() File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\backends\base\base.py", line 279, in ensure_connection self.connect() File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\backends\base\base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\backends\postgresql\base.py", line 332, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LABORATORIO\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\psycopg2\__init__.py", line 122, … -
Bug build on esbuild for Angular/Django application
Angular 4 to 18 Migration: esbuild Errors and MIME Type Issues Background I'm updating an application from Angular 4 to Angular 18 with Django as the backend. I've migrated to esbuild, but I'm encountering errors in the browser after a successful build, and the application is broken. Issue After building, I notice that the main, polyfill, and style transpiled files are the same. The application fails to load properly, with several errors related to MIME types and module loading. Errors Failed to load module script: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. Font file 404 errors: GET https://app/media/fontawesome-webfont-5GKVPAEF.woff2?v=4.7.0 net::ERR_ABORTED 404 (Not Found) GET https://app/media/fontawesome-webfont-Z4ARLA73.woff?v=4.7.0 404 (Not Found) GET https://app/media/fontawesome-webfont-RJ6LE7IU.ttf?v=4.7.0 net::ERR_ABORTED 404 (Not Found) Script execution refused: Refused to execute script from 'https://app/scripts-JNRFGZAM.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. Main script loading failure: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. CSS loading … -
Connecting On-Prem Django App with Microsoft Fabric DWH fails: Invalid connection string attribute
I'm trying to connect my Django app to microsoft fabric warehouse but I get the following error messages: django.db.utils.Error: ('01S00', '[01S00] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0) (SQLDriverConnect); [01S00] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0)') I tried various combinations to build the connection string in the settings.py. My first attempt was: 'FabricDW': { 'ENGINE': 'mssql', 'NAME': CONFIG["WAREHOUSE_DB_NAME"], 'USER': CONFIG["AZURE_CLIENT_ID"], # Azure AD user 'PASSWORD': CONFIG["AZURE_CLIENT_SECRET"], # Azure AD password 'HOST': CONFIG["WAREHOUSE_HOST"], # Server hostname 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', 'extra_params': 'Authentication=ActiveDirectoryServicePrincipal', 'host_is_server': True, }, } I looked for solutions and tried various different approaches (such as trying to use different authentication methods) or using DSN (connection itself is working fine). Nothing helps. When I use connection strings like this in usual python scripts everything works like a charm: server_name = CONFIG["WAREHOUSE_DB_NAME"] database_name = CONFIG["WAREHOUSE_DB_NAME"] client_secret = CONFIG["AZURE_CLIENT_SECRET"] tenant_id = CONFIG["AZURE_TENANT_ID"] client_id = CONFIG["AZURE_CLIENT_ID"] connection_string = f'Driver={{ODBC Driver 17 for SQL Server}};' \ f'Server={server_name};Database={database_name};' \ f'UID={client_id}@{tenant_id};PWD={client_secret};' \ 'Authentication=ActiveDirectoryServicePrincipal' params = urllib.parse.quote_plus(connection_string) engine = create_engine(f'mssql+pyodbc:///?odbc_connect={params}') I don't know if there is some parsing complications that I overlook. Help would be great. -
Why does redis report no subscribers to a channel after I subscribe to that channel without errors?
I am trying to send realtime feedback over websockets, and I'm doing that by sending data over redis from a rest-api server to a websocker server (both written in python/django). In the websocket server, I subscribe to a channel named "events" like this: redis_connection = redis.Redis( host=settings.REDIS_HOST, port=settings.REDIS_PORT, db=settings.REDIS_CACHE_DB, ) pubsub = redis_connection.pubsub() pubsub.subscribe(events=process_event) In the rest-api server, I publish data to the same redis channel like this: connection.publish("events", json.dumps({"user_email": user.email, "message": message})) While trying to figure out why no events ever made it to the "process_event" handler, I found that the publish method returns the number of subscribers to a channel, so I updated that line to this: count = connection.publish("events", json.dumps({"user_email": user.email, "message": message})) print(f"Published to events channel with {count} subscribers") The result is always 0, even after the subscription above. I went inside the redis-stack Docker container saw the following when I directly tried to query the subscriber count: redis-cli 127.0.0.1:6379> PUBSUB NUMSUB events "events" (integer) 0 127.0.0.1:6379> The output of the redis-stack itself doesn't seem to recognize any subscription or publication. -
Significant performance difference in django view vs. django shell within docker
I'm encountering a significant performance difference when running the same raw SQL query in my Django application. The query executes in about 0.5 seconds in the Django shell but takes around 2 seconds when called from a Django view. Both are running in an isolated Docker container environment. I've isolated the query execution into a function execute_query() used in both contexts, disabled DEBUG, and attempted to disable transactions with no improvement. Here's the function: def execute_query(): st = time.time() cursor = connection.cursor() cursor.execute(""" SELECT cars.created_at, cars.owner_id, cars.status, cars.color, cars.type, owners.source FROM cars INNER JOIN owners ON cars.owner_id = owners.id WHERE owners.membership_id = 'example_id' AND cars.created_at BETWEEN '2022-07-15 23:59:59' AND '2025-09-14 00:00:00' AND cars.is_active = False AND cars.description IS NOT NULL AND cars.type != 'electric' LIMIT 50000 """) rows = cursor.fetchall() end = time.time() print(f"Query took: {end - st} seconds") return end - st I am wondering what might be causing the performance differences mentioned above. -
Use JSON data in Django fields
Problem applying values from JSON config in HTML file using Django. Template error: In template C:\Users\at\pp\project\check\templates\check_list.html, error at line 52 Could not parse the remainder: '=check_status.get_status_by_id(check.status)' from 'status=check_status.get_status_by_id(check.status)' 42 : {% block content %} 43 : {% for check in checks %} 44 : 45 : 46 : <!-- Some data from check model --> 48 : 49 : 50 : 51 : <span class="check-status"> 52 : {{ status=check_status.get_status_by_id(check.status) }} 53 : {% with status %} 54 : {% if status %} 55 : <div class="check-status-svg" title="{{ check_status_config.items|get_item:check.status.id.title }}"> 56 : {{ status.svg|safe }} 57 : </div> 58 : {% else %} 59 : Статус не найден 60 : {% endif %} 61 : {% endwith %} 62 : </span> config.py This describes the basic functionality of the child classes of configs. import json class Config: def __init__(self): self.config = None self.config_file = "conf/" def get_element_by_id(self, element_id): for element in self.config.get("items", []): if element.get("id") == element_id: return element return None def load_config(self): try: with open(self.config_file, "r", encoding='utf-8') as f: self.config = json.load(f) print(f"'{self.config_file}' +") except FileNotFoundError: print(f"'{self.config_file}' ***") self.create_default_config() def get_config(self): return self.config def create_default_config(self): self.config = self.default_config with open(self.config_file, "w", encoding='utf-8') as f: json.dump(self.config, f, indent=4) check_status.py This describes … -
Display JavaScript Fetch for JsonResponse 2 Tables on HTML
I'm learning JavaScript right now and I'm trying to display data from 2 tables, which is profile and posts of the user profile. viewa.py @csrf_exempt @login_required def profile(request, user_id): try: user = User.objects.get(pk=user_id) prof = Profile.objects.get(user=user) posts = Post.objects.filter(author=user) except prof.DoesNotExist: return JsonResponse({"error": "Author not found."}, status=404) # Return profile contents if request.method == "GET": return JsonResponse({ "prof": prof.serialize(), "posts": [post.serialize() for post in posts] }, safe=False) # Update follower elif request.method == "PUT": data = json.loads(request.body) if data.get("follower") is not None: prof.follower = data["follower"] prof.save() return HttpResponse(status=204) # Profile must be via GET or PUT else: return JsonResponse({ "error": "GET or PUT request required." }, status=400) urls.py path("profile/int:user_id", views.profile, name="profile") Here is the API view API I tried to display the data on index.html using JavaScript. index.js function load_profile(author_id) { // Load posts list fetch(`/profile/${author_id}`) .then(response => response.json()) .then(prof => { // Print profile console.log(prof); const content_profile = document.createElement('div'); content_profile.className = "content_profile"; const user = document.createElement('p'); user.innerHTML = `<h3>${prof.prof.user}</h3>`; const followers = document.createElement('p'); followers.innerHTML = `Follower: ${prof.prof.followers}`; const following = document.createElement('p'); following.innerHTML = `Following: ${prof.prof.following}`; const a = document.createElement('a'); a.className = "btn btn-primary"; a.innerHTML = "Follow"; content_profile.append(user, followers, following, a); document.querySelector('#profile').append(content_profile); }) .then(datas => { // Print datas console.log(datas); … -
FCM-Django Push Notification Stopped Working After Recent Changes
I am using the FCM-Django module "fcm-django==1.0.14" to send push notifications to a mobile app built with Flutter. Previously, I used this code, and it worked fine. def sendnotificationall(message, title, regis_id=None): try: if regis_id is None: devices = FCMDevice.objects.all() else: devices = regis_id dev = devices.send_message(Msg(notification=Notifi(title=title, body=message))) return "success" except: return "no device found" However, when I checked it again recently, the code stopped working. Interestingly, when I sent notifications to individual instances, it started working correctly. def sendnotificationall(message, title, regis_id=None): try: if regis_id is None: devices = FCMDevice.objects.all() else: devices = regis_id for device in devices: device.send_message(Msg(notification=Notifi(title=title, body=message))) return "success" except: return "no device found" Can anyone explain what changes have been made to FCM-Django, or am I making a mistake somewhere? -
How in Django panel redirect button don't work
I have this code in admin.py @admin.register(BaseFundElement) class BaseFundElementAdmin(admin.ModelAdmin): list_display = ['registration_date', 'inventory_number', 'author', 'title', 'year', 'invoice_number', 'publication_status'] readonly_fields = ['id', 'registration_date', 'inventory_number', 'price', 'author', 'title', 'year', 'price_with_vat', 'vat_amount', 'invoice_number', 'invoice_date', 'publication_status'] fields = ['id', 'registration_date', 'inventory_number', 'author', 'title', 'year', 'invoice_number', 'publication_status'] labels = { 'currency': 'Издание' } change_form_template = "klib/create_act.html" def create_act(self, request, object_id): base_fund_element = self.get_object(request, object_id) if request.method == "POST": write_off_act = WriteOffAct.objects.create() return redirect(reverse('admin:klib_writeoffact_change', args=[write_off_act.pk])) return self.change_view(request, object_id) def get_urls(self): urls = super().get_urls() custom_urls = [ path('create_act/<int:object_id>/', self.admin_site.admin_view(self.create_act), name='create_act'), ] return custom_urls + urls def get_queryset(self, request): qs = super().get_queryset(request) if 'publication_status__exact' in request.GET: return qs return BaseFundElement.active.all() list_filter = ['publication_status'] actions = ['mark_as_written_off'] def author(self, obj: BaseFundElement): return obj.arrival.order_edition.edition.author if obj.arrival.order_edition.edition.author else '-' author.short_description = _('Author') def title(self, obj: BaseFundElement): return obj.arrival.order_edition.edition.title if obj.arrival.order_edition.edition.title else '-' title.short_description = _('Edition title') def year(self, obj: BaseFundElement): return obj.arrival.order_edition.edition.year if obj.arrival.order_edition.edition.year else '-' year.short_description = _('Year') def has_add_permission(self, request, obj=None): return False def changeform_view(self, request, object_id=None, form_url='', extra_context=None): extra_context = extra_context or {} extra_context['show_save_and_continue'] = False extra_context['show_save'] = False return super(BaseFundElementAdmin, self).changeform_view(request, object_id, extra_context=extra_context) def has_edit_permission(self, request, obj=None): return False def edition(self, obj: BaseFundElement): return obj.arrival if obj.arrival else '' @transaction.atomic def save_model(self, request, obj, form, change): if … -
Django table reduce text when larger then cell size
I have home.html in my Django app, with the table in which if display all my posts: {% for post in posts %} <tr> <td>{% pagination_reverse_numbering paginator page_obj forloop.counter0 %}</td> <td style="width:10%"><a class="mr-2" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></td> <td><a class="mr-2" href="{% url 'user-posts' post.author.id %}">{{ post.author.first_name }} {{ post.author.last_name }}</a></td> <td>{{ post.date_posted|date:"j.n.Y" }}</td> </tr> {% endfor %} Problem is, sometimes a single text, like post name is large and then each post is multiple rows. I would like to keep the size of each cell, just when text for preview would be larger then original/default cell size in table, just to skip rest of text. For example, instead of 'Very long long post title' it should be 'Very lon.....' to preserve cell size. I would like to implement this in html or js. I tried: <td style="width:10%"> but this only limits cell width, then text splits in multiple rows. -
Nginx serving media files only on port 80
I have searched here and other resources for the same issue. They all did not help. Please before closing this based on the fact that it is a duplicate, ask for more details and I will try to provide. First of all, I am on Windows. I have created my django app, and configured my Nginx. I then ran the django app via: uvicorn monitoring.asgi:application --host 0.0.0.0 --port 9001 --reload I have created inbound rules on the server for port 9001, and the app runs smoothly. All the static files are being served via whitenoise library. All the Media files which users upload to the app will not be served. This includes images for some products as well as some other files, PDFs, etc. I can access the files directly in the following way in the browser (notice the missing port number which will translate to port 80). This means that Nginx is performing its duty normally. http://10.0.60.26/media/xxxx/xxxxxx.png But not in the following way: http://10.0.60.26:9001/media/xxxx/xxxxx.png I have no clue why this is happening that instead of directly fetching the media files via Nginx, the app is trying to fetch them from uvicorn. Is there a way to make django to …