Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
In django template cannot get data from values_list() for select options dropdown
Im django noob here so I would like to get your support. Thank you so much in advanced. 1. My model.py: class Province(models.Model): province_name = models.CharField() class Employee(models.Model): first_name = models.CharField() province = models.ForeignKey(Province, on_delete=models.CASCADE,) 2. My filters.py (django-filter) from django_filters import FilterSet, filters from .models import ( Employee, Province, ) class EmployeeFilter(FilterSet): province_name_multi_select = ( filters.ModelMultipleChoiceFilter( field_name="province_id", queryset=Province.objects.values_list("id", "province_name"), ) ) class Meta: model = Employee fields = [ "id", "first_name", "province", ] 3. My views.py class EmployeeListView(FilterView): model = Employee queryset = Employee.objects.select_related( "province", ) form_class = EmployeeForm strict = False context_object_name = "employees_list" filterset_class = EmployeeFilter ** 4. My employee_filter.html** <select class="form-select" name="province_name_multi_select" id="multiple-select-field" multiple\> {% for element in filter.form.province_name_multi_select %} {{ element.tag }} \<= **Problem happened here** {% endfor %} </select\> ** 5. My problem** Above {{ element.tag }} produced <option value="[1], 'abc province']" </option> But what I want it to produce is, you can guess that <option value="1" </option> Once again, thank you. convert output of values_list (tuple?) to list to render in django html template's select dropdown -
how to delete old class file referenced in django migration
class Migration(migrations.Migration): dependencies = [ ("buckets", "0001_auto_20230420_2018"), ] operations = [ # Delete existing tables migrations.RunSQL( sql=buckets.my_models.models.RefObjModel.get_create_table_sql(), reverse_sql=migrations.RunSQL.noop, ), above is sample code how we have migration files, there are many migration where this kind of code is written. Question: we have to remove RefObjModel, how we should be doing it, what is preferred approach. If we are deleting the class file/code application run is failing as it tries to run all the migration file and unable to find referenced class. If we delete the references from all the migration files manually, does it create any problem in production deployment/application -
How to handle currency values properly?
I have a system where all the transaction amount are being stored in integer(cent). This has been working fine so far, with over 20 million transactions already recorded. However, I’ve recently encountered a use case where the equivalent integer value becomes zero after converting to cents, leading to issues with small amounts # Models class Wallet(models.Model): balance = models.IntegerField() class WalletTransaction(models.Model): wallet = models.ForeignKey(Wallet, on_delete=models.CASCADE) amount = models.IntegerField() # Stored in cents transaction_type = models.CharField(max_length=50) # Updating wallet balance and creating transaction cost_price = 0.0025 cost_price_in_cents = cost_price * 100 # Converts to 0.25 cents wallet = Wallet.objects.get(id=1) wallet.balance -= cost_price_in_cents wallet.save() WalletTransaction.objects.create(wallet=wallet, amount=cost_price_in_cents) Here balance gets deducted by 0.25 but in wallet transaction history it is 0. -
i can not see the items of a cart in the checkout page of a simple ecommerce website using django
i can not see the items of a cart in the checkout page of a simple ecommerce website using django, the added products displays on the cart page but not in the checkout page,also when i want to place order in the checkout page nothing adds to order page of the django admin panel, the cart item of admin panel shows that the product is added but when i place the order no order comes in the order section of admin panel,here in below you can see the project codes: models.py: from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.db import models # Create your models here. class Product(models.Model): name = models.CharField(max_length=100) price = models.FloatField() stock = models.IntegerField() short_description = models.TextField() long_description = models.TextField() image = models.ImageField() production_date = models.DateField() product_id = models.IntegerField() def __str__(self): return self.name #user class UserManager(BaseUserManager): def create_user(self, phone_number, password=None): if not phone_number: raise ValueError("Users must have a phone number") user = self.model(phone_number=phone_number) user.set_password(password) # Set password if needed user.save(using=self._db) return user def create_superuser(self, phone_number, password=None): user = self.create_user(phone_number, password) user.is_admin = True user.is_staff = True user.save(using=self._db) return user class User(AbstractBaseUser): phone_number = models.CharField(max_length=15, unique=True) USERNAME_FIELD = 'phone_number' objects = UserManager() is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) def … -
Overriding Save but database is not updated
I have a model, containing a save overide, that uses a function to set whether a sync is required based on a comparison of dates. The save is called by update_or_create which is in turn called by a management command For the purposes of debugging this issue sync_required is set to True regardless. class Site(models.Model): # LastEditDate & LastEditTime LastEditDate = models.DateField(blank=True, null=True) LastEditTime = models.TimeField(blank=True, null=True) ... # System Specific date_modified = models.DateTimeField(auto_now=True, null=True) last_synced = models.DateTimeField(blank=True, null=True) sync_required = models.BooleanField(blank=False, null=True, default=False) # Function to calculate if sync required. def is_sync_required(self): ... return True def save(self, *args, **kwargs): self.sync_required = self.is_sync_required() logger.info( f"Site/Save: LED:{self.LastEditDate}, LET:{self.LastEditTime}, DM:{self.date_modified}, LS:{self.last_synced} = SR:{self.sync_required}") super(Site, self).save(*args, **kwargs) In full operation the method is producing the correct output: A001 Site/is_sync_required/Return for A001= True with MinutesSince>=0 84659.0 Site/Save: LED:2024-02-29, LET:09:06:04.174000, DM:2024-09-27 08:19:27.430154+00:00, LS:2024-01-01 14:06:28+00:00 = SR:True A002 Site/is_sync_required/Return for A002= False with MinutesSince<0 -25449.0 Site/Save: LED:2024-08-14, LET:16:51:17.732000, DM:2024-09-27 08:20:33.720193+00:00, LS:2024-09-01 08:00:00+00:00 = SR:False A003 Site/is_sync_required/Return for A003= True with last_synced_none None Site/Save: LED:2024-09-02, LET:08:25:50.232000, DM:2024-09-27 08:18:35.456365+00:00, LS:None = SR:True A004 Site/is_sync_required/Return for A004= True with MinutesSince>=0 51517.0 Site/Save: LED:2024-08-06, LET:09:43:40.257000, DM:2024-09-27 08:21:40.917783+00:00, LS:2024-07-01 14:06:28+00:00 = SR:True However, the result of sync_required is not being saved … -
How to test the websocket connection in django channels
I need to test the success of the websocket connection. When connecting, the query_string parameter is checked. If it is transmitted, the connection is allowed. If not, the connection is closed. At the moment, the test fails with an error: Task was destroyed but it is pending! task: <Task pending name='Task-2' coro=<ProtocolTypeRouter.__call__() running at /usr/local/lib/python3.10/site-packages/channels/routing.py:62> wait_for=<Future cancelled>> Exception ignored in: <coroutine object ProtocolTypeRouter.__call__ at 0xffff845ac3c0> Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/channels/routing.py", line 62, in __call__ File "/usr/local/lib/python3.10/site-packages/channels/security/websocket.py", line 41, in __call__ File "/usr/local/lib/python3.10/site-packages/channels/consumer.py", line 58, in __call__ File "/usr/local/lib/python3.10/site-packages/channels/utils.py", line 55, in await_many_dispatch File "/usr/local/lib/python3.10/asyncio/base_events.py", line 753, in call_soon File "/usr/local/lib/python3.10/asyncio/base_events.py", line 515, in _check_closed RuntimeError: Event loop is closed Task was destroyed but it is pending! task: <Task pending name='Task-5' coro=<Queue.get() running at /usr/local/lib/python3.10/asyncio/queues.py:159> wait_for=<Future cancelled>> Task was destroyed but it is pending! task: <Task pending name='Task-4' coro=<InMemoryChannelLayer.receive() running at /usr/local/lib/python3.10/site-packages/channels/layers.py:249> wait_for=<Future pending cb=[Task.task_wakeup()]>> Exception ignored in: <coroutine object InMemoryChannelLayer.receive at 0xffff845ac7b0> Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/channels/layers.py", line 249, in receive File "/usr/local/lib/python3.10/asyncio/queues.py", line 161, in get File "/usr/local/lib/python3.10/asyncio/base_events.py", line 753, in call_soon File "/usr/local/lib/python3.10/asyncio/base_events.py", line 515, in _check_closed RuntimeError: Event loop is closed My application configuration: settings.py ASGI_APPLICATION = "hs_cubic.asgi.application" ASGI_MAX_WORKER_RUNTIME = 60 * 10 … -
Django StreamingHttpResponse with asgi setup warning
Hi I am using following class based view to define a endpoint to return large Django Queryset as either Json or CSV using Streaming Response class DataView(viewsets.ReadOnlyModelViewSet): permission_classes = [IsAuthenticated, StrictDjangoModelPermissions] authentication_classes = [JWTAuthentication] queryset = Data.objects.all() serializer_class = DataSerializer pagination_class = LimitOffsetPagination filter_backends = (DjangoFilterBackend,SearchFilter) filterset_class = DataFilter search_fields = ['^ts'] def generate_data(self, start, end, needCSV, points): cols = ['ts', 'topic_id', 'value_string'] if len(points) > 0: data = Data.objects.filter(ts__range=(start, end), topic_id__in=points) else: data = Data.objects.filter(ts__range=(start, end)) dis_dict = {point.id: point.navPoint for point in Points.objects.filter(id__in=points)} if needCSV: yield ','.join(cols + ['dis']) + '\n' for row in data: dis_value = dis_dict.get(row.topic_id, '') yield ','.join(map(str, [getattr(row, col) for col in cols] + [dis_value])) + '\n' else: yield '[' for i, row in enumerate(data): if i > 0: yield ',' dis_value = dis_dict.get(row.topic_id, '') row_dict = {col: str(getattr(row, col)) for col in cols} row_dict['dis'] = dis_value yield json.dumps(row_dict) yield ']' def list(self, request, *args, **kwargs): try: csv = request.GET.get('csv', False) csv = csv and csv.lower() == 'true' points = request.GET.getlist('point', []) start = request.GET['start'] end = request.GET['end'] contentType = 'text/csv' if csv else 'application/json' fileName = 'data.csv' if csv else 'data.json' response = StreamingHttpResponse(self.generate_data(start, end, csv, points), content_type=contentType) response['Content-Disposition'] = f'attachment; filename="{fileName}"' return … -
Django CustomUser Model Causes Lazy Reference Errors During Migration
I'm working on a Django project where I have defined a CustomUser model in an app called authentication. I've correctly set the AUTH_USER_MODEL to reference this model, but when I try to run migrations, I get the following errors: ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'authentication.customuser', but app 'authentication' doesn't provide model 'customuser'. The field authentication.Device.user was declared with a lazy reference to 'authentication.customuser', but app 'authentication' doesn't provide model 'customuser'. The field authentication.MoodReview.user was declared with a lazy reference to 'authentication.customuser', but app 'authentication' doesn't provide model 'customuser'. The field authentication.PasswordResetCode.user was declared with a lazy reference to 'authentication.customuser', but app 'authentication' doesn't provide model 'customuser'. The field authtoken.Token.user was declared with a lazy reference to 'authentication.customuser', but app 'authentication' doesn't provide model 'customuser'. # authentication/models.py from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.db import models from django.utils import timezone class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError("The Email field must be set") email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser …