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

27.07.2024
Cannot display image with JavaScript from Django Base

I am attempting to get a customer logo to load when a user signs into my app. To do that I am using the views function below to generate the logo url: Views: def view_company_logo(request): print("GETTING LOGO") client = Client.objects.get(user=request.user) …

26.07.2024
Count by Month in Django Query

Good afternoon, I am struggling with a query. Ultimately, I have some records I want to query and get a count by month. Ultimately, my goal is to come up with a data set that looks like: Month, opened, closed …

26.07.2024
Why can't I save the Django FileField with a null value

I want to use a POST request to create an object with file fields. At the same time, at the model level, I declared that fields can be null. But Django does not allow me to save this object with …

26.07.2024
Mutliple JWT generation with different django secrets based on subdomains

I am using simple JWT (django-rest-framework-simplejwt). I have an auth server which authenticates users. Each user can belong to a single or multiple Tenants and each tenant is represented by a subdomain. I am trying to generate django secret for …

26.07.2024
I am recieving a NoReverseMatch error does anyone know what I'm doing wrong?

Im trying to allow the user to edit an existing entry. But when I include new_entry.html `{% extends "learning_logs/base.html" %} {% block content %} <p> <a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></p> <p>Add a new entry:</p> <form action="{% url …

26.07.2024
Auto-py-to-exe expected str, bytes or os.PathLike object, not NoneType

I'm using auto-py-to-exe to convert my django project in an exe file but I couldn´t: Traceback (most recent call last): File "C:\Users\gerar\AppData\Local\Programs\Python\Python312\Lib\site-packages\auto_py_to_exe\packaging.py", line 132, in package run_pyinstaller(pyinstaller_args[1:]) File "C:\Users\gerar\AppData\Local\Programs\Python\Python312\Lib\site-packages\PyInstaller\__main__.py", line 215, in run run_build(pyi_config, spec_file, **vars(args)) File "C:\Users\gerar\AppData\Local\Programs\Python\Python312\Lib\site-packages\PyInstaller\__main__.py", line 70, …

26.07.2024
Attempting to put data from database onto dashboard in Django

So I am following this guide: https://www.youtube.com/watch?v=_sWgionzDoM and am at around 55 mins so far I have the login stuff all working however I am unable to get the dashboard to show my data from the database. …

26.07.2024
How To Register Model For Admin Page in Core App?

I defined a model (File) in core app(uploader) and tried to register it for admin page but didnt work. then i tried adding core apps name to installed_apps in setting . after that admin page shows model but when i …

26.07.2024
Error while trying to connect Django With ReactNative

I am building a React Native app with Django as the backend. I have set up the login screen in React Native and configured JWT authentication with rest_framework_simplejwt in Django. However, I encounter an error when trying to log in. …

26.07.2024
Heroku DB Connection Limit hit when using Python ThreadPoolExecutor

I have a Django app hosted on Heroku. Some user requests to this app require making long-running queries to external resources. In order to get around the Heroku 30 request timeout, I created a system where these long running queries …

26.07.2024
I can't open server in 0.0.0.0 instead it is working in 127.0.0.1 in while using Docker , Django and Postgres [duplicate]

I am a newbie to this. settings.py file is: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': 'db', 'PORT': 5432, } } Docker file is: FROM python:3 ENV PYTHONUNBUFFERED=1 COPY . /usr/src/app WORKDIR …

26.07.2024
Custom email validation in django form

In my django Account app I have a model for Account class Account(AbstractBaseUser): wallet_value = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) username = models.CharField(max_length=100) email = models.EmailField(max_length=200, unique=True) phone_number = models.CharField(max_length=20) """SOME OTHER REQUIED FIELD""" date_joined = …

26.07.2024
I get an error while running django project [closed]

Manage.py file looks like this: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you …

26.07.2024
Django: Error sending email: (530, b'5.7.0 Authentication Required

I am working on a Django project and get the problem with sending email. This is my code in views.py class ForgotPasswordView(APIView): def get(self, request): return render(request, 'login/forgot_password.html') def post(self, request): email = request.data.get('email') if not email: return Response({"message": …

26.07.2024
How do I send 401 response with custom login_required decorator after Django session expires?

I have a custom login_required decorator that looks like this: def login_required(function): """ Ensure that user is logged in """ def wrap(request, *args, **kwargs): if request.user.is_anonymous: message = { "status": "error", "message": "user login error", "data": "user is not logged …

26.07.2024
KeyError at /verify/ 'order_id'

I have a problem on my store site, when I want to confirm my order, when I click on confirmation on the payment page, it gives this error instead. the error Internal Server Error: /verify/ Traceback (most recent call last): …

26.07.2024
Проблема с бд при запуске вм

Запускаю django проект на вм cloud.ru, в качестве субд postgresql, возникают ошибки с "соединением" c бд psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: database "vitrina" does not exist django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port …

26.07.2024
Django OAuth Toolkit not getting redirect URI

I am using Django OAuth toolkit and using the following code for OAuth implementation import requests from django.http import JsonResponse from django.shortcuts import redirect, render from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from .forms import AuthenticationForm, UserProfileForm …

26.07.2024
How to Display Total Object Count in Wagtail Snippet ViewSet?

I am currently developing a Wagtail project where I use the ModelAdmin to create custom admin interfaces for my models. When using ModelAdmin, the total object count of a model is displayed below the model name in the list view. …

26.07.2024
Django where to store model-level variables

So I have my model: from django.db import models x_default_coordinate = 0 y_default_coordinate = 0 class Model(models.Model): location1 = gis_models.PointField( srid=4326, default=Point(x_default_coordinate, y_default_coordinate) ) location2 = gis_models.PointField( srid=4326, default=Point(x_default_coordinate, y_default_coordinate) ) Where would be an appropriate place to store …

25.07.2024
Sum an aggerated value in Django

I'm trying to achieve the following SQL query in Django: (The table contains the purchases per each day per each location. I want to get the biggest amount of each location, then group them by state to see how much …

25.07.2024
My partner and I are running the same code, but mine is the only one not working on my local server

We are working with Django to perform an asynchronous export task that will populate a CSV with information and then download the CSV automatically to the user's Downloads once a user hits the button 'Start Export.' When it comes time …

25.07.2024
How to implement Django WebSockets?

I'm trying to create a simple Django app, using websockets for sending data. According to the documentation: I've added 'channels' in settings.py's INSTALLED APPS: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "channels", "serial_mouse", ] ASGI_APPLICATION = …

25.07.2024
The debug toolbar is not displayed - docker - django

) I hope you be well... well! I just installed debug toolbar for my django project like allways. but I don't know why doesn't the debug toolbar display?! and I have to add that I'm using docker and it's my …

25.07.2024
Field is filled but still get ValidationError this field is required in

I want to create User using User.objects.create_user and I am using some fields of a form Utilisateurs to do that. The image field and username field from this form are also used to populate a model UserProfile. In views py …

25.07.2024
"No errors found by the IDE" in problems tab

My PyCharm always shows: "No errors found by the IDE" I don't open power save mode. I don't know why. I even reinstalled PyCharm …

25.07.2024
I'm unable to run my django application, but nothing happens

I have a django project and I'm trying to run it with '''python manage.py runserver ''' but nothing really happens. I was working on it just 5 mins before this happens. Now, I'm unable to run anything, my project doesn't …

25.07.2024
How to show user in TokenSerializer dj-rest-auth

I'm trying to return UserSerializer after successful login through dj-rest-auth. I followed the steps that were told in After login the `rest-auth`, how to return more information? which has a similar issue, but it still doesn't show information about …

25.07.2024
Post.objects.all() not working as i wished

Hey I am currently going through the Django tutorials and I am trying to display all of my Post objects in the python shell using from blog.models import Post Post.objects.all() my model is from django.db import models from django.utils …

25.07.2024
ReactJS useParams for Django equivalent?

Django Example # urls.py url = [ path('password_reset/<uidb64>/<token>/', views.password_reset_confirm, name='password_reset_confirm'), ] # views.py def password_reset_confirm(request, id, token): print(id) print(token) pass How would I create an equivalent for ReactJS?? // App.js <Route path='password_reset/:uid/:token' element={<PasswordResetPage/>} /> // PasswordResetPage.js ????

25.07.2024
Custom Django Transform with case statement for casting a string to either int or null

I'm trying to create a custom django lookup as_int so that you can easily compare and order the contents of text fields when they contain only a number, and treat them as NULL when they have the wrong format. For …

25.07.2024
Django errorlist in form Select Valid Choice

The situation is as follows: I am building a form where I fetch data for some fields from an API. I have tried debugging in every possible way, but I cannot understand why the data is not being persisted in …

25.07.2024
Не отображает картинку Django

#HTML <div class="container-promo"> {% for obj in promo_objects %} <img src="{{ promos.img.url }}" class="promo" /> {% endfor %} </div> #Корневой urls.py urlpatterns = [ path('dj-admin/', admin.site.urls), path('', include('customadmin.urls')), path('', include('main.urls')), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #models.py class …

25.07.2024
Django. Почему форма не проходит валидацию?

Проблема в том, что форма не хочет ни при каких условиях проходить валидацию. Т.е. я ее заполняю, а данные не добавляются. Что я делаю не так? Минимально воспроизводимый пример ниже. urls.py from django.urls import path from . import views from …

25.07.2024
How to debug HTTP 400 Bad Request errors in django?

I have an app with React frontend and Django backend. I'm trying to make a POST request from my react client but I get "Bad Request" error. I checked my request url and it matches with my api url. Therefore …

25.07.2024
Validation in DR(Django)

I'm trying create customs validations to my serialiazer but Django just ignore them and return me DRF default errors. {'message': 'Erro ao criar camião', 'data': {'plate': [ErrorDetail(string='This field may not be null.', code='null')]}} That's the answer i get view.py View …

25.07.2024
Django app deployed to under the url subdirectoly

In my server,django and nginx is deployed on ECS fargate and connected to loadbalancer, but URL is transferd by Akamai https://www.example.com/company/playground/* -> https://amazonloadbalancer/* However, there comes a few problem,such as Problem 1 static Access https://www.exmplae.com/company/playground/top will be …

25.07.2024
Django Inline Formset data not saving

I have created an inline formset which works exactly as I planned on the frontend side- However I can't seem to access any of the data- it seems like the …

25.07.2024
Is the batch processing speed of Python slower than that of Java?

I am working on migrating a function implemented in Java Spring Boot to Python Django. I encountered an issue while migrating a function that retrieves a list of keywords through a select query and updates these keywords using an update …

25.07.2024
Payment Gateway Integration with Django

I'm integrating payment gateway APIs in my application (Django). I have written a class PaymentGateway that provides all the methods for all payment related utility. The __init__ initialises the payment gateway client as self.client so that it's available across all …