Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Font awesome preload warning when Django app deployed to Heroku, but not on dev server
It's my first day using heroku to deploy my Django app. When I deploy my Django app on Heroku, the chrome inspector gives this warning: The resource https://ka-f.fontawesome.com/releases/v6.6.0/webfonts/free-fa-solid-900.woff2 was preloaded using link preload but not used within a few seconds from the window's load event. Please make sure it has an appropriate as value and it is preloaded intentionally. When I click the warning link it shows the first line of my index page html, which is blank. I don't get this warning when running in my development server and setting the Django project Debug mode has no effect. I have deleted every mention of fontawesome in my project including removing the fontawesome reference from the head of my base.html and removing it from my installed apps etc., but I still receive this warning. I used search to double check there were no font awesome references. Have tried to look up solutions for several hours today and am stumped. My base.html page looks like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Dotstory</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="shortcut icon" type="image/x-icon" href="{% static 'storymode/images/favicon.png' %}"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> </head> and my index looks like … -
Django: GET /getMessages// HTTP/1.1" 404 2987
I am following a Django tutorial video on how to create a simple chat room. When I want to create a new room, a pop-up alert says "An error occurred". Couldn't figure out what went wrong. Errors: home.html room.html urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('<str:room>/', views.room, name='room'), path('checkview', views.checkview, name='checkview') > ] views.py from django.shortcuts import render, redirect from chat.models import Room, Message # Create your views here. def home(request): return render(request, 'home.html') def room(request, room): return render(request, 'room.html') def checkview(request): room = request.POST['room_name'] username = request.POST['username'] if Room.objects.filter(name=room).exists(): return redirect('/'+room+'/?username='+username) else: new_room = Room.objects.create(name=room) new_room.save() return redirect('/'+room+'/?username='+username) models.py from django.db import models from datetime import datetime # Create your models here. class Room(models.Model): name = models.CharField(max_length=1000) class Message(models.Model): value = models.CharField(max_length=1000000) date = models.DateTimeField(default=datetime.now, blank=True) user = models.CharField(max_length=1000000) room = models.CharField(max_length=1000000) -
How to Link Multiple Social Accounts to a Single User in Django Allauth with a Custom User and Company Model?
I'm working on a Django project where I want to authenticate users using multiple social accounts and link them to a single account in my custom models. I'm using django-allauth for social authentication, and I have a custom User model along with a Company model. The Company model has a ForeignKey to the User model. The goal: I want a user to be able to log in using multiple social accounts (e.g., Google, Facebook) but all these accounts should link to the same user in my Company model. Essentially, the user should be able to authenticate through different providers but still map to a single User account in my system. My setup: Django version: 4.x django-allauth version: 0.44.x I have a custom User model. Company model has a ForeignKey to the User model. What I need help with: How do I configure django-allauth to allow a single user to authenticate via multiple social accounts and link them to the same User record? How can I ensure that all authenticated social accounts point to the same user, while still linking them to the Company model? 3)Are there any specific settings in django-allauth or middleware changes needed to make this work? I’ve … -
How to get more info on what field differences where found by manage makemigrations
Occasionally when running manage makemigrations in my Django project, I end up with an unexpected migrations.AlterField() entry in my migrations file. I am aware that these result from Django seeing differences between that field's definition in my model and the field's definition after applying all migrations. Is there any way to find out which difference it sees? I can look at my fields in the models and use _meta to get field settings I didn't explicitly specify, but is there any way to get information on what the field looks like on the migrations side of things? Compare the target vs actual state, so to speak? The info I am looking for is, if there is for instance an AlterField() on an IntegerField, that's been picked up because the max value changed, or it has a different verbose_name. For now I just manually dig through the migration files for mentions of that respective field, but I am working with a legacy project that has a LOT of them. So I am wondering if anyone ever ran into the same problem and found a better solution. -
The fixtures are not loaded and says they are not found, although they are there
In django I have folder with fixtures\goods\categories.js and fixtures\goods\products.js. I installed postgreSQL and I have tables categories and products. But when I write "python manage.py loaddata fixtures/goods/categories.json" it appears to me: "CommandError: No fixture named 'categories' found." How do I load fixtures? This may be due to the fact that I may have previously loaded everything into something other than the environment. That is, I did python manage.py dumpdata not in the environment... -
RuntimeError: populate() isn't reentrant how to debug that?
[Wed Sep 11 06:36:45.997990 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] Traceback (most recent call last): [Wed Sep 11 06:36:45.998052 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] File "/home/newsroom.dinsordesign.com/wsgi_web/wsgi_web/wsgi.py", line 22, in [Wed Sep 11 06:36:45.998063 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] application = get_wsgi_application() [Wed Sep 11 06:36:45.998075 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] File "/home/newsroom.dinsordesign.com/venv/lib64/python3.9/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Wed Sep 11 06:36:45.998084 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] django.setup(set_prefix=False) [Wed Sep 11 06:36:45.998095 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] File "/home/newsroom.dinsordesign.com/venv/lib64/python3.9/site-packages/django/init.py", line 24, in setup [Wed Sep 11 06:36:45.998103 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] apps.populate(settings.INSTALLED_APPS) [Wed Sep 11 06:36:45.998114 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] File "/home/newsroom.dinsordesign.com/venv/lib64/python3.9/site-packages/django/apps/registry.py", line 83, in populate [Wed Sep 11 06:36:45.998123 2024] [wsgi:error] [pid 1043:tid 1147] [remote 49.228.84.26:9457] raise RuntimeError("populate() isn't reentrant") i need some help what happend on my project i work on django i want to know what happend and how to fix it -
Django transaction is splitted, even if I use transaction.atomic()
with transaction.atomic(): A.objects.filter( a=a, b=b, c=c, d__range=[start_date, end_date], ).delete() A.objects.bulk_create( [ A( a=a, b=b, c=c, d=d, e=e, f=f, g=g, ) for obj in objs ] ) Query is like BEGIN BEGIN DELETE FROM ... COMMIT BEGIN INSERT INTO ... COMMIT What I want to do BEGIN DELETE FROM ... INSERT INTO COMMIT -
Django DRF error DLL Load Failed while importing _rust in Python 3.11.3 venv in Windows Server 2022 with cryptography-43.0.1-cp39-abi3-win_amd64.whl
My code is working in local environment of windows10 with venv on Python 3.10.11. However, on deploying in Windows Server 2022 with Apache2 webserver with venv on Python 3.11.3 getting following error. I have trying upgrading, installing binary. Till now issue is not resolved. Can anyone help in getting the issue resolved? from cryptography.hazmat.primitives.asymmetric import padding\r File "C:\\cbsesb\\cbsenv\\Lib\\site-packages\\cryptography\\hazmat\\primitives\\asymmetric\\padding.py", line 9, in <module>\r from cryptography.hazmat.primitives import hashes\r File "C:\\cbsesb\\cbsenv\\Lib\\site-packages\\cryptography\\hazmat\\primitives\\hashes.py", line 9, in <module>\r from cryptography.hazmat.bindings._rust import openssl as rust_openssl\r ImportError: DLL load failed while importing _rust: The specified module could not be found.\r Package Version asgiref 3.7.1 certifi 2023.7.22 cffi 1.17.1 charset-normalizer 3.3.2 cryptography 43.0.1 cx-Oracle 8.3.0 defusedxml 0.7.1 dicttoxml 1.7.16 Django 4.2.1 djangorestframework 3.14.0 djangorestframework-xml 2.0.0 idna 3.6 ldap3 2.9.1 lxml 4.9.3 mod-wsgi 4.9.4 pip 24.2 psycopg2 2.9.6 pyasn1 0.6.0 pycparser 2.22 pycryptodome 3.18.0 pyOpenSSL 24.2.1 pytz 2023.3 requests 2.31.0 setuptools 74.1.2 signxml 3.2.1 soupsieve 2.5 sqlparse 0.4.4 typing_extensions 4.6.1 tzdata 2023.3 urllib3 2.2.0 xmltodict 0.12.0 Tried to update the setup tools but did not worked python -m pip install --upgrade pip setuptools Tried to downgrade the Python to 3.10 but did not worked. installing Rust doesn't work. Tried installing binary for cryptography but did not worked. python -m pip … -
Django Microsoft SSO Integration State Mismatch (Django + Azure App Service)
I’m integrating Microsoft SSO into my Django app, and I’m encountering a "State Mismatch" error during the login process. This error occurs when the state parameter, which is used to prevent cross-site request forgery (CSRF) attacks, doesn’t match the expected value. What’s Happening: During the login process, my Django app generates a state parameter and stores it in the user’s session. When the user is redirected back to my app from Microsoft after authentication, the state parameter returned by Microsoft should match the one stored in the session. However, in my case, the two values don’t match, resulting in a State Mismatch Error. ERROR:django.security.SSOLogin: State mismatch during Microsoft SSO login. Expected state: XXXXXXXXXXXXXXXXXXXXXXXXXX Returned state: YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY Session ID: ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ Expected state: The state value generated by my app and stored in the session. Returned state: The state value returned by Microsoft after the user completes authentication. Session ID: The session key for the user during the login attempt. Django & Azure Configuration: Django version: 5.0.6 Python version: 3.12 SSO Integration Package: django-microsoft-sso Cache backend: LocMemCache (planning to switch to Redis) Azure App Service: Hosted with App Service Plan for deployment. Time Zone: Central Time (US & Canada) on local development … -
Error: 'Did you remember to import the module containing this task?'
I have this project https://github.com/LucasLeone/LaPanaSystem. I created a task for check the sales for change the state but doesn't work. The error: lapanasystem_local_celeryworker | [2024-09-10 23:47:20,238: ERROR/SpawnProcess-8] Received unregistered task of type 'check_sales_for_delivery'. lapanasystem_local_celeryworker | The message has been ignored and discarded. lapanasystem_local_celeryworker | lapanasystem_local_celeryworker | Did you remember to import the module containing this task? lapanasystem_local_celeryworker | Or maybe you're using relative imports? lapanasystem_local_celeryworker | lapanasystem_local_celeryworker | Please see lapanasystem_local_celeryworker | https://docs.celeryq.dev/en/latest/internals/protocol.html lapanasystem_local_celeryworker | for more information. lapanasystem_local_celeryworker | lapanasystem_local_celeryworker | The full contents of the message body was: lapanasystem_local_celeryworker | b'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b) lapanasystem_local_celeryworker | lapanasystem_local_celeryworker | The full contents of the message headers: lapanasystem_local_celeryworker | {'lang': 'py', 'task': 'check_sales_for_delivery', 'id': '5cdd77f4-6b48-4274-8edb-0926ac3419e0', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '5cdd77f4-6b48-4274-8edb-0926ac3419e0', 'parent_id': None, 'argsrepr': '()', 'kwargsrepr': '{}', 'origin': 'gen18@ace8c29fe6f1', 'ignore_result': False, 'replaced_task_nesting': 0, 'stamped_headers': None, 'stamps': {}} lapanasystem_local_celeryworker | lapanasystem_local_celeryworker | The delivery info for this task is: lapanasystem_local_celeryworker | {'exchange': '', 'routing_key': 'celery'} lapanasystem_local_celeryworker | Traceback (most recent call last): lapanasystem_local_celeryworker | File "/usr/local/lib/python3.12/site-packages/celery/worker/consumer/consumer.py", line 659, in on_task_received lapanasystem_local_celeryworker | strategy = strategies[type_] lapanasystem_local_celeryworker | ~~~~~~~~~~^^^^^^^ lapanasystem_local_celeryworker | KeyError: 'check_sales_for_delivery' I … -
How to set output dir dynamically to django app in TypeScript?
I have this webpack.config.js right now: const path = require('path'); const glob = require('glob'); const { log } = require('console'); const apps = ['transactions']; // List of apps with TypeScript files const getEntryObject = () => { const entries = {}; apps.forEach((app) => { const tsPath = path.join(__dirname, `dinotax/${app}/static/${app}/src/ts/**/*.ts`); glob.sync(tsPath).forEach((curPath) => { const name = path.basename(curPath, ".ts"); entries[name] = curPath; }); }) return entries; }; module.exports = { entry: getEntryObject(), output: { filename: '[name].js', // Output filename based on entry key path: path.resolve(__dirname, 'static'), }, resolve: { extensions: ['.ts'], }, module: { rules: [ { test: /\.css$/i, use: [ 'style-loader', 'css-loader' ] }, { test: /\.(ts|tsx)$/, exclude: [/node_modules/, /\.d\.ts$/], use: 'ts-loader', }, { test: /\.d\.ts$/, // Ensure .d.ts files are ignored use: 'ignore-loader', } ] }, }; The entry points would lock like this: --------------------- { fileTree: 'C:/repos/App/app/transactions/static/transactions/src/ts/fileTree/fileTree.ts', generalHelper: 'C:/repos/App/app/transactions/static/transactions/src/ts/helper/generalHelper.ts', matching: 'C:/repos/Dinotax/dinotax/transactions/static/transactions/src/ts/matching/matching.ts', overview: 'C:/repos/App/app/transactions/static/transactions/src/ts/overview/overview.ts', 'globals.d': 'C:/repos/App/app/transactions/static/transactions/src/ts/types/globals.d.ts', 'index.d': 'C:/repos/App/app/transactions/static/transactions/src/ts/types/index.d.ts' } --------------------- Which is what I want. The files are compiled, but now I struggle to set the output the same way I collect the files. I.e. files should be stored in the corresponding apps instead of the root static folder. An example would be: 'C:/repos/App/app/transactions/static/transactions/src/js/overview.d.js'. The Node Modules and webpack.config / … -
Django collecstatic requires STATIC_ROOT but setting STATIC_ROOT blocks upload to S3
So I use S3 static storage in combination with Django to serve static files for a Zappa deploy. This all worked quite well for a long time until I recently upgraded to a new Django version. Python 3.12.3 Django 5.1.1 It used to be, I could use: python manage.py collectstatic To push my static files over to my S3 bucket. But, currently, that fails with this error: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. However, If I set a STATIC_ROOT, then instead of pushing to S3, it collects the static files locally. You have requested to collect static files at the destination location as specified in your settings: /-local storage-/static This is my settings.py: STATIC_URL = '/static/' # STATIC_ROOT = os.path.join(BASE_DIR, "static") STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, "static") ] YOUR_S3_BUCKET = "static-bucket" STATICFILES_STORAGE = "django_s3_storage.storage.StaticS3Storage" AWS_S3_BUCKET_NAME_STATIC = YOUR_S3_BUCKET # These next two lines will serve the static files directly # from the s3 bucket AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % YOUR_S3_BUCKET STATIC_URL = "https://%s/" % AWS_S3_CUSTOM_DOMAIN The credentials and all are also in settings.py. It seems I a missing something, I need STATIC_ROOT to run collectstatic, but having STATIC_ROOT makes static collection … -
Electron Forge App: Issues with Executable Fiel Location in Release Build
I have an Electron Forge application designed to launch a Django server (on Windows). The Django server is compiled into an executable file using PyInstaller. The Electron Forge application invokes this executable file via the spawn command. When I build the Electron Forge application using npm run make, the application functions as expected. However, when using npm run release (which generates a setup file), the executable file cannot be located. Additionally, it does not exist in the resource folder. I get the error when starting the server: Error: spawn C:\Users\****\AppData\Local\Programs\****\resources\django-server\server.exe ENOENT My forge.config.ts file: Const config: ForgeConfig = { packagerConfig: { asar:true, icon "./src/assets/Logo/icon" extraResources: ['./django-server/server.exe'] } makers: [ new MakerSquirrel({noMsi: false}), new MakerZIP({}) ], .... The server.exe file is started inside the index.ts file by using spawn: exePath = path.join(process.resourcesPath, 'django-server', 'server.exe'); const child = spawn(exePath, []); Why is the server.exe file not being copied to the resource folder when running npm run release ? -
Change DateField Input format on django admin edit page
I have a Django project where users can submit requests and then our admin's can view these requests through Django's admin page. I'd like the TimeField on the change page to be in a different format when one our our admins selects an object to change. The image below show what a list of objects looks like through the list display page. The Start time is in a 12 hour format using AM/PM. Once the user clicks an object to change though the form expects the the Start Time to be in 24 hour format as shown below. I'd like to change the admin form to match the list display format if possible. If I need to provide any other information or code example please let me know. Thank you. -
Get Error "not enough values to unpack (expected 2, got 0)" when using Django EAV 2
from django.contrib import admin from .models import Product from eav.forms import BaseDynamicEntityForm from eav.admin import BaseEntityAdmin Register your models here. class ProductAdminForm(BaseDynamicEntityForm): model = Product class ProductAdmin(BaseEntityAdmin): form = ProductAdminForm admin.site.register(Product, ProductAdmin) Get error: Request Method: GET Request URL: http: //127.0.0.1:8000/admin/shop/product/add/ Django Version: 5.1.1 Exception Type: ValueError Exception Value: not enough values to unpack (expected 2, got 0) Exception Location: C:\Users\iskander\Desktop\shop\venv\Lib\site-packages\django\forms\widgets.py, line 772, in _choice_has_empty_value Raised during: django.contrib.admin.options.add_view Error during template rendering In template C:\Users\iskander\Desktop\shop\venv\Lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 25 <div> 16 {% if not line.fields|length == 1 and not field.is_readonly %}{{ field.errors }}{% endif %} 17 <div class="flex-container{% if not line.fields|length == 1 %} fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}{% endif %}{% if field.is_checkbox %} checkbox-row{% endif %}"> 18 {% if field.is_checkbox %} 19 {{ field.field }}{{ field.label_tag }} 20 {% else %} 21 {{ field.label_tag }} 22 {% if field.is_readonly %} 23 <div class="readonly">{{ field.contents }}</div> 24 {% else %} **25 {{ field.field }}** 26 {% endif %} 27 {% endif %} 28 </div> 29 {% if field.field.help_text %} 30 <div class="help"{% if field.field.id_for_label %} id="{{ field.field.id_for_label }}_helptext"{% endif %}> 31 … -
Sort version number of format 1.1.1 in Django
I have a Django model with a release_version char field that stores version information in the format 1.1.1 (e.g., 1.2.3). I need to sort a queryset based on this version field so that versions are ordered correctly according to their major, minor, and patch numbers. class Release(BaseModel): file_name = models.CharField(max_length=255) release_version = models.CharField(max_length=16) Using the default order_by gives the result in lexicographic order and it sorts 1.10.0 before 1.2.0 when sorting ascending. The solution seems to be that I can annotate the major, minor and patch version and then sort based on these three fields. The issue in this is that I am not able to figure out how to separate this version into major, minor and patch numbers. -
Is it possible to pause celery tasks during execution
I have an app that does transcription. I want that if the user tries to reload they are alerted that reloading will stop their task from completing. I tried to use it with unload but it didn't work most of the time and I know that it is inconsistent. I would like to pause the task if the user tries to reload. They will get the browser warning alert and if they decide that they still want to reload the task will be terminated. The idea I have is to trigger a beforeunload which will give them a warning and trigger the pausing of the celery task. I have a polling function on the frontend set up using JS that polls if the task is still running every 5 seconds. If the user reloads this polling function will stop running and so the backend will stop being polled which will trigger the celery task termination. Otherwise, the function will receive the poll if the user cancels or hasn't reloaded and the task is unpaused. Here is my polling function: function pollTaskStatus(taskId) { currentTaskId = taskId; console.log(currentTaskId) pollInterval = setInterval(() => { const xhr = new XMLHttpRequest(); xhr.onload = function() { … -
Djnago coroutine to query data from DB in batches and yield as an iterable
I am using Django 4.2 with python3.8. I have a Mysql8 DB containing a Model as class A(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=522) class B(models.Model): name = models.CharField(max_length=255, unique=True) a = models.ManyToManyField(A) i want to create a function which when provided id for A should be able to query all instances of B for A but because B can be very large like millions of rows. want to iterate over it in batches of 1000 without loading it in memory. Is it possible to do so? I wanted to use co-routines as i think i can use it to build a iterator like object. any other alternatives to make sure it is performant enough so i can parallelize it over for 100+ organizations. i would like a code snippets if possible so i can understand this better context: This is a management command that needs to be run as cronjob everyday so i need to run fast -
Can't make dynamic page changes
I want to make a dynamic page, but when I make a request the page just refreshes, although it should return an alert when no data is entered (I have not entered any). views.py def adding(request): return render(request, 'matrix_app/adding_matrix.html') create_matrix.js function create_matrix(){ let rows1 = document.getElementById("rows_1_matrix").textContent; let columns1 = document.getElementById("columns_1_matrix").textContent; let rows2 = document.getElementById("rows_2_matrix").textContent; let columns2 = document.getElementById("columns_2_matrix").textContent; nums = [rows1, rows2, columns1, columns2]; for(let i = 0; i < 4; i++){ if (nums[i] === false || nums[i] === '0') { return alert("All fields are ruqired"); } } } adding_matrix.html % extends 'base.html' %} {% load static %} {% block content %} <script src="{% static 'js/create_matrix.js' %}"></script> <form onsubmit="create_matrix()" id="matrix" method="post"> {% csrf_token %} <div> <label>text</label> <input type="number" id="rows_1_matrix"/> </div> <div> <label>text</label> <input type="number" id="columns_1_matrix"/> </div> <div> <label>text</label> <input type="number" id="rows_2_matrix" /> </div> <div> <label>text</label> <input type="number" id="columns_2_matrix"/> </div> <input type="submit" value="generate"/> </form> <a href="/operations"><button>Back</button></a> {% endblock %} -
Django + Nginx + Gunicorn : Problem to load statics files
I am running a Django application on a Linux server with NGINX. I am having issues accessing the index.html to load static files such as CSS and JavaScript. Paths: Project path: /opt/proj/proj Static folder path: /opt/proj/proj/static Static files path: /opt/proj/staticfiles WSGI path: /opt/proj/proj/config wsgi HTML templates path: /opt/proj/proj/login/templates Settings.py: BASE_DIR: /opt/proj/proj STATIC_ROOT: /opt/proj/staticfiles STATICFILES_DIRS: ['/opt/proj/proj/static'] ls -la: drwxrwxr-x 6 appusr root 4096 Sep 10 11:00 . drwxrwxr-x 3 appusr appusr 4096 Sep 9 22:44 .. drwxrwxr-x 2 appusr root 4096 Sep 10 08:53 bin drwxrwxr-x 3 appusr root 4096 Sep 9 22:44 lib drwx------ 6 appusr appusr 4096 Sep 10 11:04 proj -rwxrwxr-x 1 appusr root 203 Sep 10 08:53 pyvenv.cfg drwxr-xr-x 6 www-data www-data 4096 Sep 10 11:00 staticfiles NGINX Configuration: server { listen 80; server_name pense.ai; access_log /var/log/nginx/proj.log; location /static/ { alias /opt/proj/staticfiles/; } location / { proxy_pass http://181.177.55.120:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALLDSP COR PSAa PSDa OURNOR ONL UNI COM NAV"'; } } Console Error: WARNING 2024-09-10 13:29:08,648 log Not Found: /static/css/login-btn-voltar.css Not Found: /static/css/login-style.css WARNING 2024-09-10 13:29:08,653 log Not Found: /static/css/login-style.css Not Found: /static/js/login.js WARNING 2024-09-10 13:29:08,665 log Not Found: /static/js/login.js I have literally tried everything. I am almost considering removing the … -
Acces to django context to html js
I'm trying to access to my django context from my views.py to my index.html page but something wrong and I need help. My context from django called in my html template is working fine with: {% for i in links %} <li><a>{{i.id}}; {{i.sequence}}; {{i.category}};{{i.link}}; {{i.description}}; {{i.image}}</a></li> {% endfor %} out of that give me: 2; 0; OUTILS DU QUOTIDIEN - DIVERS;https://safran.fabriq.tech/login; La solution tout-en-un pour le QRQC Digitalisé ! Détectez, escaladez, résolvez vos problèmes plus rapidement et améliorez votre performance.; Logos/Fabriq_0ER4lsy.png 3; 0; OUTILS DU QUOTIDIEN - DIVERS;https://improve.idhall.com/; Improve est la plateforme collaborative de Safran pour piloter toutes les initiatives de progrès du Groupe (de l'idée au projet d'amélioration).; Logos/Improve_lFlB5pY.png 4; 0; OUTILS DU QUOTIDIEN - DIVERS;https://portal.bi.group.safran/reports/powerbi/REPORTS/Safran%20Aircraft%20Engines/Develop/Innovation-Participative-SAE/IP-FULL-SAE?rs:Embed=true; PowerBI IP Safran Aircraft Engines.; Logos/Gestor_gVEU0RR.png but in my js: <script> var linksData = '{{links}}'; for(let j=0;j< linksData.length;j++) { document.writeln('<p class="card-text">"'+String(linksData[j].category)+'"</p>'); } </script> give me : "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" "undefined" ... My attempt was also with var linksData = JSON.parse('{{links|escapejs}}'); but still not working and return nothing, could you help me please? Thanks a lot Philippe -
NotImplementedError: subclasses of BaseDatabaseIntrospection may require a get_sequences() method
I have recently upgraded the social-auth-app-django library version from 5.0.0 to 5.4.1. I am adding the versions of few of the other libraries used: Django==4.2.15 django-tenant-schemas==1.12.0 django-restql==0.15.4 djangorestframework==3.15.2 social-auth-app-django==5.4.1 I keep getting the below error after this upgrade, adding the stack trace below: Applying social_django.0011_alter_id_fields... Traceback (most recent call last): File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/db/models/query.py", line 916, in get_or_create return self.get(**kwargs), False ^^^^^^^^^^^^^^^^^^ File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/db/models/query.py", line 637, in get raise self.model.DoesNotExist( core.models.LoyaltyTenant.DoesNotExist: LoyaltyTenant matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/circleci/bolapi-build/manage.py", line 35, in <module> main() File "/home/circleci/bolapi-build/manage.py", line 31, in main execute_from_command_line(sys.argv) File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/core/management/commands/test.py", line 68, in handle failures = test_runner.run_tests(test_labels) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/test/runner.py", line 1054, in run_tests old_config = self.setup_databases( ^^^^^^^^^^^^^^^^^^^^^ File "/home/circleci/bolapi-build/core/test_runner.py", line 58, in setup_databases tenant, _ = get_tenant_model().objects.get_or_create( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/db/models/query.py", line 923, in get_or_create return self.create(**params), True ^^^^^^^^^^^^^^^^^^^^^ File "/home/circleci/.pyenv/versions/3.11.9/lib/python3.11/site-packages/django/db/models/query.py", line 658, in … -
How to filter the one-to-many relationship from both side
I have two tables which has relationship. class Parent(SafeDeleteModel): name = models.CharField(max_length=1048,null=True,blank=True) class Child(SafeDeleteModel): name = models.CharField(max_length=1048,null=True,blank=True) parent = models.ForeignKey(Project,blank=True, null=True, on_delete=models.CASCADE,related_name="parent_project") In this case I can filter the Child by Parent such as Child.objects.filter(parent__name="test") However I want to do the reverse like this below. Parent.objects.filter(child__name="test") Is it possible? -
Django PayPal webhooks verification testing
I want to create my own realization of paypalrestsdk.WebhookEvent.verify that I'm using right now, so I want to create test, that uses request from PayPal webhook that my app already handled, for verification tests. My question is - Is it possible to verify webhook that is already verified (so basically I just provide already verified request to paypalrestsdk.WebhookEvent.verify). I created test that uses data that was used for real webhook verification for paypalrestsdk.WebhookEvent.verify. Symbol "*" is used for confidential info. class MockRequest: def __init__(self, meta, body): self.META = meta self.body = body class TestVerifyEvent(unittest.TestCase): def setUp(self): self.body = {"id":"*","event_version":"1.0","create_time":"*","resource_type":"sale","event_type":"PAYMENT.SALE.COMPLETED","summary":"Payment completed for $ 10.0 USD","resource":{"billing_agreement_id":"I-2CSK9W3P6C29","amount":{"total":"10.00","currency":"USD","details":{"subtotal":"10.00"}},"payment_mode":"INSTANT_TRANSFER","update_time":"*","create_time":"*","protection_eligibility_type":"ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE","transaction_fee":{"currency":"USD","value":"0.84"},"protection_eligibility":"ELIGIBLE","links":[{"method":"GET","rel":"self","href":"https://api.sandbox.paypal.com/v1/payments/sale/*"},{"method":"POST","rel":"refund","href":"https://api.sandbox.paypal.com/v1/payments/sale/*/refund"}],"id":"1TV06398E1048801N","state":"completed","invoice_number":""},"links":[{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/*","rel":"self","method":"GET"},{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/*/resend","rel":"resend","method":"POST"}]} self.META = { 'HTTP_PAYPAL_TRANSMISSION_ID': 'verified transmission id', 'HTTP_PAYPAL_TRANSMISSION_TIME': 'verified transmission time', 'HTTP_PAYPAL_CERT_URL': 'https://api.sandbox.paypal.com/v1/notifications/certs/*', 'HTTP_PAYPAL_TRANSMISSION_SIG': 'verified transmission signature', 'HTTP_PAYPAL_AUTH_ALGO': 'SHA256withRSA' } self.mock_request = MockRequest(self.META, str(self.body).encode('utf-8')) def test_verify_event(self): result = verify_event(self.mock_request) self.assertTrue(result) if __name__ == '__main__': unittest.main() And that is my code that gets info from request and uses paypalrestsdk.WebhookEvent.verify for verification. It's working on deployment server, but in my test it always returns False. I have several ideas why it is like that: 1. It's because I test it on localhost 2. Maybe webhook can be verified only once or something like that 3. My test work's … -
How to specify a default based on the request for a field in the create form of a TabularInline
I have a model which has a language_code field: class SkillSynonym(StandardModel): """SkillSynonym class""" skill = models.ForeignKey( Skill, on_delete=models.CASCADE, related_name="synonyms" ) name = models.CharField(max_length=200) language_code = models.CharField( db_index=True, max_length=8, verbose_name="Language", choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE, ) class Meta: unique_together = ("name", "language_code") def __str__(self) -> str: """SkillSynonym object representation.""" return f"{self.name}" This is then edited through a TabularInline admin inside the SkillAdmin: class SkillSynonymInline(admin.TabularInline): model = SkillSynonym extra = 0 def get_queryset(self, request: HttpRequest): queryset = super().get_queryset(request) language_code = request.GET.get("language", "en") if language_code: queryset = queryset.filter(language_code=language_code) return queryset As you can see I am already filtering the records to be shown in the inline field by the language GET parameter. This is set by the parler extension in the parent admin. I would also like to set a default value for language_code in the create form for the TabularInline I've tried overriding get_formset, but I'm not sure what to do with it.