Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a DjangoModel Form with a model that contains FKs and M2M relationships
I have seen posts that talk about this scenario separately but they seem to be very old, using old documentation. I am here wondering if there is a new fix. Also I'm relatively new to django and they have been quite confusing. I would like to create a Form that takes in the relevant information to be able to create a parking space object. This is the Forms.py class AddParkingSpace(forms.ModelForm): class Meta: model = ParkingSpace fields = [ "__all__"] exclude = ["reviews","seller_account"] # widgets to include all the fields like fields not in the specified model above (explained below) widgets = { } I have excluded the reviews because these will be added to the parking space object as and when a review is submitted. The seller_account will be added to the parking space in the view(backend). Using this form I would like to be able to access each field separately using the Django syntax {{formname.fieldname}} in the template. So I can style/position it how I desire I Models.py class ParkingSpace(models.Model): name = models.CharField(max_length=50,blank=False) # name of a parking space description = models.TextField(blank=False)# the description of a parking space image = models.ImageField(null=True,upload_to="images/parking_spaces") #The image of a parking space price = … -
how to fix 504 Gateway Time-out on AWS ECS in my Django app?
Explanation I am hosting Django app on ECS on AWS. I am using nginx and gunicorn on production It happens very often that I see status 499 and then 504 with timeout error. Below yuo can see my container logs. During that time backend does not respond for several minutes and after restart it changes status to 200 again. 2023/09/06 14:42:52 [error] 9#9: *1348 upstream timed out (110: Operation timed out) while reading response header from upstream, client: 10.0.10.112, server: , request: "GET /api/tasks/logs/8b9ad2d4-b63a-4782-83c2-940764c04eb1/ HTTP/1.1", upstream: "http://127.0.0.1:8000/api/tasks/logs/8b9ad2d4-b63a-4782-88c2-940764u04eb1/", host: "admin.myapp.com" 10.0.11.207 - - [06/Sep/2023:14:42:48 +0000] "GET /admin HTTP/1.1" 499 0 "-" "ELB-HealthChecker/2.0" "-" 10.0.10.112 - - [06/Sep/2023:14:42:49 +0000] "GET /admin HTTP/1.1" 504 167 "-" "ELB-HealthChecker/2.0" "-" My CPU and memory usage never exceeds 20% (usually it is around 8-12%). Only few people are using this application. My health check settings look like this: nginx.config upstream myapp_backend { server ${APP_HOST}:8000; } server { listen 80; location / { proxy_pass http://myapp_backend; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 200M; } location /static/ { alias /home/app/web/static/; } } Dockerfile-nginx FROM public.ecr.aws/nginx/nginx:1.24-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /nginx.conf.template CMD ["/bin/sh" , "-c" , "envsubst '$APP_HOST' < /nginx.conf.template > /etc/nginx/conf.d/default.conf && exec nginx -g … -
Django Module Not Found Error - No module named todocompressor
I was working on todo project and was trying to add a scss to my project. So i installed django_compressor package but i can't seem to figure out how to add the scss file to my html page.Can someone provide me any tips I added 'compressor' to installed apps i added all these to settings STATICFILES_FINDERS = 'compressor.finders.CompressorFinder' COMPRESS_PRECOMPILERS = ( ('text/x-scss', 'django_libsass.SassCompiler'), ) and this infront of html template {% load compress %} {% compress css %} {% endcompress %} I added the bootsrap source files to static folder in my project -
Django User Auth
Django all auth I have problem with mymodels, I wanna create User auth with AbstractUser from django.contrib.auth.models but when I makemigrations the terminal show these error. see the image on top ^ this my models.py file code : from django.db import models from django.contrib.auth.models import AbstractUser from users.managers import CustomUserManager class User(AbstractUser): email = models.EmailField(unique=True, max_length=255) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=255, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.user.username}'s profile" Succes for makemigrations and migrate models django -
DRF and FactoryBoy for testing - testing viewset logic - saving factory to database?
I'm currently working on testing a Django Rest Framework (DRF) application using Factory Boy. In my setup, I have a straightforward model, serializer, and viewset (specifically, a ModelViewSet). As part of my testing process, I'm making some modifications to the logic within the ModelViewSet, particularly by customizing the perform_create method. And it is the part what I want to test - viewset logic. However, while using Factory Boy, I've observed that the perform_create method is not being triggered by Factory Boy's default behavior. I'd appreciate any suggestions or insights on how to ensure that perform_create is invoked when using Factory Boy in my tests. Maybe I should call perform_create manually? Alternatively, if you think it might be more appropriate to explore other testing frameworks or methods for this scenario, or if using the simple APIClient for testing would be a better approach, I'd welcome your guidance on that as well. Thank you, and have a wonderful day! -
iis django deployment error when the iis try to download file
PermissionError: [WinError 5] Access is denied: 'C:\Windows\system32\config\systemprofile/.paddleocr' StdOut: Trying to load best model from weights/id_model_v5 Loading...... Loading model from weights/id_model_v5/best The model has been loaded successfully download https://paddleocr.bj.bcebos.com/PP-OCRv3/multilingual/Multilingual_PP-OCRv3_det_infer.tar to C:\Windows\system32\config\systemprofile/.paddleocr/whl\det\ml\Multilingual_PP-OCRv3_det_infer\Multilingual_PP-OCRv3_det_infer.tar Trying to load best model from weights/id_model_v5 StdErr: [2023-09-06 05:47:15,095] [ WARNING] init.py:546 - Matplotlib created a temporary cache directory at C:\Windows\TEMP\matplotlib-9k3m2kjz because the default path (C:\Windows\system32\config\systemprofile.matplotlib) is not a writable directory; it is highly recommended to set the MPLCONFIGDIR environment variable to a writable directory, in particular to speed up the import of Matplotlib and to better support multiprocessing. i expect to see the server runing -
Ajax Show button
I have an issue with my button when I press to show more it adds the same images that I have already on the page. I was trying different functionality, even know why this is happening really need advice from people who has more experience in coding. I am making a project by using Python javascript and Django. it looks like my data-page attribute isn't being updated when you click the Read More button. So I did that but still, the same if somebody can help me will be appreciated. view.py: from django.shortcuts import render, redirect, reverse, get_object_or_404 from django.contrib import messages from django.contrib.auth.decorators import login_required from django.db.models import Q from django.db.models.functions import Lower from .models import Jewellery, Category from .forms import ProductForm from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.http import JsonResponse # Create your views here. import math # def get_total_image_count(): # # Use the count() method to get the total count of images # return total_image_count # total_images = get_total_image_count() # print(f'Total Images: {total_images}') def all_jewelleries(request): """ A view to show all products, including sorting and search queries """ query = None categories = None sort = None direction = None jewelleries = Jewellery.objects.all() total_images = jewelleries.count() … -
Why Django DRF Response is not working right on live server with 204 content status?
I have a delete_rider view that works fine with @action(detail=False, methods=['DELETE'], permission_classes=[IsAuthenticated]) def delete_rider(self, request): """Delete the authenticated rider if the user's rider.""" user = request.user # Check if the user is a rider (role 2) if user.role == 2: user.delete() # Delete the user return Response(status=status.HTTP_204_NO_CONTENT) else: return Response({"message": "User is not a rider (role 2)."}, status=status.HTTP_400_BAD_REQUEST) on local server. But on live server it gets stuck in request and after some seconds it times out although delete the user but time out. HttpResponse instead of Response worked. What am I missing here? @action(detail=False, methods=['DELETE'], permission_classes=[IsAuthenticated]) def delete_rider(self, request): """Delete the authenticated rider if the user's rider.""" user = request.user # Check if the user is a rider (role 2) if user.role == 2: user.delete() # Delete the user return HttpResponse(status=status.HTTP_204_NO_CONTENT) else: return Response({"message": "User is not a rider (role 2)."}, status=status.HTTP_400_BAD_REQUEST) -
Django Project Connect to Google Cloud SQL
I host Database and Django Application separately Server. I have a Google Cloud SQL (PostgreSQL) but I tried many ways to configure Database as Django document DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': '[Your-Cloud-SQL-Public-IP]', 'USER': '[YOUR-USERNAME]', 'PASSWORD': '[YOUR-PASSWORD]', 'NAME': '[YOUR-DATABASE]', } } by filling it with my credential but cannot connect got error like this: line 729, in connect raise ex.with_traceback(None) django.db.utils.OperationalError: connection failed: could not receive data from server: Socket is not connected (0x00002749/10057) could not send SSL negotiation packet: Socket is not connected (0x00002749/10057) Expert please help me to make it works. I am looking the guideline to configure Django project with Google Cloud SQL. -
How can I limit the records that appear in the django forms select2?
The problem is that it loads more than 50.000 articles in the selector and the page takes a long time to load. query_set = Article.objects.all() self.fields["national_foreign_articles"].queryset = query_set.exclude(national_agency=self.instance) self.fields["national_foreign_articles"].widget.attrs["class"] = "select2" I need this or similar -
Docker Compose's integration for ECS and ACI will be retired in November 2023
I try to deploy a docker django container to the Azure cloud. And so I login in with: docker login azure. And I am logged in. SO I am in the local directory wheren the application files are stored. And I try to build the docker image: docker compose -f docker-compose-deploy.yml build But then I get every time this message: (env) PS C:\repos\DWL_backend_Rachid> docker compose -f docker-compose-deploy.yml build Docker Compose's integration for ECS and ACI will be retired in November 2023. Learn more: https://docs.docker.com/go/compose-ecs-eol/ And I can not build or run. I searched for this of course. But I can not find any thying how to tackle this. And I also updated the docker desktop. Question: how to handle the message: ```Docker Compose's integration for ECS and ACI will be retired in November 2023. Learn more: https://docs.docker.com/go/compose-ecs-eol/ ```` -
How can I log in in an API with Python?
Good afternoon, everyone, I have a question about how I can log into an API through Python code. I want to "identify" the API login so that the user can see which invoices are pending, i.e. a user logs in with my Django login, which, at the same time, has to log in to the API. Once logged into the api, I want the api to return the documents that have an id with its assigned tag. I attach below the function that I have made and that connects me to the database. This function does not return any information from the API because of what I said, because first you have to identify which user is logged in. @login_required def f_facturaspendientes(request): # URL de la API a la que deseas conectarte url = 'http://host.docker.internal/api/v4/documents/' try: response = requests.get(url) if response.status_code == 200: # La solicitud fue exitosa, puedes procesar la respuesta aquí data = response.json() # Hacer algo con los datos de la API # Devuelve una respuesta JSON con los datos procesados return JsonResponse({'message': 'Solicitud exitosa', 'data': data}) else: # La solicitud no fue exitosa, maneja el error aquí si es necesario return JsonResponse({'error': 'Error en la solicitud', … -
Django Admin - Add New Object Redirect to List Instead of Object?
I'm using a custom Admin User model with all fields being shown on the ADD NEW USER form. When clicking SAVE under ADD NEW USER in my Admin interface, it opens the continue editing page instead of going back to the User list. How can I redirect back to the list while still keeping the built in Django validation for saving? -
AWS Postgresql DB not accepting TCP/IP
i want to deploy my django app on the free AWS platform and i'm having issues connecting the app to AWS postgresql DB, I've setup the DB and django setting file like this AWS SETTINGS Endpoint RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "ecommerce.cxu8zbmvaiut.us-east-1.rds.amazonaws.com" (172.31.34.128), port 5432 failed: Connection timed out Is the server running on that host and accepting TCP/IP connections? warnings.warn( port '5432' name 'commerce' user: 'hello-world' password '******' Publicly accessible 'Yes' DJANGO SETTING FILE DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'commerce', 'USER':config('user), 'PASSWORD': config('password'), 'HOST': config('endpoint'), 'PORT': config('port') } } but when i try to make migrations from my AWS console i get this error message RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': connection to server at "ecommerce.cxu8zbmvaiut.us-east-1.rds.amazonaws.com" (172.31.34.128), port 5432 failed: Connection timed out Is the server running on that host and accepting TCP/IP connections? warnings.warn( can anyone help out thanks -
Django - Annotate count of related objects
Let's assume the next models: class A: b=models.ForeignKey("B") class B: pass I want to annotate queryset of B count of related A objects def annotate_count_a(b_queryset): /* ..... */ How to do? Thanks -
Algolia: define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
Requested setting ALGOLIA, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I've tried: 1 export DJANGO_SETTINGS_MODULE=Website.settings (I checked to be Website.settings when I turned on the server(python manage.py runserver)) 2 to specify PYTHONPATH 3 I've also checked the API KEYS to be valid and have the right installed apps in INSTALLED_APPS INSTALLED_APPS=[ ... "algoliasearch_django", ... ] ALGOLIA = { 'APPLICATION_ID': ' ', 'API_KEY': ' ' } chatgpt And still couldn't figure it out. TO REPLICATE THE PROBLEM: SIMPLE DJANGO PROJECT + ALGOLIA Thanks! -
create users base on other a certain user
I want to create a django project like stock management systems for multiple companies, but I want the staff of a specific company can only have access their company profile and stocks. case study like multi school management system, if a school register, their staffs can have full access to their school app. I tried a OneToMany relationship but I don't Know how to do the Auth and restrict the users to only there domain. -
'function' object has no attribute '__func__' issue with graphene django
TypeError: UserProcessOptionsNode fields cannot be resolved. 'function' object has no attribute '__func__' This issue is caused when I upgrade graphene-django from 2.15.0 to 3.1.5. -
Problems connecting a Rest API to my Django project
I'm having a lot of problems connecting a REST API, in this case the Mayan Edms one, with my Django application. I want to make all the documents that arrive or simply that are in my mayan, I can see it in my Django interface. Can anyone give me a hand? Below, I attach the code of the function that I have tried to do and that does not work. @login_required def f_facturaspendientes(request): # URL de la API a la que deseas conectarte url = 'http://localhost/api/v4/documents/' try: # Realiza una solicitud GET a la API response = requests.get(url) # Comprueba si la solicitud fue exitosa (código de estado 200) if response.status_code == 200: # Convierte la respuesta JSON en un diccionario de Python datos = response.json() return datos else: # Si la solicitud no fue exitosa, maneja el error según tu necesidad return {"error": "La solicitud a la API falló"} except requests.exceptions.RequestException as e: # Maneja excepciones de solicitudes HTTP (por ejemplo, problemas de red) return {"error": f"Error de solicitud: {e}"} I need to know how to connect so I can see things in my mayan in my Django GUI. Thank you. -
How to solve the 404 error for Django rest Api deployed to IIS
Hello everyone I need some help for Django rest api deployment related. I deployed django rest api on IIS server its worked perfect for that day in another day I checked again same deployed URL its showing 404 page not found like that so can any one help for this issue. I need solution for this error or I need any proper tutorial for deploying Django rest api on IIS server side. Thanks. -
Celery worker processes django task but does not execute
I am a beginner. I have a django project in which I am trying to add a functionality where I send a welcome email when a user signs up. I am using the django development server on 127.0.0.1:8000, a celery worker, and a docker container running redis on redis://127.0.0.1:6379. When I sign up a test user, no welcome email prints to the console (current email config is EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' so that would be the expected result. Contents of my tasks.py @shared_task def send_welcome_email(user_email): print("send welcome email started") subject = 'Welcome to My Website' message = 'Thank you for registering at My Website!' from_email = 'noreply@mywebsite.com' recipient_list = [user_email] print(f"Sending email to {user_email}") send_mail(subject, message, from_email, recipient_list) print("Email sent") I have done necessary configuration such as adding the celery app to my project's init.py, adding Celery settings (broker URL and result backend), a celery.py file in my django project, and I have also confirmed that Celery is connected to my redis database. When I check the status of the task with Flower, I see that a Celery worker has received the task, and it is listed under 'Processed', but does not move to Failed or Succeeded, and as stated, no … -
Trying to fix a Django error calling a Module that doesn't exist for an SQLite Database
I'm designing a website using Django and SQLite, using Models to parse information between the database and the front-end. I'm encountering errors that are limiting my developmental process, as I'll explain below. For reference, here's the code that I'm using with my Models: # Internal = 0, Derived = 1. class Grade(models.Model): name = models.CharField(max_length=100, default="null") # classPage = models.ManyToManyField(classPage, related_name="_set") amegrade = models.CharField(max_length=10, default="null") description = models.CharField(max_length=500, default="null") type = models.BooleanField(default=1) class Student(models.Model): studentName = models.CharField(max_length=50, default="null") age = models.CharField(default="13", max_length=3) house = models.CharField(max_length=10, default="null") bday = models.CharField(default="null", max_length=50) class classPage(models.Model): teacher = models.CharField(max_length=50, default="null") # classStudents = models.ManyToManyField(Student, related_name="_set") class timetableItem(models.Model): name = models.CharField(max_length=50, default="null") timeStart = models.CharField(max_length=50, default="null") timeEnd = models.CharField(max_length=50, default="null") class dailyTimetable(models.Model): timetableItems = models.ManyToManyField(to=timetableItem) class weeklyTimetable(models.Model): monday = models.OneToOneField(to=dailyTimetable, on_delete=models.CASCADE) class sideViewButton(models.Model): name = models.CharField(max_length=100, default="null") directory = models.URLField(max_length=100, default="null") class Notice(models.Model): title = models.CharField(max_length=50, default="null") description = models.CharField(max_length=10000, default="null") I'm using Models in my Database to store information. That works all well and dandy, but I'm trying to migrate new changes to the project using python3 manage.py migrate, and I'm getting thrown an error that "TypeError: fromisoformat: argument must be str". I use Google Bard to help diagnose the issues and the over … -
I can't getting input fields in blog page but i written code for input fields in html page
I can't getting input fields in blog page but i written code for input fields in html page First i added some reactions you may see in my page it is saved in my sql server, i want to input fields to react for my post and those reactions(comments) should be displayed in below for my blog but input fields are hidden i am unable to see it, with my knowledge i written this below code but i can't getting input fields like email and comment box, i'm trying to display those reaction in same page index.html ''' forms.py from django import forms from . models import user_response class userfield(forms.ModelForm): class Meta: model = user_response fields='__all__' models.py from django.db import models # Create your models here. class user_response(models.Model): userName = models.CharField(max_length=15) userEmail = models.EmailField() message = models.TextField() def __str__(self): return self.userName, self.userEmail urls.py from django.urls import path from . import views urlpatterns = [ path('userdata/',views.userdata, name='userdata'), ] views.py from django.http import HttpResponse from django.shortcuts import redirect, render from . models import user_response from . forms import userfield # Create your views here. def userdata(request): if request.method == 'POST': form = userfield(request.POST) if form.is_valid(): form.save() return redirect(request, '../templates/index.html') else: form = … -
Django Snippets/Updating Primary Key
I have a client that requested (after launch) to start their records at a very large number (3,000,000). The model itself has at least 10 relationships/reverse relationships all through FK, established with "on_delete=CASCADE". Originally I was working with this snippet: https://djangosnippets.org/snippets/10619/, which gave quite a few errors. After some formatting (removing %s formatting for easier to read f-string formatting), the script ran but gave the dreaded: Cannot delete or update a parent row: a foreign key constraint fails. I am looking at any sort of way to get the 100 or so records (and their respective relationships) to update accordingly. I have already updated the MYSQL database to start numbering from the last record + 3,000,000 so that any resulting scripts should not result in a collision keeping the PK restraints. I believe there used to be a way to do this via a simple model.objects.all().update(id=F('id')+3000000), but this also has failed in Django 4.2. Any help is appreciated. d -
htmx isn't call in meta widgets
I'm trying to validate a field in a crispy form in Django using htmx: class Foo( forms.ModelForm ): id = forms.CharField( label='Id', disabled="true") # WORKING local_amount = forms.DecimalField( label='Local Amount', required=True, max_digits=10, decimal_places=2, widget=forms.TextInput(attrs={ 'type': 'number', # Use 'number' type for numeric input 'hx-get': reverse_lazy('check_amount'), 'hx-trigger': 'change', # Trigger the request when the value changes }) ) class Meta: model = Cost_schedule_org_unit fields = ['id','cost_schedule', 'local_amount',.....] # NOT WORKING IN THIS WAY widgets = { 'local_amount' : forms.TextInput(attrs={ 'type': 'number', # Use 'number' type for numeric input 'hx-get': reverse_lazy('check_amount'), 'hx-trigger': 'change', }) } The htmx call is working in the first way but not on the second way?