Django and Python "Questions and answers"

15.10.2024
Redirecting after making PUT request: can I redirect with GET request instead?

For my Django project, I have a primary model, Book, and an associated BookViewSet (from Django REST Framework). From the frontend, it's possible to edit other objects like Page, which POSTs to a corresponding PageViewSet. Changes to Page objects will …

15.10.2024
Django (s3) doesn't use custom domain for statics

I have S3 object storage with a CDN infront of it (on DigitalOcean). I have pointed my domain cdn.domain.com to the cdn & this is working fine. In Django I am using django-storages[s3] to connect with S3 and store static …

15.10.2024
Проблема с выполнением Celery задач в Django проекте: первая задача выполняется, вторая — нет

Концепция работы проекта: Есть django-project, он поднят локально, в нем есть 2 приложения, но виновник события - приложение с базой данных. В рамках нее, а точнее в рамках таблиц прописаны методы по доступу к этим таблицам, они же являются задачами …

15.10.2024
How can I use if else statements with multiple blocks in Django templates?

I want to load different meta tags based on the context data I receive. As you can see, in case 1, I retrieve the name from '2. name', while in case 2, it comes from 'name'. When I use this …

15.10.2024
Django pagination "infinity scroll" with HTMX incorect insert order

I'm trying to implement pagination known as "infinite scroll" with HTMX. All works fine except ordering of newly inserted objects not always correct. For example if view paginate_by = 10 then first 10 objects ordered as expected and next 10 …

15.10.2024
Problem running Django crontab in Docker container

