Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to trigger Django task at specific date in model field
I have a model that contains the following field class EventConfig(models.Model): end_date = models.DateTimeField(blank=True, null=True) I have celery installed that's sending periodic emails and triggering other tasks at set time intervals e.g every hour or at 12pm. However, if I want to trigger an email as exactly when 'end_date' is reached, what is the best way to do this? I realise I could set a Celery schedule to run every minute to check the date, but is running a batch job every 60 seconds perpetually, the best approach or would this have drawbacks? Is there a way for example to set the crontab schedule to read from a list of values so that I could so something like schedule_list = EventConfig.objects.all().values_list(end_date, flat=True) or schedule_list.append(self.end_date) whenever a model instance is saved, and have Celery read from 'schedule_list' so the batch jobs then only fire at the correct times? Or is there a better way to do this either with or without celery? -
Merging tags admin action result in TemplateDoesNotExist
Following the docu's step: 3. Use the dropdown action list and select Merge selected tags and then click Go, I get the error below. Any ideas where I should start to investigate? Otherwise taggit works like a charm. django-taggit 6.0 TemplateDoesNotExist at /admin/taggit/tag/merge-tags/ admin/taggit/merge_tags_form.html Request Method: GET Request URL: http://localhost:8001/admin/taggit/tag/merge-tags/ Django Version: 4.2.16 Exception Type: TemplateDoesNotExist Exception Value: admin/taggit/merge_tags_form.html Exception Location: /home/abc/.local/share/virtualenvs/django-xy011hf/lib/python3.8/site-packages/django/template/loader.py, line 19, in get_template Raised during: taggit.admin.merge_tags_view Python Executable: /home/abc/.local/share/virtualenvs/django-xy011hf/bin/python Python Version: 3.8.12 -
Rendering datetime and proper formatting
I have a django project to keep track of tasks in a office enviroment. I have this model for tasks and it has a finish_date attribute that its assigned as soon i acces the route to done the desired task. I'm trying to use datetime and pytz to correctly format the date to the DateTimeField attribute. Here's the view code: task.data_conclusao=datetime.now().astimezone(pytz.timezone('America/Sao_Paulo')) task.save() It's saving the datetime but when i render it on the html, it just doesnt adjust to the timezone i set. Can anyone help me? -
Why am I getting the error (CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.)?
I'm trying to send from React a PUT request to my Django server for updating a Django model field. Here's the code const handleStatusChange = async (projectId, newStatus) => { try { const response = await fetch(`/api/project/${projectId}/status`, { method: 'PUT', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value }, body: JSON.stringify({ status: newStatus }) }); if (response.ok) { setProjects(prevProjects => prevProjects.map(project => project.id === projectId ? { ...project, status: newStatus } : project ) ); setStatusDropdown(null); setUpdatingProjectId(null); } else { console.error('Failed to update project status'); } } catch (error) { console.error('Error updating project status:', error); } }; The problem is that the console logs the message 'Failed to update project status' because of the server error: Forbidden (CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.): /api/project/1/status WARNING:django.security.csrf:Forbidden (CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.): /api/project/1/status [06/Dec/2024 17:37:21] "PUT /api/project/1/status HTTP/1.1" 403 2549. I have no clue of what's leading to the error. I applied the same logic to another PUT request in other page and I didn't have the issue. Can somebody explain please how I can manage the csrf token length? I'm not "manually" generating such token. I'll share the complete console error if helps: index.js:25 … -
how to classify based on a column values from database in django
i wanted to classify some data from database and show it in a table this is how get the data <tbody> <tr class=""> {% for c in cluster %} <td>{% if c.hasil_klasifikasi == 'Banyak Terjangkit' %}{{ c.nama_penyakit }}{% endif %}</td> <td>{% if c.hasil_klasifikasi == 'Kurang Terjangkit' %}{{ c.nama_penyakit }}{% endif %}</td> </tr> {% endfor %} </tbody> but the results dont looks right result on the table any help would be very much appreciated, thanks i was trying to classify the data in the table without blank cell like that i want to get the data like this here -
Django gettext translation doesnt work on dinamic translations
Question: I am working on a Django application that supports multiple languages. I am using token-based authentication and trying to change the language for authenticated users based on their preference stored in their profile. However, I am encountering a few issues regarding how the translations are being applied, particularly when it comes to dynamic message translations. What I have: I have set up multiple languages in settings.py (LANGUAGES) and configured the default language to be English (LANGUAGE_CODE = 'en'). I am using token-based authentication (rest_framework.authtoken) to authenticate users. The user’s preferred language is stored in the database as preferred_language. I have added a custom middleware to handle language switching based on the user’s preference, which should be applied as soon as the user is authenticated and the session is set. Problem: Language preference seems to be applied for static content (like templates), but dynamic translations for strings in views (using gettext) are not applying correctly after the user’s preferred language is set. For example, while the language change works partially (like UI content), messages generated using gettext() (like error or success messages) are still showing in the default language (en), not the user's preferred language (e.g., es for Spanish). Here … -
OperationalError. Django tries to access a non-existent table
Building a e-commerce site with django. When I try to add a new element into the products model in the django interface and click the save button, this is what I get(refer to the pic below via the link). It says 'no such table: main.auth_user_old', but I don't know why it tries to access a non-existent, unnecessary table. Help me to solve this issue I tried upgrading the django library, made several migrations and even built the project again from scratch, none of it helped. I've checked the database, the closest thing to the specified table is auth_user and not auth_user_old. Screenshot of the error page -
403 error with CSRF when accesing Django login by axios
await axios.get("http://localhost:8000/get_csrf_token/").then((res)=>{ console.log(res.data.csrf_token); axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.withCredentials = true; axios.post('http://localhost:8000/login/',{ username:'admin', password:'Kv79NExi' }, { headers: { 'Content-Type': 'application/json', 'X-CSRFToken': res.data.csrf_token, } }) .then((response) => { log("response login",response.data); }); }); I am trying to access django login, however it shows the error like this, <p>Reason given for failure:</p>\n' + ' <pre>\n' + ' CSRF cookie not set.\n' + ' </pre>\n' + It returns 403 error, it looks like sending csrf_token correctly. Where am I wrong? Ran all test suites matching /TopPage/i. node:internal/process/promises:288 triggerUncaughtException(err, true /* fromPromise */); ^ AxiosError { message: 'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: { transitional: { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false }, adapter: [ 'xhr', 'http', 'fetch' ], transformRequest: [ [Function: transformRequest] ], transformResponse: [ [Function: transformResponse] ], timeout: 0, xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFTOKEN', maxContentLength: -1, maxBodyLength: -1, env: { FormData: [Function: FormData] { LINE_BREAK: '\r\n', DEFAULT_CONTENT_TYPE: 'application/octet-stream' }, Blob: [class Blob] }, validateStatus: [Function: validateStatus], headers: Object [AxiosHeaders] { Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'X-CSRFToken': '9aSiDra8P3LzU0hMlSFZ9yqX5fllDySQljBRyHM6jjSYfuZ1BWrCUF9blkElzl1v', 'User-Agent': 'axios/1.7.9', 'Content-Length': '42', 'Accept-Encoding': 'gzip, compress, deflate, br' }, withCredentials: true, method: 'post', url: 'http://localhost:8000/login/', data: '{"username":"admin","password":"Kv79NExi"}' }, request: <ref *1> ClientRequest { _events: [Object: null prototype] { abort: … -
Why is related_name required for annotation?
I'm struggling to understand why related_name is required in order to do annotation. When trying to obtain the count of related object as annotation, one could use the below: class ModelA(models.Model): (...) class ModelB(models.Model): model_a_fk = models.ForeignKey(ModelA, related_name="model_bs") ModelA.objects.annotate(num_model_b=Count('model_bs')).order_by('-num_model_b') Why is the related_name required on the model and can't we just use the below? ModelA.objects.annotate(num_model_b=Count('model_a_fk_set')).order_by('-num_model_b') As this yields following error: FieldError: Cannot resolve keyword 'model_a_fk_set' into field. Choices are: id, (...) -
Why is the request URL / HTTP_REFERRER in Django error from an external domain?
TL;DR Was getting a Django error because I wasn't properly redirecting authenticated users making GET requests to my login endpoint (fixed this problem); however, I'd like to understand why the Request URL / HTTP_REFERRER in the error message was an external domain. Background I've been getting a few Django server errors per month in my production web app that list sendgrid.net as the Request URL (as well as the HTTP_REFERRER). I realized that some of my transactional email templates were turning links into strange sendgrid URLs for clicktracking, so I added clicktracking="off" to all the anchor elements in my templates to avoid this. However, the errors have persisted. Current Problem Today I tried navigating to https://example.com/login/ when I was already logged in, expecting it to redirect me to my user profile page but instead it triggered a 500 error. When I looked at the error readout that was automatically emailed to me from my Django app, the Request URL / HTTP_REFERRER was not https://example.com/login/ but rather a subdomain of sendgrid.net (see below). The error was being triggered on my view called CustomLoginView: Exception Type: NoReverseMatch at /login/ Exception Value: Reverse for 'member-detail' with no arguments not found. 1 pattern(s) tried: … -
Files get served when django website is ran locally, but not when run on heroku
When I run my django website locally all my MEDIA files get served via AWS, but I now uploaded my website to heroku, and it keeps trying to load the files locally instead of AWS, how to fix this? Settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5" CRISPY_TEMPLATE_PACK = "bootstrap5" LOGIN_REDIRECT_URL = 'home' LOGIN_URL = 'login' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = 'eu-north-1' #change to your region AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' django_heroku.settings(locals()) -
What is the correct AWS policy in order for my app allow users to login at AWS COGNITO?
I am using Django Warrant for IAM: from rest_framework.response import Response from rest_framework.exceptions import AuthenticationFailed from rest_framework.decorators import api_view from django.apps import apps @api_view(['POST']) def login(request): username = request.data.get('email') password = request.data.get('password') if not username or not password: raise AuthenticationFailed('Username and password are required.', code=401) pool_id = getattr(settings, 'COGNITO_USER_POOL_ID', None) app_id = getattr(settings, 'COGNITO_APP_ID', None) region = getattr(settings, 'COGNITO_REGION', None) key = getattr(settings,'COGNITO_AWS_KEY',None) secret = getattr(settings,'COGNITO_AWS_SECRET',None) cognito = Cognito( user_pool_id=pool_id, client_id=app_id, user_pool_region=region, access_key=key, secret_key=secret, username=username ) try: cognito.authenticate(password=password) except Exception as e: print(e) raise AuthenticationFailed(str(e), code=401) # Return tokens return Response({ "access_token": cognito.access_token, "refresh_token": cognito.refresh_token, }, status=201) But despite my authentication being sucessfull: aws cognito-idp admin-initiate-auth --user-pool-id eu-west-1_XXXXXX --client-id XXXXXXXX --auth-flow ADMIN_NO_SRP_AUTH --auth-parameters USERNAME=YTYY,PASSWORD=YYYY Return The nessesary credentials: { "ChallengeParameters": {}, "AuthenticationResult": { "AccessToken": "XXXXXXXXXX...XXXXXX", "ExpiresIn": 3600, "TokenType": "Bearer", "RefreshToken": "XXXDDDXXXX", "IdToken": "XXXSSSXXX" } } But the view above return: { "detail": "An error occurred (NotAuthorizedException) when calling the InitiateAuth operation: Password attempts exceeded" } Responding with a 401, My IAM permissions are: { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowAdminUserPoolActions", "Effect": "Allow", "Action": [ "cognito-idp:AdminInitiateAuth", "cognito-idp:AdminRespondToAuthChallenge", "cognito-idp:AdminGetUser", "cognito-idp:AdminSetUserPassword", "cognito-idp:ListUserPools", "cognito-idp:GetUser", "cognito-idp:ListGroups", "cognito-idp:AdminAddUserToGroup" ], "Resource": "arn:aws:cognito-idp:eu-west-1:962331388720:userpool/eu-west-1_XXXXXX" } ] } What I am missing I suspect my policy is wrong. But … -
AWS Elastic Beanstalk: Connection Refused
I have deployed my django app to AWS Elastic Beanstalk, using the Docker platform. I have created a postgresql database with RDS, issued an EC2 connection from this database to the EC2 instance my Elastic Beanstalk is running on (ensuring it is part of the same VPC and subnets). The root volume for my Elastic Beanstalk container is gp3 with IMDSv1 disabled. I have assigned two security groups, one of them contains the following settings to allow for connections through NGINX and to my database: The other is the default security group. All environment variables are configured, including those required for access to my RDS Database, and AWS Access Keys for S3 buckets. However, when I go to the Elastic Beanstalk provided domain, I am shown a page saying "This site can't be reached. Connection refused". I am unsure if this may be related to my docker-compose file (something to do with networking or ports perhaps) which looks as follows: version: '3.8' services: web: build: context: . dockerfile: Dockerfile restart: always volumes: - media-data:/usr/src/media - static-volume:/usr/src/staticfiles command: gunicorn APPNAME.wsgi:application --bind 0.0.0.0:8000 -w 3 --timeout 120 ports: - "8000:8000" environment: DJANGO_SETTINGS_MODULE: "APPNAME.settings" AWS_REGION: ${AWS_REGION} env_file: .env nginx: build: ./nginx volumes: - … -
How to display 2 featured and 8 organic products per page in Django based on rank and search query?
I’m working on a Django-based e-commerce application where products have fields like is_featured (boolean) and rank (integer). The goal is to create a paginated search results view where: After searched each page displays 10 products in total. The first 2 products should always be featured (is_featured=True) and sorted by their rank. The remaining 8 products should be organic (is_featured=False) and also sorted by their rank. The products must match the search query (e.g., filtering by title or content). Ensuring this logic works efficiently, especially with large datasets. Dynamically adjusting the number of organic products to fill the rest of the page if fewer than 2 featured products are available. I want to do with caching -
html.parser and django issues
I would like to know if there are any known issues using the html.parser with django, readin The Docs and searching internet i've found nothing. I know I should post my code but its long and is spread over multiple modules; views, models, etc. My app is simple, the user uploads html file, the django app parses and writes to database. the parsing app works perfectly locally. If I use lxml parser one of my 3 html test files parses fine, the other two .sourceline returns None. If I use the html.parser or the html5lib parser a different file works, but with the other two I get bad gateway error. Its perplexing because the app works consistently locally -
How to query a reverse foreign key multiple times in Django ORM
Assuming the following models: class Store(models.Model): name = models.CharField(max_length=255) class Stock(models.Model): name = models.CharField(max_length=255) store = models.ForeignKey(Store, on_delete=models.PROTECT) class Consignment(models.Model): cost = models.FloatField() class Order(models.Model): quantity = models.IntegerField() stock = models.ForeignKey(Stock, on_delete=models.PROTECT) consignment = models.ForeignKey(Consignment, on_delete=models.PROTECT) How to create a queryset of all 'consignments' of all instances of a specific 'stores' queryset like so: target_stores = Store.objects.filter(name__startswith="One") consignments = target_stores.consignments.all() -
Migrations not getting applied , deleted the migrations folder in django
I deleted the migrations folder in one of my app folders of the project now when I run makemigrations I am getting No changes detected ..please help I was expecting that migrations folder will be created with the migration files -
Django on PythonAnywhere: ImproperlyConfigured: The SECRET_KEY setting must not be empty
I’m hosting a Django project on PythonAnywhere and encountering the following error when running makemigrations: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. My Setup: Hosting Platform: PythonAnywhere Environment Management: Using a .env file to manage secrets Python Version: 3.10 Django Version: 5.1.2 In my WSGI file, I’ve included the following code to load the .env file: import sys from dotenv import load_dotenv path = '/home/verbsmerch/verbs_backend' project_folder = os.path.expanduser(path) load_dotenv(os.path.join(project_folder, '.env')) In my settings I load the SECRET_KEY like this: SECRET_KEY = os.getenv("SECRET_KEY") What I’ve Tried: Verified that the .env file exists and is located in the correct directory. Checked that the .env file has the correct permissions (chmod 600). Ran a Python shell to debug: from dotenv import load_dotenv import os load_dotenv('/home/verbsmerch/verbs_backend/.env') print(os.getenv("SECRET_KEY")) # This prints the correct key Reloaded the web app from the PythonAnywhere Web tab. Why is Django unable to load the SECRET_KEY when it seems to work in the Python shell? How can I resolve this error? -
Approach for Handling Unfinished Chess Games When Both Players Disconnect
I need to figure out what to do if both players leave the game without finishing it. In this case, I need a solution to preserve the current game state and determine when the game should be considered over. Solution 1: Storing the Game in Redis Store the game state in Redis in case one of the players returns. When a player re-enters the game, check the state. If the time hasn't expired, continue the game; if it has, automatically end it. Solution 2: Timer via Celery Set up a Celery task that starts a timer when both players leave. If neither player returns within the given time, the game is automatically considered finished, and the result is recorded. I would appreciate any recommendations on how to solve this problem more effectively and would like to know how such situations are typically handled in production environments. -
how to generate a constent certificate in django restframework?
"How to manage consent certificates for organ donation in a DRF project?" Body: I'm building a feature where users can mark their willingness to donate organs and generate a consent certificate. The user should be able to upload the signed certificate after reviewing it. Here's the flow I need: Users mark their willingness to donate organs during registration or profile update. A consent certificate is generated and made available to the user. The user must download the certificate, sign it, and re-upload it. i need to know how to generate certificates -
Can't get Django-CMS to work with Apache and mod_wsgi
I am trying to get django-cms to run with apache wsgi. I am using Python 3.12 and the latest version of all software (a fresh bare metal install of ubuntu 24.04). Django-cms runs with runserver. My vhost file: Define impact_lab_partners_path /home/mark/python-projects/impact_lab_partners WSGIApplicationGroup %{GLOBAL} <VirtualHost *:80> ServerName impactlabpartners.com ServerAlias www.impactlabpartners.com ServerAdmin xxxxxxxxxxxxxxxxx DocumentRoot /home/mark/python-projects/impact_lab_partners ProxyRequests off ProxyPreserveHost On WSGIDaemonProcess ilp python-home=/home/mark/.virtualenvs/impact_lab_partners python-path=${impact_lab_partners_path}/impact_lab_partners WSGIProcessGroup ilp WSGIScriptAlias / ${impact_lab_partners_path}/impact_lab_parthers/wsgi.py process-group=ilp Alias /static "/home/mark/Documents/impact_lab_partners/do_not_change/static" <Directory "/home/mark/Documents/impact_lab_partners/do_not_change/static"> Require all granted </Directory> Alias /documents "/home/mark/Documents/impact_lab_partners/do_not_change/documents" <Directory "/home/mark/Documents/impact_lab_partners/do_not_change/documents"> Require all granted </Directory> <Directory ${impact_lab_partners_path}/impact_lab_partners> <Files wsgi.py> Require all granted </Files> </Directory> # LogLevel Debug # LogLevel debug # ErrorLog ${APACHE_LOG_DIR}/impact_lab_partners/error.log # CustomLog ${APACHE_LOG_DIR}/impact_lab_partners/access.log combined </VirtualHost> I have verified the paths are correct. The error I am getting in /var/log/apache2/error.log every second or so: Current thread 0x0000731f722d1780 (most recent call first): <no Python frame> [Thu Dec 05 18:27:05.634492 2024] [wsgi:warn] [pid 21694:tid 126578896738176] (13)Permission denied: mod_wsgi (pid=21694): Unable to stat Python home /home/mark/.virtualenvs/impact_lab_partners. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/mark/.virtualenvs/impact_lab_partners' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = … -
How to revert migrations when there are multiple leaf nodes?
manage.py showmigrations shows me a list like ... [X] 0240_employer_data (A) [X] 0241_person_metadata (B) [ ] 0242_delete_capability_delete_collection (C) [X] 0242_personemployer_employerworkplace (D) [X] 0243_personemployer_employed_personemployer_stage (E) [X] 0244_remove_employerworkplace_and_more (F) 0242_delete_capability_delete_collection arrived after doing a git pull and rebase. My local branch stuff that I had been working with is 0242_personempl..0244. I believe the graph looks like | A | B / \ D C | E | F Because all my migrations are just in development, I'm trying to undo them to reach the same state that the main branch is at, then make them again. I thought I could manage.py migrate myapp C delete my local D, E, F migration files files manage.py makemigrations manage.py migrate But both manage.py migrate myapp C and manage.py migrate myapp B throw the same error: CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0242_delete_capability_delete_collection, 0244_remove_employerworkplace_and_more in myapp). It looks like I cannot even revert migrations while the migration graph is in this state. What can I do to just reset my local branch's migrations and compatibilise with the main branch before building my local branch's needed migrations again? "Rebasing" the migrations in a way? -
How do I convert a complex Postgres SQL query into a Django queryset?
I have the following SQL query working: SELECT mrc.token_id, ARRAY_AGG(mt.name) AS tracking FROM markets_rankscurrent mrc LEFT JOIN ( SELECT mtg.id, mtg.index_id, mtg.favorites_group_id, mtg.name, COALESCE(ufe.token_id, mte.token_id, mie.token_id) AS token_id FROM markets_trackinggroup mtg LEFT JOIN users_favoritesentry ufe ON mtg.favorites_group_id = ufe.group_id LEFT JOIN markets_trackingentry mte ON mtg.id = mte.group_id LEFT JOIN markets_indexentry mie ON mtg.index_id = mie.index_id ) mt ON mrc.token_id = mt.token_id GROUP BY mrc.token_id; Here are my models: class Token(models.Model): class RanksCurrent(models.Model): token = models.ForeignKey(Token, on_delete=models.CASCADE, db_index=False) class TrackingGroup(models.Model): name = models.CharField(max_length=60, verbose_name='Name') favorites_group = models.ForeignKey(FavoritesGroup, on_delete=models.CASCADE, related_name='tracking_groups', blank=True, null=True) index = models.ForeignKey(Token, on_delete=models.CASCADE, related_name='tracking_groups', blank=True, null=True) class TrackingEntry(models.Model): group = models.ForeignKey(TrackingGroup, on_delete=models.CASCADE, related_name='tokens') token = models.ForeignKey(Token, on_delete=models.CASCADE, related_name='tracking_entries') class IndexEntry(models.Model): index = models.ForeignKey(Token, on_delete=models.CASCADE, related_name='index_tokens') token = models.ForeignKey(Token, on_delete=models.CASCADE, related_name='indices') class FavoritesGroup(models.Model): pass class FavoritesEntry(models.Model): group = models.ForeignKey(FavoritesGroup, on_delete=models.CASCADE, related_name='favorites_entries') token = models.ForeignKey('markets.Token', on_delete=models.CASCADE, related_name='favorites_entries') The TrackingGroup.index foreign key will only be set to a Token object that is also a foreign key in the IndexEntry table. My end goal is to be able to query the RanksCurrent table and annotate a tracking_groups column that contains a list of TrackingGroup names where the Token is a member. My attempts have made use of Subquery and ArrayAgg to try and … -
Django / Stripe - Webhook not found
I am trying to establish a webhook with stripe. (first timer) However, it seems the path to the webhook is not found. Hoping someone might be able to bring a pair of fresh eyes and tell me what I am doing wrong. In my urls.py (project level) urlpatterns = [ path('my_app/', include('my_app.urls')), ... ] In urls.py app level: urlpatterns = [ .. path('stripe_webhook/', views.stripe_webhook, name='stripe_webhook') ] In my views.py (my_app level): @csrf_exempt def stripe_webhook(request): print("enter webhook") stripe.api_key = settings.STRIPE_SECRET_KEY_TEST payload = request.body signature_header = request.META.get('HTTP_STRIPE_SIGNATURE') webhook_secret = settings.STRIPE_WEBHOOK_SECRET_TEST ... In stripe, in local listenners I have regiestered: localhost:8000/stripe_webhook/ If I run stripe trigger customer.created. I get the following returned to me: A newer version of the Stripe CLI is available, please update to: v1.22.0 Setting up fixture for: customer Running fixture for: customer Trigger succeeded! Check dashboard for event details. However, running simultaneously stripe listen --forward-to localhost:8000/stripe_webhook/, I also get the following logs: > Ready! You are using Stripe API Version [2024-09-30.acacia]. Your webhook signing secret is XXXXX (^C to quit) 2024-12-05 22:27:54 --> customer.created [xxx] 2024-12-05 22:27:54 <-- [404] POST http://localhost:8000/stripe_webhook/ [xx] and my server logs will also return (whether in production or local): Not Found: /stripe_webhook/. This makes … -
django, how to use subquery values into outer query
I have a query that uses the values from a subquery. While I'm able to write the subquery in django, I can't write the main query. Here's a little example (the schema is department <-- person <-- device --> model): SELECT department.id, AVG(subquery.typeofdevices_count) AS avg_typeofdevice_count_per_department FROM department INNER JOIN person ON (department.id = person.department_id) INNER JOIN device ON (person.id = device.person_id) INNER JOIN ( SELECT model.id AS id, count(DISTINCT device.location_id) filter (WHERE device.type = 'something') AS typeofdevices_count, FROM model LEFT OUTER JOIN device ON (model.id = device.model_id) WHERE ('some-conditions...') GROUP BY model.id, ) AS subquery ON (subquery.id = device.model_id) As you can see the outer query uses the inner value typeofdevices_count while joining with the subquery id. About the inner query is quite simple: subquery = Model.objects.annotate(typeofdevices_count= Count('device__location_id', filter=Q(device__type='something'), distinct=True ) ).filter('some-conditions...').values('id', 'typeofdevices_count') What about the main query? I tried with the following: Department.objects.annotate(avg_typeofdevice_count_per_department= Avg('persons__devices__model__typeofdevices_count', filter=Q(persons__devices__model__in=subquery) ) ).values('id', 'avg_typeofdevice_count_per_department') But I got this error, it seems it doesn't recognize the subquery annotation typeofdevices_count FieldError: Cannot resolve keyword 'typeofdevices_count' into field. Choices are:... Can you help me?