Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to optimize multi column indexing in Django with PostgreSQL
In my application I have this model: class ObservedData(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) unique_id = models.CharField(max_length=128) timestamp = models.DateTimeField() value = models.FloatField(null=True) 90% of my queries are select * from ObservedData where user=<user> AND unique_id=<uid> AND timestamp BETWEEN <date1> AND <date2> This is how I am indexing: class Meta: indexes = [ models.Index(fields=['user', 'unique_id', 'timestamp']), models.Index(fields=['user', 'unique_id']), models.Index(fields=['unique_id', 'timestamp']), ] unique_together = ('user', 'unique_id', 'timestamp') Is this the correct way to do it? I have noticed an increased growth of the database allocated space and I was wondering if this is an overloading or unnecessary overlapping of indexes. -
RetrieveUpdateDestroyAPIView image field when i update a field in django rest framework
i created this api which has a model collection where there is an image field. the list and collection creation part is not a problem but the part of detail especially update has a problem, when I want to update a field I get an error because the image field is not filled in. How can I fix this, I would like if I don't change the image the file will remain the same. model class Collection(models.Model): name = models.CharField(max_length = 255) description = models.TextField() discount = models.PositiveIntegerField(default = 0) image = models.ImageField(upload_to ='collection/') active = models.BooleanField(default = False) def __str__(self): return self.name serializer class CollectionSerializer(serializers.ModelSerializer): class Meta: model = Collection fields = ('id', 'name', 'description', 'discount', 'image', 'active') views class CollectionDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Collection.objects.all() serializer_class = CollectionSerializer url path('collections/', CollectionListCreate.as_view(), name="collections-list"), path('collections/<int:pk>/', CollectionDetail.as_view(), name="collection-detail"), -
DJANGO: How to Display or Access Data from ListView and DetailView on The Same Page / Template?
I want to be able to render, display or access List-view and Detail-view on this same page or Django templates. Below is what I tried so far. Here is a link to where I got a very similar but limited code on how to solve this issue. (DJANGO: How to access data from ListView and DetailView on the same template?). The result when I runserver.py shows a completely blank page with no single error even on the terminal Please Help me resolve this issue. THANKS A LOT models.py class Reports(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=255) name = models.CharField(max_length=255) email = models.EmailField(max_length = 254) phone = models.CharField(max_length=11) address = models.CharField(max_length=255, blank=True, null=True) subject = models.CharField(max_length=255) message = models.TextField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) due = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ('-created',) views.py from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.views.generic.list import ListView from django.views.generic.detail import DetailView from datetime import timezone, tzinfo from . models import Reports # Create your views here. class index(TemplateView): template_name = 'reports_list.html' class ReportsListView(ListView): model = Reports # context_object_name = 'data' def get_queryset(self): return Reports.objects.filter(create_date__lte=timezone.now()).order_by('-create_date') class Detail(DetailView): model = Reports def get_context_data(self, **kwargs): context … -
Django postgres psycopg2: ImproperlyConfigure even though module installed
I am using Django for the first time but have used PostgreSQL previously. I am trying to follow the official Django tutorial to set up with a database. I have followed everything but I get an error when using the command "python manage.py migrate" that psycopg2 is not found even though I have it installed.Traceback (most recent call last): File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/db/backends/postgresql/base.py", line 24, in <module> import psycopg2 as Database ModuleNotFoundError: No module named 'psycopg2' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/alexanderverheecke/Documents/GitHub/mysite/manage.py", line 22, in <module> main() File "/Users/alexanderverheecke/Documents/GitHub/mysite/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/apps/registry.py", line 116, in populate app_config.import_models() File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/apps/config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/Users/alexanderverheecke/Library/Python/3.9/lib/python/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import … -
Django rest filter by serializermethodfield with custom filter
As declared in question title, i got task to filter results by field not presented in model but calculated by serializer. Here is the view code: class RecipeViewSet(ModelViewSet): queryset = Recipe.objects.all() permission_classes = [IsAdminOrAuthorOrReadOnly, ] serializer_class = RecipeInSerializer pagination_class = LimitPageNumberPagination filter_backends = [DjangoFilterBackend] filterset_fields = ['tags', ] filter_class = RecipeFilter Serializer: class RecipeOutSerializer(serializers.ModelSerializer): tags = ManyRelatedField(child_relation=TagSerializer()) author = CustomUserSerializer() ingredients = serializers.SerializerMethodField() is_favorite = serializers.SerializerMethodField() is_in_shopping_cart = serializers.SerializerMethodField() class Meta: fields = '__all__' model = Recipe def get_ingredients(self, obj): ingredients = IngredientAmount.objects.filter(recipe=obj) return GetIngredientSerializer(ingredients, many=True).data def get_is_favorite(self, obj): request = self.context.get("request") if request.user.is_anonymous: return False return Favorite.objects.filter(recipe=obj, user=request.user).exists() def get_is_in_shopping_cart(self, obj): request = self.context.get("request") if not request or request.user.is_anonymous: return False return ShoppingCart.objects.filter(recipe=obj, user=request.user).exists() And custom filter code: class RecipeFilter(rest_framework.FilterSet): tags = ModelMultipleChoiceFilter( field_name='tags__slug', to_field_name="slug", queryset=Tag.objects.all() ) favorite = BooleanFilter(field_name='is_favorite', method='filter_favorite') def filter_favorite(self, queryset, name, value): return queryset.filter(is_favorite__exact=True) class Meta: model = Recipe fields = ['tags', ] Target is is_favorited field that return boolean value. I tried writing func in custom filter class that return queryset but didnt work, neither documentation helped me with examples. Hope for your help. -
render a word document download as a response using django rest framework
I used the python-docx module to create a word document. In my views.py file. I want to be able to render or trigger a download of this word document as a response using django rest framework. Most of the solutions have a file already saved in the database, I need a solution where the file is being created dynamically like with the python-docx module. How can this be done? I tried using custom renderers but I'm not sure how to go about it -
How to find the location of a news article (i.e. the news is related to which place) from a news website?
I am making a news app that aggregates news from different news websites. I have successfully made the UI and the scrapping part is also done. But I am unable to get the location of the news article wherefrom the news is based. Suppose, the news is of Masachuttes from the USA Today. So, I need to extract the location - Masachuttes from the news website - USA Today. This is my problem description. So, I need your help in this regard. I tried the Geo-Location API but it did not work as it only asks for the user permission so it went in vain. As of now, I have no idea how to do it. Expectation is that I could scrape the loation of a particular news article of a news website. -
Override_settings not working at runtime with pytest DJANGO
In my settings.py file inside my django proyect I added a new constant ALLOW_SELF_REGISTRATION, that constant will allow or not a url in the proyect in the way: if settings.ALLOW_SELF_REGISTRATION: urlpatterns += [path( "self_registration/", views.self_registration_client, name="self_registration" ),] My problem is that I need to test when that constant is set to False in that case the url should not be added and a test to that url must raise a NoReverseMatch. I found that the override_settings is not working as expected, I do differents attemps to see if any could work, but no. Until now i tried: def test_constant_on_change_edit_urls_on_false(client): with override_settings(ALLOW_SELF_REGISTRATION=False): with pytest.raises(NoReverseMatch): response = client.get(reverse('profiles:self_registration')) If I print the value of the constant in that test is set to True (as default) and not False as it should by the override_settings context manager. I need a way to override that constant at runtime inside the tests so I can test that functionality. Also tried: @override_settings(ALLOW_SELF_REGISTRATION=False) def test_constant_on_change_edit_urls_on_false(client): with pytest.raises(NoReverseMatch): response = client.get(reverse('profiles:self_registration')) But also failed. There is any way to change that value at runtime during the tests? -
How connect Django with SQLServer 2008 r2
I tried connect Django with SQL Server 2008 r2 SP3. But when y run "python manage.py migrate" i get "django.db.utils.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Sintaxis incorrecta cerca de 'OFFSET'. (102) (SQLExecDirectW)")" My Settings: DATABASES = { "default": { "ENGINE": "mssql", "NAME": "xx", "USER": "xx", "PASSWORD": "xx", "HOST": "xx", "PORT": "1433", "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server", }, }, } Version SQL Server: Microsoft SQL Server 2008 R2 (SP3) - 10.50.6000.34 (X64) Aug 19 2014 12:21:34 Copyright (c) Microsoft Corporation Express Edition with Advanced Services (64-bit) on Windows NT 6.3 (Build 19045: ) (Hypervisor) Version Python: 3.8.10 Version Django: 3.1.7 -
Create template with two forms
Good morning, I'm new to python and I have a problem with data entry. Some of the data is in a form and other data is selected and stored in another table. How can I load the two forms that are related in the same Template? I will appreciate if you can help me. Thank you forms.py from cProfile import label from dataclasses import fields from datetime import date, datetime from email.policy import default import imp from mailbox import NoSuchMailboxError from random import choices from django import forms import datetime,django.utils from django.contrib.admin.widgets import AdminTimeWidget, AutocompleteSelect from django.contrib.admin import widgets from .models import Detalle_remito, Personas, Recursos, Remito from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms.widgets import NumberInput OPERADOR=( ('Fabiana', 'Fabiana'), ('Ma. Laura', 'Ma. Laura'), ('Adrian', 'Adrian'), ('Martín', 'Martín'), ('Andres', 'Andres'), ) USO=( ('INTERNO', 'INTERNO. Uso dentro de la Universidad'), ('EXTERNO', 'EXTERNO. Uso fuera de la Universidad') ) DIA_SEMANA=( ( '0', 'Lunes'), ( '1', 'Martes'), ( '2', 'Miercoles'), ( '3', 'Jueves'), ( '4', 'Viernes'), ( '5', 'Sabado'), ) class DetalleRemitoForm(forms.ModelForm): class Meta: model = Detalle_remito fields = {'id_remito', 'fecha', 'hora_retiro', 'hora_devolucion', 'id_recurso', 'estado'} class formularionuevo (forms.Form): uso=forms.ChoiceField(label="Uso del equipamiento ",choices=USO, widget=forms.widgets.RadioSelect(), initial='INTERNO') fecha_retiro=forms.DateField(label="Fecha retiro ",widget=NumberInput(attrs={'type': 'date'}), initial = datetime.date.today()) hora_retiro=forms.TimeField(label="Hora … -
How to define my aggregate function in django orm
I want to define an aggregate function, but I don't understand the example in Django document toally. -
Save zip to FileField django
I have a view that create two csv and my goal is to zip them and add to a model.FileField zip = zipfile.ZipFile('myzip.zip','w') zip.writestr('file1.csv', file1.getvalue()) zip.writestr('file2.csv', file2.getvalue()) I have tried this, the zip is upload but when I download it I have the error 'the archive is damaged or unknown format' Mymodel.objects.create(zip = File(open('myzip.zip','rb')) -
I can't use the command ' python manage.py makemigrations' in django VSC
I already did 'python manage.py migrations'. Now i want to create '0001_inital.py' file in migrations with the code 'python manage.py makemigrations'. Firstly this is my models.py; from django.db import models class Room(models.Model): #host = #topic = name = models.CharField(max_Length=200) description = models.Textfield(null=True, blank = True) #participants = updated = models.DateTimeField(auto_now = True) created = models.DateTimeField(auto_now_add = True) def __str__(self): return str(self.name) And here is the some of the errors that when i write 'python manage.py makemigrations'. File "", line 1006, in _find_and_load_unlocked File "", line 688, in _load_unlocked File "", line 883, in exec_module File "", line 241, in _call_with_frames_removed File "C:\Users\c.aktel\OneDrive\Masaüstü\laan\base\models.py", line 5, in class Room(models.Model): File "C:\Users\c.aktel\OneDrive\Masaüstü\laan\base\models.py", line 8, in Room name = models.CharField(max_Length=200) File "C:\Users\c.aktel\OneDrive\Masaüstü\laan\new_env\lib\site-packages\django\db\models\fields_init_.py", line 1121, in init super().init(*args, **kwargs) TypeError: Field.init() got an unexpected keyword argument 'max_Length' -
Converting two complex dictionary list to a dictionary
suppose I have two dictionary list below: all=[] lis1={ 'code':'matata', 'commandes':[ { 'date':'12-10-22', 'content':[ { 'article':'Article1', 'designation':'Designe1', 'quantity':5 } ] } ] } lis2={ 'code':'fropm', 'commandes':[ { 'date':'04-08-21', 'content':[ { 'article':'Article2', 'designation':'Designe2', 'quantity':3 } ] } ] } Now I add at list level my two dictionaries all.append(list1) all.append(liste2) to replace the [..] in {..} for a single list we can do all[0] But after adding the two lists and then doing all[0] we only have the first list whose [..] whose square brackets are replaced by {..} I would like to have this rendering { {...}, {...} } Is this possible?? -
python django app deploy error in cpanel?
I can't solve Cpanel 503 Error. If anyone can solve this problem please Help me. For hosting Django project I have tried many time with many python versions but showing same error -
How to use Filterset and paginateion in ApiView?
I am trying to use PageNumberPagination and FilterSet in APIView. But I have an error below in my code. object of type 'ListSerializer' has no len() How to implement this? Here are the code: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' class MyFilter(filters.FilterSet): class Meta: model = MyModel fields = '__all__' class MyAPIView(views.APIView, PageNumberPagination): def get(self, request, *args, **kwargs): filterset = MyFilter(request.query_params, queryset=MyModel.objects.all()) if not filterset.is_valid(): raise ValidationError(filterset.errors) serializer = MySerializer(instance=filterset.qs, many=True) paginate_queryset = self.paginate_queryset(serializer, request, view=self) return Response(paginate_queryset.data) Django 3.2.6 django-filter 22.1 djangorestframework 3.12.4 Python 3.8 -
What is the difference between Django timezone now and the built-in one?
I've just noticed this: >>> import datetime >>> from django.utils import timezone >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).microseconds 999989 >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).seconds 86399 >>> 24*60*60 86400 >>> (datetime.datetime.now(tz=datetime.timezone.utc) - timezone.now()).days -1 >>> timezone.now() datetime.datetime(2022, 11, 17, 13, 1, 36, 913132, tzinfo=<UTC>) >>> datetime.datetime.now(tz=datetime.timezone.utc) datetime.datetime(2022, 11, 17, 13, 1, 41, 913958, tzinfo=datetime.timezone.utc) How do both options to get the current time with the UTC "timezone" differ? Why is the difference a positive number of seconds, but exactly negative one day? Can I replace timezone.now() by datetime.datetime.now(tz=datetime.timezone.utc)? -
In Celery Task, MyModel matching query does not exist
I am trying to run my django application using docker which involves celery. I am able to set everything on local and it works perfectly fine. However, when I run it docker, and my task gets executed, it throws me the following error: myapp.models.mymodel.DoesNotExist: mymodel matching query does not exist. I am particularly new to celery and docker so not sure what am I doing wrong. Celery is set up correctly, I have made sure of that. Following are the broker_url and backend: CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'django-db' This is my docker-compose.yml file: version: "3.8" services: redis: image: redis:alpine container_name: rz01 ports: - "6379:6379" networks: - npm-nw - braythonweb-network braythonweb: build: . command: > sh -c "python manage.py makemigrations && python manage.py migrate && gunicorn braython.wsgi:application -b 0.0.0.0:8000 --workers=1 --timeout 10000" volumes: - .:/code ports: - "8000:8000" restart: unless-stopped env_file: .env networks: - npm-nw - braythonweb-network celery: build: . restart: always container_name: cl01 command: celery -A braython worker -l info depends_on: - redis networks: - npm-nw - braythonweb-network networks: braythonweb-network: npm-nw: external: false I have tried few things from different stackoverflow posts like apply_async. I have also made sure that my model existed. -
I want create comment section that can only logged in users can use but i have this problem
cannot unpack non-iterable bool object profile = Profile.objects.get(Profile.user == request.user) this is my models.py in account app and blog app: class Profile(models.Model): STATUS_CHOICES = ( ('manager', 'مدیر'), ('developer', 'توسعهدهنده'), ('designer', 'طراح پروژه'), ) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) bio = models.CharField(max_length=50, blank=True) task = models.CharField(choices=STATUS_CHOICES, max_length=20, blank=True, null=True, default=None) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to='users/photos/%Y/%m/%d/', blank=True) def __str__(self): return f'{self.user.get_full_name()}' class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='user_comments') body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) and this is my views.py for comments: def post_detail(request, year, month, day, slug): post = get_object_or_404(Post, slug=slug, status='published', publish__year=year, publish__month=month, publish__day=day) tags = Tag.objects.all() tagsList = [] for tag in post.tags.get_queryset(): tagsList.append(tag.name) profile = Profile.objects.get(Profile.user == request.user) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.profile = profile new_comment.post = post new_comment.save() return redirect('post_detail', slug=post.slug) else: comment_form = CommentForm() post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:3] return render(request, 'blog/post/detail.html', {'post': post, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form, 'similar_posts': similar_posts, 'tagsList': tagsList, 'tags': tags}) Is there any solution for this problem? -
The view main.views.view didn't return an HttpResponse object. It returned None instead
I have a upload function. But when I try to upload the file. I get this error: ValueError at /controlepunt140 The view main.views.view didn't return an HttpResponse object. It returned None instead. So this is the template:" <form class="form-inline" role="form" action="/controlepunt140" method="POST" enctype="multipart/form-data"> <div class="form-group"> {% csrf_token %} {{ form }} <button type="submit" name="form_excel" onclick="test()" class="btn btn-warning"> Upload! </button> </div> <div class="form-outline"> <div class="form-group"> <textarea class="inline-txtarea form-control" id="" cols="65" rows="25"> {{content_excel}}</textarea > </div> </div> </form> and views.py: def post(self, request): submitted_form = ExcelForm(request.POST, request.FILES) content_excel = '' if request.POST.get('form_excel') is not None: if submitted_form.is_valid() and request.POST: excel_file = request.FILES["upload_file"] excel_file.save() wb = openpyxl.load_workbook(excel_file) worksheet = wb['Sheet1'] print(worksheet) excel_data = list() content_excel = excel_data return render(request, "main/controle_punt140.html", { 'form': ExcelForm(), "content_excel": content_excel, }) return render(request, "main/controle_punt140.html", { "form": submitted_form, "content_excel": content_excel, }) and forms.py: class ExcelForm(forms.Form): upload_file = forms.FileField() Question: how resolve this? -
Get component schema for a specific endpoint with drf spectacular
I want to use drf spectacular to get the component schema of a specific endpoint. For example, if I have the endpoint api\articles that supports POST with two CharFields field1 and field2. I then want another endpoint such as api\articles\schema\post where I could use GET to return an autogenerated JSON like this: { "type": "object", "description": "description of article", "properties": { "field1": { "type": "string", "maxLength": 255 }, "field2": { "type": "string", "maxLength": 255 } -
Django & gunicorn in docker-compose consume alot of resources ( Memory - CPU )
I have 3 containers that share the same code (WSGI - ASGI - Celery) Everything works fine but when I check the docker stats docker stats I found that WSGI consumes a lot more resources than the rest The containers are deployed on DigitalOcean droplet without domain just IP docker-compose.yml version: "3.7" services: db: build: context: . dockerfile: ./docker/database/master/Dockerfile restart: always ports: - ... volumes: - ... environment: - ... replica: build: context: . dockerfile: ./docker/database/replica/Dockerfile restart: always environment: - ... replica1: build: context: . dockerfile: ./docker/database/replica/Dockerfile restart: always environment: - ... backend: restart: unless-stopped build: context: . dockerfile: ./docker/backend/Dockerfile_wsgi entrypoint: /app/docker/backend/wsgi_entrypoint.sh volumes: - static_volume:/app/backend/server/django_static - static_image:/app/backend/server/media expose: - 8000 environment: - ... depends_on: - db links: - redis - db - cere asgiserver: restart: always build: context: . dockerfile: ./docker/backend/Dockerfile entrypoint: /app/docker/backend/asgi.entrypoint.sh volumes: - static_volume:/app/backend/server/django_static - static_image:/app/backend/server/media environment: - ... depends_on: - db links: - redis - db - cere expose: - 9000 redis: image: "redis:alpine" restart: unless-stopped command: redis-server /usr/local/etc/redis/redis.conf volumes: - ./docker/redis/redis.conf:/usr/local/etc/redis/redis.conf expose: - 6379 cere: image: "redis:alpine" restart: unless-stopped command: redis-server /usr/local/etc/redis/redis.conf volumes: - ./docker/redis/redis_1.conf:/usr/local/etc/redis/redis.conf expose: - 6380 celery: restart: unless-stopped build: context: . dockerfile: ./docker/backend/Dockerfile_celery entrypoint: /app/docker/backend/celery-entrypoint.sh environment: - ... depends_on: - asgiserver - backend … -
creating an admin user using django
I was creating an admin user account, when it got to create password my keys stopped working!!I even rebooted my system and started from top boom it happened again tried to create password on django admin user account? -
PostgreSQL queries slow after upgrading django project from 2.X to 3.2
We just upgraded our project from Django 2.x to 3.2 and are experiencing queries that are much slower. We are not quite sure what is handled differently, but if we EXPLAIN ANALYZE some query on a local database before the migration and one after, we see very different results with regards to time. Example Query: SELECT SUM("journals_journalmutation"."amount") AS "sum" FROM "journals_journalmutation" INNER JOIN "ledger_ledgeraccount" ON ("journals_journalmutation"."ledger_account_id" = "ledger_ledgeraccount"."id") INNER JOIN "journals_purchasejournalentryline" ON ("journals_journalmutation"."purchase_journal_entry_line_id" = "journals_purchasejournalentryline"."id") WHERE ("ledger_ledgeraccount"."master_ledger_account_id" IN (1611, 1612, 1613) AND "journals_purchasejournalentryline"."journal_entry_id" = 370464 AND "journals_journalmutation"."credit_debit" = 'DEBIT' AND "ledger_ledgeraccount"."master_ledger_account_id" IN (1611, 1612, 1613)) Here is the result of EXPLAIN ANALYZE on that query on the database before migration: Aggregate (cost=19.83..19.84 rows=1 width=32) (actual time=0.008..0.008 rows=1 loops=1) -> Nested Loop (cost=1.28..19.82 rows=1 width=6) (actual time=0.006..0.007 rows=0 loops=1) -> Nested Loop (cost=0.85..17.70 rows=4 width=10) (actual time=0.006..0.006 rows=0 loops=1) -> Index Scan using journals_purchasejournalentryline_ea982348 on journals_purchasejournalentryline (cost=0.42..8.44 rows=1 width=4) (actual time=0.005..0.006 rows=0 loops=1) Index Cond: (journal_entry_id = 370464) -> Index Scan using pjel_idx on journals_journalmutation (cost=0.43..9.25 rows=1 width=14) (never executed) Index Cond: (purchase_journal_entry_line_id = journals_purchasejournalentryline.id) Filter: ((credit_debit)::text = 'DEBIT'::text) -> Index Scan using ledger_ledgeraccount_pkey on ledger_ledgeraccount (cost=0.42..0.53 rows=1 width=4) (never executed) Index Cond: (id = journals_journalmutation.ledger_account_id) Filter: ((master_ledger_account_id = ANY ('{1611,1612,1613}'::integer[])) … -
Docker Mailhog with Docker django error: [Errno 111] Connection refused
I have 2 containers running through docker-compose, one with Django, the other with Mailhog. But when I send_mail through Django python manage.py runserver, it is possible to send, if i run a docker-compose up when I send email this error is returned: [Errno 111] Connection refused My docker-compose is: services: mailhog: image: mailhog/mailhog logging: driver: 'none' # disable saving logs ports: - 1025:1025 # smtp server - 8025:8025 # web ui networks: - my_net api: build: . container_name: my_api command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/src ports: - '8000:8000' env_file: - '.env' depends_on: - mailhog networks: - my_net networks: my_net: My env file is: EMAIL_HOST = '0.0.0.0' EMAIL_PORT = '1025' EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' What should I do?