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

19.05.2024
How to move submit row to the top of the Django admin panel

I have pretty large list of objects so I would like to move the "save" button in the Django admin panel to the top of the list of objects, rather than the bottom. This would be similar to the result …

19.05.2024
Выделить сортировку в Django проекте в отдельную функцию

Существуют 2 функции: функция index выводит срез [:5] отфильтрованных карточек постов на главную страницу, функция post_detail отвечает за содержимое этих карточек. def index(request): CONST_NUMBER_OF_POSTS: int = 5 post_list = Post.objects.filter(is_published=True, category__is_published=True, pub_date__lte=timezone.now() )[:CONST_NUMBER_OF_POSTS] context = { 'post_list': post_list, …

19.05.2024
Page not found (404) django. Ошибка при переходе на страницу, на которой должна отобразиться подробная информация о товаре из бд

Я новичок в Django. Пишу сайт онлайн доски объявлений. При нажатии на карточку товара, по идее должна отобразиться страница с подробной информацией о нём, которая берётся из базы данных, но выходит ошибка "Page not found (404)". Помогите разобраться. Вот фрагменты …

19.05.2024
Issues with File Encryption/Decryption using pycryptodome

We've recently upgraded our project from Python 2.7 and Django 1.11 to Python 3.11 and Django 3.2. In the process, we've switched from using the pycrypto library to pycryptodome for cryptographic operations. Our Django application handles file uploads and downloads …

19.05.2024
Psycopg2.errors.UndefinedTable: relation "mydjangoapp_mymodel" does not exist

I am managing a django app built by third parts. I have configured in settings.py the connection to a new db 'default': { # changed 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'waterwatch', 'USER': 'waterwatch_main', 'PASSWORD': '****', 'HOST': 'localhost', } Now I want …

19.05.2024
Unable to process the input data from ModelMultipleChoiceField in Django

I've been trying to process the data captured from a simple Django Model Form, and for some reason, it isn't possible to access the group of items selected under ModelMultipleChoiceField. I'm only able to access only one item from the …

19.05.2024
Django Allauth headless Unauthorized 401 (Initial)

I'm receiving 401 when trying to reach the end point "/_allauth/browser/v1/auth/password/reset", althoug sending cookie, crsf and the key for email reseting. I'm following the flow of reseting the users password from a vuejs Frontend with this: async function sendEmailReset() { …

19.05.2024
Django custom admin template view problem

I changed the admin site index template in Django like this: admin.site.index_template = "admin/list-aprovals.html" but how can i send my model datas this page or can i add a custom view for this url: path('admin/', admin.site.urls), So, I …

19.05.2024
How to add data to Django's database by the click of a button using JS

I'm trying to add this data on database when it's clicked. It updates on my website which is static. But the data in not updating on the Database. Showing list From database on index.html <ul id="myUL"> {% for name in …

19.05.2024
Django Template Inheritance Issue: {% if %} Block Not Rendering When Extending base.html

Problem Description I'm working on a Django project where I have a form that, when submitted, calculates some results and displays them on the same page. The issue arises when I use a base template (base.html). Without using base.html, everything …

19.05.2024
Aws app running django static s3 url missing colon wrong url

This is my first post and i was to highlight a problenm that i've struggled with for a whole day. While configuring my django project by recovering the static files from an s3 bucket i've ended up with a problem, …

19.05.2024
Pygame in django

I'm trying to make an online game using Django, but having some trouble: Here is my game code in py/main.py import pygame import sys def main(): pygame.init() screen = pygame.display.set_mode((50, 50)) pygame.display.set_caption("Test") while True: screen.fill((255, 255, 255)) for event in …

19.05.2024
How the PrivateFileField handles validators in django?

Class AbstractFirmwareImage(TimeStampedEditableModel): build = models.ForeignKey(get_model_name('Build'), on_delete=models.CASCADE) file = PrivateFileField( 'File', upload_to=get_build_directory, max_file_size=app_settings.MAX_FILE_SIZE, storage=app_settings.PRIVATE_STORAGE_INSTANCE, max_length=255, validators=[MaxLengthValidator(255)], ) type = models.CharField( blank=True, max_length=128, choices=FIRMWARE_IMAGE_TYPE_CHOICES, help_text=_( 'firmware image type: model or ' 'architecture. Leave blank to attempt ' 'determining automatically' ), ) …

19.05.2024
Python 3.12 Sentry-sdk AttributeError: module 'collections' has no attribute 'MutableMapping'

I tried to use sentry-sdk latest version with Python 3.12, but when I run my django app, it shows me following error: AttributeError: module 'collections' has no attribute 'MutableMapping' Full trace as follows: File "/usr/local/lib/python3.12/site-packages/sentry_sdk/__init__.py", line 1, in <module> …

19.05.2024
User defined logvars for Django application deployed on uWSGI server

I have deployed a Django application on a uWSGI server, which has the following middleware # myapp/middleware.py from django.utils.deprecation import MiddlewareMixin class LogUserMiddleware(MiddlewareMixin): def process_request(self, request): request.META['REMOTE_USER'] = 'test' The middleware is added in the settings.py file as well …

19.05.2024
How to run the build command before the build on Digital Ocean App Plateform

I need the json key file to configure my google cloud storage credentials in my settings.py (Django app) `GS_SERVICE_ACCOUNT = "static/GCS_key_api.json" GS_PROJECT_ID = os.getenv('GS_PROJECT_ID') GS_CREDENTIALS = service_account.Credentials.from_service_account_file(GS_SERVICE_ACCOUNT)` Here the logs of the build on App Plateofrm: 2024-05-19T09:24:41.171400485Z [34m╭────────────[34m[30m[44m git repo …

19.05.2024
Flatten DRF's nested serializer

I have two models for each user, a User model and a Profile model. class User(BaseModel, AbstractUser): username = None image = models.CharField(max_length=300, blank=True, null=True) email = models.EmailField(unique=True) password = models.CharField(max_length=300) emailConfirmed = models.BooleanField(default=False) phoneNumber = models.CharField(max_length=15, blank=True, …

19.05.2024
Django ошибка 404 django

Всем доброго времени суток. Я новичок в цифровом мире. Учусь на Python по ютубу и книге Мэтиза. Делаю сайт, но возникла проблема с urls. При попытке открыть страницу topics отображается ошибка 404. Меняла urls, но все тщетно. Далее код из …

19.05.2024
404 found error for post request at backend

I am unable to make post request to backend side using react. Here is my auth file and error file: I am expecting to make a request at http://localhost:8000/api/v1/user/register/ But the site …

19.05.2024
Is there a better way to update all relation rows with `ForegnKey` relation in `Django ORM`

I have two models, one like this: class PhysicalSensor(models.Model): name = models.CharField(unique=True, max_length=255) def __str__(self) -> str: return self.name class Sensor(models.Model): physical_sensor = models.ForeignKey(PhysicalSensor, on_delete=models.RESTRICT, null=True, blank=True) So, when I want to add a PhisycalSensor record, I …

19.05.2024
"'BillInvoice' instance needs to have a primary key value before this relationship can be used" Error

I'm experiencing an issue with my Django project where I'm trying to create a BillInvoice and its associated BillLineItem instances. The error I'm encountering is: "'BillInvoice' instance needs to have a primary key value before this relationship can be used" …

19.05.2024
Django create relation between this two tables from different db schemas

I use RDS. The db have different schemas for Users and Products class Product(models.Model): id = models.AutoField(primary_key=True) class User(models.Model): id = models.AutoField(primary_key=True) DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "OPTIONS": {"options": "-c search_path=public"}, "NAME": config("DB_NAME", default=""), "USER": config("DB_USER_NAME", …

19.05.2024
Sorted serializer data by group DJANGO RESTFRAMEWORK

How do I get sorted serializer data by group in DJANGO RESTFRAMEWORK? My model: class VariantCombination(models.Model): product = models.ForeignKey(Product, related_name='variant', on_delete=models.CASCADE, null=True, verbose_name="Продукт") variant = models.ForeignKey(Variant, on_delete=models.CASCADE, null=True, blank=False, verbose_name="Варианты") variant_value = models.ForeignKey(VariantValue, on_delete=models.CASCADE, null=True, blank=False, verbose_name="Значение варианты") price = …

19.05.2024
I can't seem to load data from mysql to django's templates

I've been trying for hours, and i can't seem to get data from mysql to django. i've checked everything, views, urls, the html files, admin etc. I have a submission in 5 hours so it'll be great help if i …

19.05.2024
Custon user form conflict in variables [duplicate]

Trying to use custom forms to use info from models, for signup, login, etc. models.py from django.db import models from datetime import datetime from django.contrib.auth.models import AbstractUser # error is in CustomUser, next line class CustomUser(AbstractUser): username = …

19.05.2024
Django class based views, follow system

I want to use If statement and I use class based views. the problem is I don't know how to implement if statement in class based views here is the view: class ProfileView(DetailView): model = CustomUser template_name = 'profile.html' def …

18.05.2024
How to upload and store multiple images in Django 4

Django 4 Need user to be able to upload either an archive of images or just a few images at a time. Then these pages are numbered according to the order in which the user has placed them and stored …

18.05.2024
Why recognize my models in an other app in django how can i call models in other app

From product.models import Product CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): cart = self.cart.copy() for item in cart.values(): item['product'] = …

18.05.2024
[Nginx][Django] Cannot access the media files in production via Nginx

I am trying to access the media files using Nginx. The file exists in the directory: /usr/src/app/backend/media/profile/c4ebe33d-7da1-4a62-bb17-8da254d69b36, where the part profile/c4ebe33d-7da1-4a62-bb17-8da254d69b36 is created dynamically. The media root is: /usr/src/app/backend/media. I know the file exists cause I am able to see …

18.05.2024
When I console.log fetched data it appears as undefined but it appears when I refresh

I have this function in react to fetch the data from my django API: const [filterData, setFilterData] = useState([]); const fetchFilterData = async () => { const filter_url = 'http://127.0.0.1:8000/api/filters/' try { const response = await fetch(filter_url) const result = …

18.05.2024
Django Deployment failed during build process on railway

When I deploy my Django app on rail after adding nessary variables and updated file everything done unless this failed do u know why and how to fix it Build logs on railway;here the problem how can i fix it"#8 …

18.05.2024
Nothing happens when transferring data to the database

I have a problem. I'm new to django. And so the error lies in the fact that nothing happens during the data transfer. The database is not being updated. I will be very grateful for your help! this is code: …

18.05.2024
Data Flow in Django Rest Framework?

I have recently started learning Django Rest Framework, and hit a little roadblock trying to understand the data flow in DRF. From what I understand, views take in a web request and return a web response, so they are the …

18.05.2024
Django Model Form, seems like there is an anomaly where my user creation form's clean_username method is not throwing a ValidationError when it should

Background I have a custom User model that I have extended from BaseUserManager and AbstractBaseUser. Similarly, I have a custom sign-up form that I've extended from UserCreationForm (all these custom items are extended from django.contrib.auth). The custom UserCreationForm I've made …

18.05.2024
Cant run django-admin in windows11

I was trying to start a new project in django and ran into this error.enter image description here i already created venv and installed django with venv activated.But even after successfull installlation of django i can't run …

18.05.2024
I want to add CMS feature in my current website, which lib would you recommend? [closed]

Curretly, I want to add CMS feature in my current website, which lib would you recommend? Hi, I already using Django build a simple website, but don't have CMS feature yet. Recently, I want to add CMS feature in the …

18.05.2024
Displaying images from static folder in Django

We have a problem with displaying images on html pages. We create graph, save it and then pass it's url to html page via context, but django can't find the picture (Error 404 Not Found). There's no model to store …

18.05.2024
Mock patching an endpoint unittest that makes several requests to third party

I have a single endpoint written using django ninja. This endpoint executes a crawler that performs several requests. The sequence of requests has 3 different routines depending on whether or not the crawler already has valid login credentials in its …

18.05.2024
KeyError error at /registration/register/ 'email'

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. I want to point out that there is a specific 'email' error here! …

18.05.2024
How to reverse a URL in format namespace:view:endpoint?

I have a Django project with the following urlpattern defined on project level: urlpatterns = [ path('', include(('ws_shopify.urls', 'ws_shopify'), namespace='shopify')), ] The file ws_shopify.urls defines the following urlpatterns: urlpatterns = [ path('api/shopify/', ShopifyWebhookAPIView.as_view(), name='webhook'), ] The class ShopifyWebhookAPIView …