I'm trying to create a simple cron, in my django application, but despite adding and launching correctly, the cron doesn't execute, nor does it save logs settings.py INSTALLED_APPS = [ 'django_crontab', ] CRONJOBS = [ ('*/1 * * * …

15.10.2024
Coda docs webhooks and django

I am building a web application with Django and I'm trying to automate the fetching of new data from Coda Docs. I want to use web hooks so that when rows are added on the Coda docs, my code for …

15.10.2024
Dynamically Show/Hide Django Admin Inline Forms Based on Dropdown Selection

I'm trying to dynamically show and hide inline forms in the Django admin based on a dropdown selection. I have two inline forms: one for IndividualCustomer and another for CorporateCustomer. The goal is for the corresponding inline to appear when …

15.10.2024
Django Admin panel css not align

Enter image description hereDjango admin CSS is not working as expected. As seen in the attached screenshot, the search box is misaligned. I need the search box to be properly aligned above the model data in the …

15.10.2024
Django Channels - Route not found

I have been grinding on this from past 4 days and still couldn't get the websockets connected , it always shows Not found : ws/play/testroomcode This is my consumers.py: from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json class …

15.10.2024
Can you set permission classes per function in class-based views?

Let's say we have the following class-based view (CBV) implementing DRF's APIView: class ExampleListAPIView(APIView): permission_classes = [IsAuthenticatedOrReadOnly] def get(self, request): ''' List all examples ''' examples = Example.objects.all() serializer = ExampleListSerializer(examples, many=True) return Response(serializer.data, status.HTTP_200_OK) def post(self, request): ''' Create …

15.10.2024
Python Django sees old migrations but everything was deleted

I cleared all my database, even created new with different name, deleted all migrations and migrations folder in every app of my django project, cleared all images, containers, volumes and builds in my Docker. But when I am running …

15.10.2024
Can I make a dj-rest-auth login screen that uses a different database for login details?

I want to make a login screen for my Django Rest framework. I want to create a login page that's based on my database and not the default credentials of dj-rest-auth. Is it possible to do? Or should I use …

15.10.2024
Django Rest Framework - Cross Origin Resquest got blocked

I'm developing an API using Django Rest Framework. I'm trying to list or create an "Article" object, but when i'm trying to access the console gives me this error: I host my frontend at http://localhost:3000 and sending request to 127.0.0.1:8000 …

15.10.2024
Stream an entire folder using Django without reading everything to memory

The premise is similar to this question. But the accepted answer not only requires every file to be in memory to work. The answer does provide an example of iterator usage but that doesn't work with open(file, 'rb').read(chunk_size). More …

15.10.2024
With Django , When I use connection pool , eoor(PoolTimeout) occurs. why?

When I use connection pool, yhere is no problem when starting it for the first time run, but, After a while, an error will start occurring. Traceback (most recent call last): File "web/django/venv/lib/python3.11/site-packages/django/db/backends/base/base.py", line 279, in ensure_connection self.connect() File "web/django/venv/lib/python3.11/site-packages/sentry_sdk/utils.py", …

15.10.2024
Django Testing in PyCharm. manage

I have a simple django project that I'm making in pycharm. The directory structure is the following: zelda_botw_cooking_simulator |-- cooking_simulator_project |---- manage.py |---- botw_cooking_simulator # django app |------ init.py |------ logic.py |------ tests.py |------ all_ingredients.py |------ other standard django app …

15.10.2024
Django SelectDateWidget default values for month and year only

I use the SelectDateWidget in my form and want to give default values for year and month, but show the empty_label (----) on day. I either get all three fields to be empty_label, or all fields showing the default date …

15.10.2024
How to edit lines of bar chart in apache superset based on threshold

***I am unable to customise colour of bar char in Apache super-set dashboard. The goal is if count/sum/avg is greater then 100 the colour should be blue of the line, elif greate then 1200 the colour should be red of …

14.10.2024
Ошибка при попытке авторизации с помощью drf-social-oauth2

Согласно документации создал Приложение с настройками по умолчанию. Далее настроил python_social_auth, однако при вызове http://127.0.0.1:8000/auth/login/vk-oauth2/ выдает ошибку ValueError at /auth/login/vk-oauth2/ not enough values to unpack (expected 2, got 1) Exception Location: ..\.venv\Lib\site-packages\social_core\utils.py, line 58, in module_member Вот та самая …

14.10.2024
Django storages + boto3 not working. Keeping static files local while uploading media files to S3

I'm trying to setup a django project in such a way that static files are kept in the filesystem and media files are uploaded to an amazon s3 bucket. The django storages library had an update for django>4.2. This used …

14.10.2024
TypeError: ForwardRef._evaluate() missing 1 required keyword-only argument: 'recursive_guard' on Mac

I was developing my fastapi project in my windows PC and everything was working fine there, but I recently got a new macbook and installed the lastest python 3.13 version and everything is just giving error When I try to …

14.10.2024
Dokku Procfile "release: python manage.py migrate" results in a NodeNotFoundError "Migration XYZ dependencies reference nonexistent parent node"

When attempting to deploy to the Dokku testing environment with a Postgres database, I encounter an error while the Procfile is being utilized. -----> Releasing aha-website-test... -----> Checking for predeploy task No predeploy task found, skipping -----> Checking for release …

14.10.2024
The Git pull encounter issue "RPC failed; curl 92 HTTP/2 stream 7 was not closed cleanly: CANCEL (err 8)"

I'm experiencing difficulties executing git pull in my repository. The order is unsuccessful with the subsequent error notifications: remote: Enumerating objects: 42, done. remote: Counting objects: 100% (34/34), done. remote: Compressing objects: 100% (11/11), done. error: RPC failed; curl 92 …

14.10.2024
Selenium(chrome driver) and Gunicorn problem workers close immediately after starting with daemon

I'm publishing my app to a vps everything works great when starting the app using runserver or normal testing with Gunicorn but when trying to run my server through Gunicorn the driver keeps crushing any help please ? ideas to …

14.10.2024
How to implement one-way data transfer at specific intervals using SSE or WebSockets?

I'm working on a web application where I need to send data from the server to the client at specific times rather than continuously. I want to achieve this using either Server-Sent Events (SSE) or WebSockets. Requirements: One-way communication: Data …

14.10.2024
How to bind selected objects to another model object at once on web page (like a checkbox) [closed]

I wanted to know how to create a model object by binding multiple other selected objects at once on a web page (like a checkbox or something). For example If I want to create a model named group for university …

14.10.2024
Timeout error when uploading PDF and CSV files in Django app on o2switch server

I deployed a Django application on an o2switch server and I am trying to upload files to my media folder. My code works perfectly for .txt and .xlsx files, but it does not work for .pdf or .csv files. I …

14.10.2024
Calculate max parallel elements by time in elasticsearch

I need to calculate max parallel people survey in elastic search. Mapping for this fields are: "start_at": {"type": "date"}, "end_at": {"type": "date"}, So, for one week i need to know with accuracy ~10s when in our system was max …

14.10.2024
Django Wagtail, React Native and 3rd Party Signup and Signin

I'm working on a marketplace platform. My sellers have a web portal to manage their stores. My buyers have a react native mobile application to access the platform. My server is running on django wagtail. I am using django allauth …

14.10.2024
Access Denied while sending email from AWS SES in ElasticBeanstalk (Django application)

I have recently (noticed) that I'm getting the following error in my Django application running on AWS An error occurred (AccessDenied) when calling the GetSendQuota operation: User: arn:aws:iam::123412341234:user/USER-IAM-NAME is not authorized to perform: ses:GetSendQuota with an explicit deny in …

14.10.2024
What is the best option for Django+Celery in Google Cloud run?

We currently have an application which runs in Django and background tasks are in Celery. Now, we need to move to Google Cloud Run, and how to Celery in that case, since celery can not be run in Google cloud …

14.10.2024
Can you use HTMX with datatables?

I have this in my datatables: columns: [ { data: 'product.item_code', className: 'text-start align-middle', render: function (data, type, row) { return '<a href="#" class="btn btn-primary" hx-post="/app/function/" hx-trigger="click" hx-target="#details" hx-swap="beforeend">' + row.product.item_code + '</a>' } } I am not able …

14.10.2024
Зачем нужен Django Rest Framework?

Всем привет! Возможно вопрос покажется глупым, но хочу полностью разобраться в теме начиная с таких азов. Я изучаю DJango, написал уже интернет магазин для своего знакомого, получилось достаточно неплохо, как мне кажется. Все работает, у меня есть регистрация пользователей, есть …

14.10.2024
After adding the HOST setting in django, I get a utf-8 error when creating a superuser

I am new to django. I am trying to open my project with a postgresql database in docker. There is no problem in the build process, but when I try to create a superuser, I get a utf-8 error. yml …

14.10.2024
Django returns "Authentication credentials were not provided" when I attempt token authentication

(I tried the solutions in similar questions, but they didn't work for me). I am creating a simple Django REST based web-app, where a user will register, create some events, log in later and view events. Here's the event's view: …

14.10.2024
Django: Favicon Not Displaying for Extracted Link Previews

I'm developing a Django application where users can create blog posts that include links. I want to display a preview of these links, including the website's favicon. However, despite implementing the logic to extract the favicon from the linked websites, …

14.10.2024
Django system Not Logging User Out on Browser/Tab Close (Chrome/Safari) [duplicate]

Regular Safari/Chrome: Sessions don't expire on tab or browser close. #middleware.py if manager: if client.logout_browser_close_manager: request.session.set_expiry(0) request.session.modified = True #settings.py SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_SAVE_EVERY_REQUEST = True I can confirm the middleware.py is added to the middleware configuration …

13.10.2024
PyCharm autocomplete not working for context variables in Django templates

Normally, PyCharm autocomplete (code completion) works for context variables in Django templates. For example, if the context is {"question": question}, where question is an instance of the Question model, PyCharm will offer autocomplete suggestions when I start typing {{ question. …

13.10.2024
Adds extra www when entering django admin panel

My website worked very well yesterday but today i have a problem. My website is https://www.622health.com.tr When i write https://www.622health.com.tr/admin and click enter, Its redirect to https://www.www.622health.com.tr/admin I made some redirect …