"Вопросы и ответы" Django и Python

17.05.2024
Advice on using patch file in django for installed library

I am using rest_framework_simple_api_key in my production application on python version 3.9 . On running command python generate_fernet_keymanage.py as given in doc(djangorestframework-simple-apikey) i am getting File "C:\Users\DELL\anaconda3\lib\site-packages\rest_framework_simple_api_key\models.py", line 15, in <module> class AbstractAPIKeyManager(models.Manager): File "C:\Users\DELL\anaconda3\lib\site-packages\rest_framework_simple_api_key\models.py", line 16, …

17.05.2024
TypeError: 'class Meta' got invalid attribute(s): manager_inheritance_from_future in Django4.2

I got above error while running the makemiragtions command. So I delete/renamed the existing migration folder and rerun the makemirations command it's is migrated but when I run the migrate I got same error i.e., TypeError: 'class Meta' got invalid …

17.05.2024
Where to add css files within django project

I'm building a To Do list in Django by following a tutorial, I'm trying to make seperate CSS file instead of directly writing it within HTML file, However i'm recieving 404 error. Below is directory structure ├─ base/ │ …

17.05.2024
Django: how to create a unique instance of one model as a field in another model

I am trying to store an instance of an Item model as a field in my users model using ForeignKey like so: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) username = models.CharField(max_length=255) items = models.ForeignKey('Item', on_delete=models.CASCADE) def __str__(self): return …

17.05.2024
Why will my Django middleware redirect googlebot instead of directly allowing it?

Class BlockDirectAPIAccessMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): protected_paths = ['/api/socialinfo', '/api/crypto-data'] if any(request.path.startswith(path) for path in protected_paths): googlebot_user_agents = [ "Googlebot", "Googlebot-Image", "Googlebot-News", "Googlebot-Video", "Storebot-Google", "Google-InspectionTool", "GoogleOther", "Google-Extended" ] # Check for Googlebot (allow access) user_agent …

17.05.2024
Issue connecting MySQL to Django [duplicate]

My Django project will not migrate the changes I have made to the settings.py I get this error (1045, "Access denied for user 'root'@'localhost' (using password: NO)") I installed and setup a MySQL created a database connected all the information …

16.05.2024
Image gallery using magnific-popup always popup first one, not the one selected when clicked

I'm using JQUERY and Magnific Popup in a django project. When I clicked on any image in the gallery, it always popup the first image instead of the one selected. This is my current code: Here is the django template …

16.05.2024
Django (DRF) Channels getting SynchronousOnlyOperation on deleting User instance

I'm using DjangoRestChannels (based on Django Channels). I made a simple comments page. When new Comment added by any User instance consumer sends in to JS and renders on HTML. Everything works exceps when User instance gets deleted I'm getting …

16.05.2024
Error in vercel while uploading a django app

While trying to upload my Django application I got these errors requirements.txt error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully Error: Command failed: pip3.12 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/requirements.txt error: subprocess-exited-with-error how do …

16.05.2024
How to efficiently convert denormalized data to JSON?

I am learning django and couldn't find an answer on this. I am receiving data a query in denormalized form. Here is how it looks like. Store_id Shelf_id Product_id Qty store1 …

16.05.2024
Upgrading postgres version in django error

I'm trying to get postgres 14 (upgrading from 11) to work locally. Initially the docker file looked like: db: image: postgres-14.11 environment: volumes: healthcheck: test: timeout: 20s retries: …

16.05.2024
Error in django KeyError at /accounts/register/

I have a problem. When clicking on the link http://127.0.0.1:8000/accounts/register / returns the KeyError error at /accounts/register/ 'email'. I program in django in pycharm this is code: registration/urls.py: from django.contrib.auth import views as auth_views from django.urls import …

16.05.2024
Bad Request (400): Django / Nginx / Gunicorn / Kubernetes

I have a Django project running on Kubernetes with Redis, Postgres, Celery, Flower, and Nginx. I deploy it using Minikube and Kubectl on my localhost. Everything looks fine; the pod logs appear good, but when I'm trying to tunnel the …

