Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django display crossed tables
I have an event signup page where the participant insert's details upon signing up. Then in a view I am trying to display a listing of their name, title, and details. I am stuck trying to get the details field to display if there were any for the participant. Thank you. ######## Model - Events ######## class Event(models.Model): Event_ID = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) Event_Description = RichTextField(null=True, blank=True) Event_Category = models.ForeignKey(EventCategories, default=1, on_delete=models.CASCADE) Event_participants = models.ManyToManyField(User, blank=True, related_name='events') def __str__(self): return self.Event_Name ######## Model - Events ######## class Submission(models.Model): participant = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="submissions") event = models.ForeignKey(Event, on_delete=models.SET_NULL, null=True) details = models.TextField(null=True, blank=False) id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) def __str__(self): return str(self.event) + ' --- ' + str(self.participant) ######## View ######## def single_event(request, pk): try: event = Event.objects.get(Event_ID=pk) submitted = Submission.objects.filter(event=event) submitted = list(submitted.values('participant','details')) except: return render(request, 'events/single-event.html', {"success":True,}, status=200) context = {'events':Event.objects.filter(Event_ID=pk), 'event':event, 'submitted':submitted} return render(request, 'events/single-event.html', context) ######## Template - single-event.html ######## {% for event in events %} {% for user in event.Event_participants.all %} <tr> <td>{{ user.profile.title }}</td> <td>{{ user.first_name }} {{ user.last_name }}</td> <td>{{ ??????????? }}</td> #This is where i need help. I would like to display 'details' from the Submission model here </tr> {% endfor … -
Django-allauth Third-Party Login Failure
I've got an instance of an application where I'm trying to authenticate users using Google/Github. All the configuration is as documented, the callbacks are as required by the docs, the client ID and secrets are alright. Yet, when receiving the callback, I get shown the following page The callback url i am getting is (with no error msg): http://localhost:8000/accounts/github/login/callback/?code=1216195be45faf4d04af&state=jYUTOFAXVKeiqzpk I do not know what code and state in uri is referring to. The page I am getting redirected to after login attempt I was using version 0.61.1 Downgrading to 0.54.0 and removing allauth.account.middleware.AccountMiddleware middleware solved the problem. But now I can not use LinkedIn Open ID Connect authentication as it is not supported in version 0.54.0. Looking for the solution so that i can use google,github, and linkedin social auth in version 0.61.1 -
Rendering a form with Django using crispy forms
I am rendering a review form on a product page, however the basic rendering is not working. I know I have crispy forms installed correctly as I have used it elsewhere without problem. Can anyone see where I am going wrong? models.py from django.db import models class Review(models.Model): """ Model for review form. Assistance with the positive integer field came from: https://www.geeksforgeeks.org/positiveintegerfield-django-models/ """ stars = models.PositiveIntegerField(choices=( (1, '1 star'), (2, '2 stars'), (3, '3 stars'), (4, '4 stars'), (5, '5 stars'))) body = models.TextField(blank=False) created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ["created_on"] def __str__(self): return f"Review {self.body}" forms.py from django import forms from .models import Review class ReviewForm(forms.ModelForm): """ Review form set up """ class Meta: model = Review fields = ('stars', 'body') views.py from django.shortcuts import render from .models import Review from .forms import ReviewForm from django.contrib import messages def review(request): """ A view to return review """ # reviews = Review.objects.order_by('-created_on').all() # if request.method == 'POST': # review_form = ReviewForm(request.POST) # if review_form.is_valid(): # review_form.instance.name = request.user.username # review_form.save() # review_form = ReviewForm() # messages.add_message(request, messages.SUCCESS, # 'Your review has been successfully posted!') # else: review_form = ReviewForm() context = { 'review_form': review_form, } return render(request, 'product/product_detail.html', context) … -
PyCharm: how to add multiple arguments after manage.py, without paying for Django support?
Running tests for my django app I use ./manage.py test --settings=soardataDJ.settings.testing which runs fine in a terminal window. When I try to run/debug it in PyCharm with a run configuration, it fails if I add anything after "test" in the script parameters, as I did in the screenshot. I see answers on how to add more arguments within PyCharm's Django support plugin. But how do I add arguments without paying for the support? Why can't PyCharm interpret arguments just like my terminal does? Does PyCharm block this to get people to pay? -
django for-loop to calculate laon repyament and interest for a period only displaying the last iteration
Am building a loan system to calculate the repayment period. am having this issue when i run the code it only display the last row. below is my view.py please i need it to display all the rows not only the last row def sveloan(request): if 'userid' in request.session: if request.method == 'POST': balance = 120000 annual_interest_rate = 42 monthly_payment_rate =0.3 monthly_interest_rate = annual_interest_rate / 12 monthly_payment = monthly_payment_rate * balance new_balance= (balance - monthly_payment) * (1 + monthly_interest_rate) for month in range(1, 6): monthly_payment = 20000 balance = (balance - monthly_payment) rateint = (balance / 100 * monthly_interest_rate) mydist = ('Month: %d \n Minimum monthly payment: %g \n Remaining balance: %g \n Minimum Interest payment: %g'\ % (month, round(monthly_payment, 2), round(balance,2), round(rateint, 2))) context={ 'mylist': mydist } return render(request,'loantest.html',context) else: return render(request,'index.html') else: return render(request,'index.html') in my template: {% for p in mylist %} {{p}} {% endfor %} -
Removing a non-nullable Django field with SeparateDatabaseAndState
Let's say I have the following model: class Product(models.Model): name = models.CharField(max_length=128) is_retired = models.BooleanField(default=False) I want to remove the is_retired field. I'm using blue-green deployments to release changes to production so I'm using SeparateDatabaseAndState in my migration. My initial migration to remove the field from the application state is simple: class Migration(migrations.Migration): dependencies = ... operations = [ migrations.SeparateDatabaseAndState( state_operations=[ migrations.RemoveField( model_name="product", name="is_retired", ), ], database_operations=[], ), ] I can successfully run the migration. However, I'm getting the following error when I attempt to create a new product with Product.objects.create(name="Wrench"): self = <django.db.backends.sqlite3.base.SQLiteCursorWrapper object at 0x106bf4050> query = 'INSERT INTO "core_product" ("name") VALUES (?) RETURNING "core_product"."id"' params = ('Wrench',) def execute(self, query, params=None): if params is None: return super().execute(query) # Extract names if params is a mapping, i.e. "pyformat" style is used. param_names = list(params) if isinstance(params, Mapping) else None query = self.convert_query(query, param_names=param_names) > return super().execute(query, params) E django.db.utils.IntegrityError: NOT NULL constraint failed: core_product.is_retired Looks like the INSERT query is failing because the is_retired field is defaulting to null, instead of its correct default of False. I've fixed it by making Product.is_retired nullable before removing it from the state: class Migration(migrations.Migration): dependencies = ... operations = [ migrations.AlterField( … -
Method Not Allowed (GET): /accounts/logout/
there is an issue in Django with the LogoutView. when I put the link 'accounts/logout' it prompts in the cmd "GET /accounts/logout/ HTTP/1.1" 405 0 Method Not Allowed (GET): /accounts/logout/ Method Not Allowed: /accounts/logout/. this is the urlpatterns: urlpatterns = [ path('', include('django.contrib.auth.urls')), path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), path('profile/', showProfile, name='profile'), path('logout/', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'), ] and this is the 'registration/logged_out.html' file content: {% extends "generic_base.html" %} {% block content %} <form method="post" action="{% url 'user:logout' %}"> {% csrf_token %} <button type="submit">Logout</button> </form> {% endblock content %} I saw a lot of ways to fix this. but none of them worked. -
Hosting django with celery and redis
I want to host my django project.But i donot know which hosting site will support celery and redis.Can someone suggest me some website for hosting. -
How do I make my test behave as expected when my model is updated?
My view class MovieUpdateView(UpdateView): model = Movie template_name = "movie_update.html" fields = [ 'movie_name', 'movie_year', 'movie_director', 'movie_rating', 'movie_cover_image' ] def get_success_url(self): return reverse_lazy('movie_detail', kwargs={'pk': self.object.pk}) My test update def setUp(self): self.movie = Movie.objects.create( movie_name='Avengers - Endgame', movie_year= 2019, movie_director='Anthony Russo, Joe Russo', movie_rating=10.0, movie_cover_image = '\movies\images\movies_covers\1f8373201516a4657649d61e97b1f91a_WhvCLCe.jpg' ) def test_movie_update_view(self): self.assertEqual(self.movie.movie_name, 'Avengers - Endgame') movie_update = { 'movie_name' :'Title Updated', 'movie_director' :'New Director', } response = self.client.post( reverse('movie_update', kwargs={'pk': self.movie.pk}), data=movie_update ) self.movie.refresh_from_db() self.assertEqual(self.movie.movie_name, 'Title Updated') File "E:\\Users\\Santiago\\Desktop\\web-projects\\personal_blog\\reviews\\tests.py", line 99, in test_movie_update_view self.assertEqual(self.movie.movie_name, 'Title Updated') AssertionError: 'Avengers - Endgame' != 'Title Updated' - Avengers - Endgame + Title Updated I want to test my MovieUpdateView view based on the UpdateView generic class, but when I try to update through the test, I can't, but manually through the site, everything is fine, when I update it's ok, I'm still starting with the tests, maybe I did something wrong! -
Django Django administration shows more objects then the actual datapoints
I have created a Django model and uploaded some data, around 90 data point. I deleted and uploaded these data points multiple times for testing purposes. I notice my Django admin showing object number much higher then the actual data point present in the database. PeptideSeq object (695) While the total data point I have around 90. Is these normal behavior or is there a way to correct this issue and start the count from zero when you delete all objects. I used Django admin GUI to delete objects. Thanks! -
failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 1
I am using this Dockerfile for my Django + React(Vite) application. Its giving the same error every time when I am running it with docker-compose build GitHub: click here Dockerfile (Django) FROM python:3.10-slim ENV PYTHONUNBUFFERED=1 ENV EMAIL_HOST_USER=email ENV EMAIL_HOST_PASSWORD=password WORKDIR /backend RUN apt-get update && apt-get install -y libpq-dev build-essential RUN pip install -r requirements.txt COPY . . EXPOSE 8000 Dockerfile (React) FROM node:20.6-buster-slim WORKDIR /frontend COPY . . RUN npm install EXPOSE 5173 CMD ["npm", "run", "dev"] docker-compose.yml services: backend: build: ./backend ports: - "8000:8000" volumes: - ./backend:/backend command: bash -c "python manage.py makemigrations && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" frontend: build: ./frontend ports: - "5173:5173" volumes: - ./frontend:/frontend I would appreciate if anyone can help me with solving the issue and make the build successful with dockerizing the whole application. -
Dynamic chat page on django channel
At the moment my chat room functions through 2 simple pages: home.html (chat list) and chat_room.html with input field and connection to a web socket: <!DOCTYPE html> <html> <head> <title>Chat Rooms</title> </head> <body> <div> <h1>Chat Rooms</h1> <ul> {% for room in chat_rooms %} <li><a href="{% url 'chat_room' room.id %}">{{ room.name }}</a></li> {% endfor %} </ul> </div> </body> </html> chat_room.html: <!DOCTYPE html> <html> <head> <title>{{ room.name }}</title> <script> var room_id = {{ room.id }}; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + room_id + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; var sender = data['sender']; var chatMessages = document.querySelector('#messages'); var messageElement = document.createElement('p'); messageElement.innerHTML = '<strong>' + sender + ':</strong> ' + message; chatMessages.appendChild(messageElement); }; function sendMessage() { var messageInputDom = document.querySelector('#id_content'); var message = messageInputDom.value; var sender = "User"; chatSocket.send(JSON.stringify({ 'message': message, 'sender': sender })); messageInputDom.value = ''; } </script> </head> <body> <h1>{{ room.name }}</h1> <div id="messages"> {% for message in messages %} <p><strong>{{ message.sender }}:</strong> {{ message.content }}</p> {% endfor %} </div> <form id="message-form" onsubmit="event.preventDefault(); sendMessage()"> {% csrf_token %} {{ form }} <button type="submit">Send</button> </form> </body> </html> Both pages are received by the user through the view renderer: def home(request): … -
Error occurred during python3.7 pip install mysqlclient
When I tried to use pip install mysqlclient, I encountered the error shown in the screenshot. My Python version is 3.7, and I attempted to install mysqlclient version 2.1.1. I'm using MacOS with Anaconda. Initially, I executed brew install mysql-connector-c and then brew install mysql-client in the macOS terminal. I configured the environment variables according to the official documentation, but I still encountered installation errors later on. I downloaded the compressed source code files, extracted them, and moved them to the site-packages directory of Anaconda. However, when I tried pip install mysqlclient, I encountered the following error. How can I resolve this issue?Installation error I need to resolve these issues before I can install it. -
Phone won't vibrate when receiving firebase push notification
I am sending firebase push notification using the python sdk but I am having an issue. Even though the notifications are being delivered, however it doesn't vibrate the phone. Below is my code. message = messaging.Message( token=token, notification=messaging.Notification( title=title, body=body, ), ) messaging.send(message) I have tried everything, used data message also but no difference. I have also tried some examples on here but still the same thing. I would really appreciate any help. Thank you -
Is Postgres good for long text?
I designed a corporate website with Django and Postgres. I made a blog section for him. I am uploading the contents that I wrote in WordPress to the blog of the new site. But I get an error OperationalError at /en/admin/blog_app/blog/add/ index row size 3144 exceeds btree version 4 maximum 2704 for index "blog_text_key" DETAIL: Index row references tuple (24,1) in relation "blog". HINT: Values larger than 1/3 of a buffer page cannot be indexed. Consider a function index of an MD5 hash of the value, or use full text indexing. I researched about this error and found out that the WordPress content is too big for the Postgres database. What is your suggestion? Should I change the database? Or can the problem be solved? Thank you for your guidance. -
Switching from directory-based URL to subdomain-based URL in ReactJS and Django
I have developed a web application using ReactJS and Django, allowing users to create custom websites. Currently, these websites are stored in the website.com/applicationname directory. However, I want to switch to a subdomain-based URL structure, where each user's custom website is accessible via applicationname.website.com. How can I achieve that? My application is hosted in Heroku. -
Django link table row to detail view with buttons to other views
Hey thanks in advance for any help its always much appropriated. So I found this post on here that help do this and it worked great. So i have my table and when you click a row it goes to the right detail view for that row. What i would also like to do is have a column in the table with a button for delete and one for edit for each row. I was able to add the buttons but it looks like the JS code that makes the rows clickable is overriding the buttons. without the JS code the buttons work. Any guidance on what to look up or helpful terms to make the rows clickable and and buttons not be lumped into it. Sorry I've very new to this in general and especially inexperienced in javascript I tested with the rows not clickable (no javascript) and the buttons that are in work and go to the intended view. I also tried moving data-href="{% url 'detail' part.pk %}"the tag in the html the Table tag. this made a single cell clicked as expected (not what i want) but the buttons become clickable again but don't route properly. I … -
Error: The invalid form control is not focusable
I'm encountering an issue with my Django form where I'm getting the following error messages in my browser console: The invalid form control with name=‘content’ is not focusable. An invalid form control is not focusable. I'm not sure what's causing this error or how to resolve it. I've checked my HTML form and Django view, but I can't seem to find any obvious issues. Btw, I'm kind of new to both CKEditor and Django, excuse me for any "dumb" requests - I just couldn't find a fix to this. Here's a snippet of my HTML form: create.html: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Create Post</title> <link rel="stylesheet" href="{% static 'django_ckeditor_5/dist/styles.css' %}"> </head> <body> <div class="container"> <div class="card"> <h1>Create Post</h1> <form action="" method="POST" enctype="multipart/form-data"> <!-- Other fields, removed for simplicity reasons. --> <div class="input"> {{ form.content }} </div> <button type="submit">Create Post</button> </form> </div> </div> <script src="{% static 'django_ckeditor_5/dist/bundle.js' %}"></script> </body> </html> views.py(only the function required for create.html: def createPost(request): if request.user.is_authenticated: if request.method == "POST": form = forms.CreatePostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.slug = slugify(post.title) post.save() messages.success(request, 'Post created successfully.') return redirect('home') else: messages.error(request, 'Error creating post. … -
How can I deploy a Django project with a pickled model in Railway app?
I would like to deploy my Django project on a Railway app, but the server does not find the pickled model. Although I made sure that the file exists in the github repository that I am deploying, Railway app continuously displays this error: from core import views File "/app/core/views.py", line 37, in binary_clf = joblib.load(os.path.abspath('binary_classifier.pkl')) File "/opt/venv/lib/python3.8/site-packages/joblib/numpy_pickle.py", line 650, in load with open(filename, 'rb') as f: FileNotFoundError: [Errno 2] No such file or directory: '/app/binary_classifier.pkl' The thing is, I don't have any static files except for this pickled ML model. But, I tried including the pickled model in a 'static' folder like it was described here, in which case I got this error: from core import views File "/app/core/views.py", line 37, in binary_clf = joblib.load("static/binary_classifier.pkl") File "/opt/venv/lib/python3.8/site-packages/joblib/numpy_pickle.py", line 650, in load with open(filename, 'rb') as f: FileNotFoundError: [Errno 2] No such file or directory: 'static/binary_classifier.pkl' How are we supposed to deploy Django apps when we have pickled files in it? -
Operational Error in Django: Migrating a Python Web Application to a mariadb database
I am trying to connect a mariadb database that I created in a Linux VM and have my python web application migrate the files over. When I use the python manage.py migrate command, I come across this error: django.db.utils.OperationalError: (2002, "Can't connect to server on '127.0.0.1' (36)") When connecting to the database in my terminal, I end up with this error: mysql -h '127.0.0.1' -P maxdj2k polls_db ERROR 2002 (HY000): Can't connect to server on '127.0.0.1' (36) I'm trying to connect via unix_socket, and have already routed the file to the correct path in my my.cnf file. (/tmp/mysql.sock) is not correct and I'm not entirely sure why it designates that as the path outright. Here is my DATABASES section in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'NAME': 'polls_db', 'USER': 'maxdj2k', 'PASSWORD': 'M24i21F27*', } } I've also included an options parameter under 'PASSWORD' to specify where the actual path for my socket file is. Here is my my.cnf file In linux: # # This group is read both both by the client and the server # use it for options that affect everything # [client-server] socket=/var/lib/mysql/mysql.sock port=3306 # # include all files from the config directory # … -
cannot get token and store it is local storage
I want to while logging user to send post request to http://127.0.0.1:8000/auth/token/login to get auth user token, store it i local storage and then log in user i need this token in local storage for sending post request and getting api response back in my vue cuz now it hardcoded <template> <div> <div v-if="question">{{ question }}</div> <div v-else>Loading...</div> </div> </template> <script> import axios from 'axios'; export default { name: 'QuestionView', props: { slug: { type: String, required: true, }, }, data() { return { question: null }; }, methods: { async getQuestionData() { const endpoint = `http://localhost:8000/api/v1/questions/${this.slug}`; try { const response = await axios.get(endpoint, { headers: { 'Authorization': 'token (here is my token) ' }s }); this.question = response.data; // Assuming your API response is an object containing question information } catch(error) { console.log(error.response); alert(error.response.statusText); } } }, created() { this.getQuestionData(); } } </script> this login.html logging user but doesn't save token {% extends "auth_layout.html" %} {% load widget_tweaks %} <script> async function loginUser(event) { event.preventDefault(); var username = document.getElementById("username").value; var password = document.getElementById("password").value; console.log('a') try { console.log("s") const response = await fetch("http://127.0.0.1:8000/auth/token/login", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username: username, password: password }) }); if … -
I created a Babylon with meshes loaded in a X Django app template, now I need to rotate it by clicking buttons located a dash-board on a y Django app
I'm using a Babylon in a Django project, created a app template that I have few meshes loaded and I did set buttons to rotate the meshes using addEventListener, it are working well when the UI buttons is located in the same HTML template where the canvas is loaded, APP X. My main goal is to have the UI buttons located in a template that will be a dash-board created on a different APP, APP Y on my Django project. When I place the UI buttons in the Y APP (dash-board template) I get the error: Uncaught TypeError: Cannot read properties of undefined (reading 'trackUbosInFrame') at new e (uniformBuffer.ts:256:36) at t.createSceneUniformBuffer (scene.ts:2405:26) at Ar.createSceneUniformBuffer (engine.multiview.ts:203:12) at t._createUbo (scene.ts:1933:41) at new t (scene.ts:1690:14) at HTMLDocument. (jackpot.js?v=:7:17). My JS rotation setup located in my Django JS file inside X APP: javascript function createRotationLogic(mesh, axis, speed) { var rotationAxis; switch (axis) { case "X": rotationAxis = BABYLON.Axis.X; break; case "Y": rotationAxis = BABYLON.Axis.Y; break; case "Z": rotationAxis = BABYLON.Axis.Z; break; default: rotationAxis = BABYLON.Axis.Y; } return function () { scene.unregisterBeforeRender(mesh); scene.registerBeforeRender(function () { mesh.rotate(rotationAxis, speed, BABYLON.Space.LOCAL); }); setTimeout(function () { scene.unregisterBeforeRender(mesh); }, 30000); // Stop after 30 seconds }; } // Function to … -
Javascript request to Python Django not found
I am new to Django and Javascript. Now totally stuck with this error, probably a really small thing, but I can not figure out what can be the problem. I would like to delete a document through my form using Javascript and send it to my Django backend through a request. At the terminal I get this error message: "Not Found: /delete_document/7/ [23/Feb/2024 13:26:53] "DELETE /delete_document/7/ HTTP/1.1" 404 2371" The request color is yellow and it happens as I see, it just can not find my view function. views.py @require_http_methods(['DELETE']) def delete_document(request, document_id): document = get_object_or_404(Document, pk=document_id) document.delete() return JsonResponse({'message': 'Document deleted successfully'}, status=204) urls.py from django.urls import path from . import views # Define namespace app_name = 'advice' urlpatterns = [ ... path('delete_document/<int:document_id>/', views.delete_document, name='delete_document'), ] index.html relevant parts <form id="documentForm" action="" method="post" data-base-action="{% url 'advice:gpt_base' %}"> {% csrf_token %} <input type="hidden" name="firstQuestion" value="True"> <select id="documentSelect" class="form-select" aria-label="Select form"> <option selected>Select a file</option> {% for document in documents %} <option value="{{ document.id }}">{{ document.title }}: {{ document.uploaded_file.url }}</option> {% endfor %} </select> <button type="button" class="btn btn-danger" id="deleteButton">Delete</button> <br> <button type="submit" class="btn btn-primary">Submit</button> </form> <script> document.getElementById('deleteButton').addEventListener('click', function() { var selectedDocumentId = document.getElementById('documentSelect').value; if (selectedDocumentId === 'Select a file') { alert('Please … -
Slow response from Django Rest Framework with annotated queryset
I am using Django Rest Framework and simply trying to filter out objects which have more than 0 related items but as soon as I add in a filter to my annotation that includes a datetime, the response time goes from milliseconds to 90 seconds or so. Here is the code that takes ages:- class EventVenueViewSet(viewsets.ReadOnlyModelViewSet): queryset = EventVenue.objects.annotate( num_slots=models.Count( "eventblock__eventslot", filter=Q(eventblock__status='active') & Q( eventblock__eventslot__start_time__gt=timezone.now() + timedelta(days=2) ) ) ).filter(num_slots__gt=0) If I remove the filter that includes the DateTimeField (start_time)... class EventVenueViewSet(viewsets.ReadOnlyModelViewSet): queryset = EventVenue.objects.annotate( num_slots=models.Count( "eventblock__eventslot", filter=Q(eventblock__status='active') ) ).filter(num_slots__gt=0) it is very fast. But the presence of that datetime filter slows it down to the point of being useless. It's nothing to do with db lookups - it's doing 8 of those so that's fine. The SQL query looks fine and the results are correct - it's just taking soooooo long! Any ideas? -
Could not translate host name "db" to address: Name or service not known
I'm using Django + Docker and when building the image of one of my projects I'm facing problems when running the command: docker-compose run web python manage.py makemigrations error: root@debian:/home/suportenpd1/Documentos/setorT# docker-compose run web python manage.py makemigrations [+] Creating 1/0 ✔ Container setort-db-1 Created 0.0s [+] Running 1/1 ✔ Container setort-db-1 Started 1.1s /usr/local/lib/python3.12/site-packages/django/core/management/commands/makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "db" to address: Name or service not known warnings.warn( No changes detected docker-compose.yml: services: db: image: postgres:15.6 volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=setorT - POSTGRES_USER=setorT - POSTGRES_PASSWORD=setorT@2024$ ports: - "5432:5432" web: build: . command: ["./wait-for-it.sh", "db:5432", "--", "python", "manage.py", "runserver", "0.0.0.0:8000"] volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=setorT - POSTGRES_USER=setorT - POSTGRES_PASSWORD=setorT@2024$ depends_on: - db setting.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': os.environ.get('POSTGRES_NAME'), 'USER': os.environ.get('POSTGRES_USER'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), 'HOST': 'db', 'PORT': 5432, } }