16.05.2024
Django 5 use of static files with images

I´m trying to a picture to website with help of Django 5 and static files, the website its self is working with no error is diplayed in Django 5 but image is not displayed Has tried to read the documentation …

16.05.2024
How to deal with Django and TimescaleDB hypertables?

Firstly hypertable needs all PK contains partition column, in this case time, and in the other hand Django does not allow create multi column PK so you can't create a PK that could contains the time column. Second: if I …

16.05.2024
Django cycles/wrapped classes error with running server

I am learning to build and run django framework web applications. Recently I am watching this video tutorial:https://www.youtube.com/watch?v=pLN-OnXjOJg&list=PL-51WBLyFTg38qZ0KHkJj-paDQAAu9HiP . I am doing everything as shown in the video, cmd shows that the server is working properly. But …

16.05.2024
Применяются несуществующие стили к странице

Самая распространенная проблема - не применяются стили к шаблону. У меня же все наоборот: удаляя стили из файла, страница продолжает выглядеть так, будто бы стили существуют. После перезагрузки, миграции базы данных - все так же. Проблема исправляется при …

16.05.2024
CSRF Token in Angular 17 using django

I am using django for backend and for POST/GET request I am using this function which is def player_list(request): if request.method == 'GET': players = Player.objects.all().values() # get all players as Python dictionaries player_list = list(players) return JsonResponse(player_list, safe=False) elif …

16.05.2024
Django objects.filter returns empty array even it returns an object befor with same request

Im currently working on a Excel to DB Project where i put the 3000 products in my SQLite DB. Some of the products are duplicated or already exist in the DB. So I am looping through the Excel sheet and …

16.05.2024
Page not found on Django using Websockets

It's the first time I'm working with websockets in Django and I'm not doing it very well, what's happening to me is that I get either the 404 not found error or the error: unexpected server response: 200, I've been …

16.05.2024
How to implement a message system with Django across domain and subdomains?

I want to develop a web application using Django. This application is a support network. End users will create support tickets via the 'www.mydomain.com' web address, and employees will respond to these tickets via an admin panel at 'support.mydomain.com'. Tickets …

16.05.2024
Django-allauth NoReverseMatch Error for 'account_login' with Custom URL Patterns

I'm working on a Django project that includes user authentication using django-allauth. I have set up custom URL patterns that include a library_slug parameter for multi-tenancy purposes. However, when I navigate to the signup page (http://localhost:8000/bgrobletest/accounts/signup/), I encounter a NoReverseMatch …

16.05.2024
How can I download satellite images (e.g sentinel-2) from Google Earth Engine (GEE) using the python api in Django

So basically I am trying to create an API endpoint using Django that returns a geoJSON of coordinates and satellite images, which would be consumed by a frontend application (Nextjs/React). The coordinates are displaying as grids, but I am not …

16.05.2024
'pages' is not a registered namespace

Trying to load a index in this ambient: ├── admin_material │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── models.py │ ├── __pycache__ │ │ ├── admin.cpython-311.pyc │ │ ├── admin.cpython-312.pyc │ │ ├── apps.cpython-311.pyc …

16.05.2024
KeyError at /accounts/register/ [closed]

I have a problem. When clicking on the link http://127.0.0.1:8000/accounts/register / returns the KeyError error at /accounts/register/ 'email'. I program in django in pycharm this is code: registration/urls.py: from django.contrib.auth import views as auth_views from django.urls import …

16.05.2024
How to get set-cookies in react from django

I am running frontend as react and backend as Django. I've configured CORS and set up my environment for my web application. Within this application, I'm storing some values in session for each user. The requirement is to persist data …

16.05.2024
VPS Ubuntu 22.04 - Django - Gunicorn - Nginx

If I use; gunicorn --bind 0.0.0.0:8000 my_project.wsgi works Then this is my config: gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target gunicorn service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=my_user Group=www-data WorkingDirectory=/home/my_user/test EnvironmentFile=/home/my_user/test/.env ExecStart=/home/my_user/test/env/bin/gunicorn \ --access-logfile - \ --workers 3 …

16.05.2024
Can't browse server for videos in Django Rest Framework project using CKEditor in admin panel

I use CKEditor for my django project to write Articles rich text. I easily can upload images to the server and next time select them by browsing server like this (by click on Embed Image button): enter …

16.05.2024
Creating many models dynamically for an app in django

Hello folks, I want to know if it is possible to create models dynamically for example from the admin panel in django ? For example an app which is role is to have a model itself with many fields …

16.05.2024
Django Channels: Error UNKNOWN while writing to socket. Connection lost

We have Django Channels coupled with uvicorn and azure redis instance. Our sentry is getting swamped with errors such as: Exception in ASGI application ssd.consumers in disconnect Error UNKNOWN while writing to socket. Connection lost. The exception is thrown …

16.05.2024
Django DRF deosn't deserialize json

I faced a very weird issue with django drf. The below view does not deserializes the event_time in post() method. class EventListCreateView(generics.ListCreateAPIView): class EventSerializer(serializers.ModelSerializer): school_id = serializers.IntegerField(read_only=True) class_number = serializers.CharField(source='class.universal_number', read_only=True) class_id = serializers.IntegerField(write_only=True) class Meta: model = Event fields …

16.05.2024
Django celery with redis, celery worker not receive any message

I have a django project with celery Here is my proj/settings.py (just the celery parts) # -----CELERY CELERY_TIMEZONE = "Asia/jakarta" CELERY_BROKER_URL = "redis://localhost" CELERY_TASK_DEFAULT_QUEUE ='taibridge' CELERY_DEFAULT_QUEUE ='taibridge' CELERY_BROKER_CONNECTION_RETRY_ON_STARTUP = True # ---EOF-CELERY and here is my proj/celery.py import …

16.05.2024
Python Daylight Savings Accomodation [duplicate]

Iam working on a django project. Im fairly new to it. I have a requirement to sent out email reports in which I need to convert datetimes into yours local timezone. Im saving records in utc time and I have …

16.05.2024
Setting field.required to false cause error list indices must be integers or slices, not str

I want to set a page to update a user information, including a field to create a new password. This page is strictly for updating existing user. The password field in this page will be optional. There is another page …

16.05.2024
How to mysql database in django project

I set database connecting statement in settings.py it returns no biulding tools and ask to install mysqlclient. django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?

16.05.2024
Файл представлений Django говорит

У меня возникла следующая ошибка: не был возвращен объект HttpResponse. Вместо него возвращается None. И из того, что я прочитал, это было связано с отсутствием рендера в строке возврата, однако после многократной проверки рендер выводится из функции возврата, как …

16.05.2024
KeyError в /cart/ 'product_obj' Django

В моей корзине я могу добавить один и тот же товар с разными размерами и цветами. Но случайно, когда я хочу добавить один и тот же товар с разными размерами и цветом, у меня возникает ошибка в функции корзины iter. …

16.05.2024
Как реализовать пул соединений в django?

У нас есть несколько серверов, обращающихся к центральной базе данных MySQL, что приводит к разрыву соединений и потенциально влияет на производительность. Чтобы уменьшить это, я реализовал пул соединений в Django, используя пакет django-db-connection-pool (https://pypi.org/project/django-db-connection-pool/#:~:text=django%2Ddb%2Dconnection%2Dpool%5Ball%5D). Однако я не …

16.05.2024
Django Tests Throw ORA-00942: table or view does not exist

Я не нашел ни одного вопроса по тестам Django и Oracle DB. Я пытаюсь запустить тест на существующем приложении, но сталкиваюсь с ошибкой "Таблица или представление не существует" Я запутался, поскольку в тесте говорится, что он удаляет …

16.05.2024
Решение технического стека Python 5-Card Draw

Я пытаюсь создать игру в покер на 5 карт (один игрок с 4 ботами) для моего 85-летнего отца, чтобы он мог использовать планшет - с помощью сенсорного управления. Я изучаю python и не против использовать его для продолжения обучения. Я …