Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to clean a model after the related models inline forms have been saved in the admin site in the transaction start?
I have such models: class Advert(CreatedUpdatedMixin): ... use_pickup = models.BooleanField( verbose_name=_('pickup'), default=False, ) use_nova_post = models.BooleanField( verbose_name=_('nova post'), default=False, ) use_courier = models.BooleanField( verbose_name=_('courier'), default=True, ) ... def clean(self): if not any([self.use_pickup, self.use_nova_post, self.use_courier]): raise ValidationError( _('One of next field must be true: use_pickup, use_nova_post, use_courier.'), 'invalid_use_fields', ) if self.use_pickup and getattr(self, 'address', None) is None: raise ValidationError( _('Address must be specified if use_pickup field is true.'), 'empty_address', ) class AdvertAddress(Address): advert = models.OneToOneField( verbose_name=_('advert'), to=Advert, on_delete=models.CASCADE, related_name='address', ) When I save a Advert model in the admin site, there is error from this part code: if self.use_pickup and getattr(self, 'address', None) is None: raise ValidationError( _('Address must be specified if use_pickup field is true.'), 'empty_address', ) because admin form check clear before saving advert and advert address. The only thing that came to mind was to modify changeform_view. Maybe there exists some another way. -
Django cant change default language
I have developed a web application in 2 languages, where users can change in-between them using the UI, and it all works fine, the language is changing. What I cant setup is the default language that is working when the application is opened for the first time. This is my settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'az' USE_I18N = True LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGES = [ ('az', 'Azerbaijani'), ('en', 'English'), ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('', include('main.urls')), # Include your app's URLs ) if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Djoser cant access extra fileds in registration
I am using Djoser and i have role field in user model as i integrated the role i cant signup a user. it works with without role but role field is import to update. in api body { "first_name":"test", "last_name":"data", "email":"testdata@gmail.com", "phone_number":"9876543210", "password":"pass@123", "re_password":"pass@123", "role":2 } i get thisAttributeError at /api/users/ 'dict' object has no attribute 'role' in social auth i cant get the first and last name My Serializers ` from .models import User from rest_framework import serializers from djoser.serializers import UserCreateSerializer class SignupSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ("first_name", "last_name", "email", "password", "role") extra_kwargs = { "first_name": {"required": True, "allow_blank": False}, "last_name": {"required": False, "allow_blank": True}, "email": {"required": True, "allow_blank": False}, "password": {"required": True, "allow_blank": False, "min_length": 6}, "role": {"required": False, "allow_blank": True}, } class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("id", "first_name", "last_name", "email", "role") ` **Djoser and social auth settings ** ` DJOSER = { "SERIALIZERS": { "user_create": "accounts.serializers.SignupSerializer", "current_user": "accounts.serializers.UserSerializer", "user": "accounts.serializers.UserSerializer", }, "PASSWORD_RESET_CONFIRM_URL": "password-reset/{uid}/{token}", # "USERNAME_RESET_CONFIRM_URL": "username-reset/{uid}/{token}", "SEND_ACTIVATION_EMAIL": True, "ACTIVATION_URL": "activation/{uid}/{token}", "USER_CREATE_PASSWORD_RETYPE": False, "PASSWORD_RESET_CONFIRM_RETYPE": True, "LOGOUT_ON_PASSWORD_CHANGE": True, "PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND": True, "TOKEN_MODEL": None, "SOCIAL_AUTH_TOKEN_STRATEGY": "djoser.social.token.jwt.TokenStrategy", "SOCIAL_AUTH_ALLOWED_REDIRECT_URIS": config("REDIRECT_URLS").split(","), } SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config("GOOGLE_CLIENT_ID") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config("GOOGLE_SECRET") SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", "openid", ] SOCIAL_AUTH_GOOGLE_OAUTH2_EXTRA_DATA … -
How to translate content with variables in Django Template?
I just took over an old project using Django 1.8 + Python 2.7. I need to refactor a feature where I have to retrieve different information based on different host information and display it on the page. Additionally, I need to internationalize this displayed information. my code looks something like this: <div> {% blocktrans with site_name=request.site.site_name %} welcome to {{ site_name }} {% endblocktrans %} </div> I want to translate this entire content, but I found that only the variable 'site_name' was translated eg:site_name = "stackoverflow" I want to translate welcome to stackoverflow, not stockoverflow. Can you tell me how to solve this problem? thanks!!!! -
Django Deploy Nginx Bad Gateway no such file or directory
So, I've been struggling for the past week to deploy my Django project on my VPS server (domains.co.za). After all this time, I managed to figure out a few things on my own. My server runs on AlmaLinux 9, and I'm connecting via the IP address 41.76.110.165. Here's what I've done so far: Gunicorn Configuration (/etc/systemd/system/gunicorn.service) [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=marco Group=www-data WorkingDirectory=/home/marco/domestic_voicelogging ExecStart=/home/marco/domestic_voicelogging/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ domestic_voicelogging.wsgi:application [Install] WantedBy=multi-user.target Gunicorn Socket (/etc/systemd/system/gunicorn.socket) [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock SocketUser=marco SocketGroup=www-data SocketMode=0660 [Install] WantedBy=sockets.target Nginx Configuration (/etc/nginx/sites-available/myproject) server { listen 80; server_name 41.76.110.165; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/marco/domestic_voicelogging; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I'm encountering this error: 2024/07/09 10:11:40 [crit] 21042#21042: *8 connect() to unix:/opt/domestic_voicelogging.sock failed (2: No such file or directory) while connecting to upstream, client: 41.13.200.12, server: mydjangoserver.co.za, request: "GET / HTTP/1.1", upstream: "http://unix:/opt/domestic_voicelogging.sock:/", host: "41.76.110.165" Current Socket Status (venv) [marco@mydjangoserver domestic_voicelogging]$ ls -l /run/gunicorn.sock srw-rw-rw-. 1 marco www-data 0 Jul 9 09:37 /run/gunicorn.sock (venv) [marco@mydjangoserver domestic_voicelogging]$ I'm puzzled why the directory path in the error message shows /opt/domestic_voicelogging.sock instead of /run/gunicorn.sock. I've checked everything seems … -
Unknown command: 'collectstatic' after overriding StaticFIlesConfig
I followed the instructions on https://docs.djangoproject.com/en/5.0/ref/contrib/staticfiles/#s-customizing-the-ignored-pattern-list to override the ignore_patterns in my static files. Here are my steps: Created a new app app_staticfiles. in app_staticfiles.apps.py, this code: from django.contrib.staticfiles.apps import StaticFilesConfig class AppStaticfilesConfig(StaticFilesConfig): name = 'app_staticfiles' ignore_patterns = ["CVS", ".*", "*~", "*.map", "*.min.css", "*.min.js", "*.scss"] In original staticfiles, there is the management directory that has the following commands collectstatic and findstatic. Django project settings.py modified: INSTALLED_APPS = [ # ... # 'django.contrib.staticfiles', 'app_staticfiles', ] Now when I run collectstatic, I get error Unknown command. Obviously since I have commented out the original app from Django. Is there a way for this to run as-is without having to copy the management commands from original place to the overwriting app? -
django model add scheme to url field if not represented
I have a model with a URL field in my Django project. I want to ensure that a scheme (like https://) is added to the URL if it doesn't exist. from django.db import models class MyModel(models.Model): url = models.URLField() I've tried using the clean, save, clean_fields methods, but none of them seem to work. I feel there should be a straightforward way to accomplish this, but I can't find one. Any suggestions or best practices would be greatly appreciated. Thanks! -
Why does Request.build_absolute_uri lead to localhost instead of the real domain?
I have a website deployed on Nginx and built on Django. The Request.build_absolute_uri link there for some reason leads not to the real domain and ip which is attached to it, but to localhost:8080 of Waitress/gunicorn on which the app is running. Why? I tried Request.build_absolute_uri and request._current_scheme_host both lead to the localhost. Now, temporarily I just use the direct path like "domain.com", but it is not a very convinient decision. Could you please let me know how to solve it? -
My form validation in Django seems okay but it is not working
Template of the form Form.py models.py Views.py seetings.py Everything seems to be okay but the form is not storing data to the database, the form.py , views.py, models.py, settings.py .. For me everything seems okay but when i submit the form it doesn't store data into the database -
push reload or invoke javascript function from server
I have Django + React + uwsgi application. Uwsgi access to the database. Now I want to reload Django(React) web applicataion triggered by Database is changed. For example User open the web application Administrator use mysql command on server Insert into mytable(name) values("data") User's application will be reloaded or some javascript function be called. It's something like push reload from server. In my idea. Web application access the database to check the value is altered in every seconds. However It requires to access API every seconds. (And at most it has the one seconds delay, or requires too much api access) Is this a good practice ? Is there any good method for this purpose?? -
Sucessful compilation but browser can't access site
I am doing my first project with Django and React. Whenever i run npm run dev the project compiles succesfully. But once I go to the browser, it says that the site can't be reached and that localhost rejected the conection. I tried running PORT=8001 npm run dev but the same keeps happening. I have read other options about changing the webpack.config.js file, like this devServer: { contentBase: path.join(__dirname, 'dist'), compress: true, port: 3000, open: true, }, but my project has no dist folder -
Inspecting celery tasks in django
Is importing celery app and calling control.inspect() the best way for inspecting active tasks? Also, I'm using RabbitMQ as my broker. from core.celery import app def get_running_tasks(request): i = app.control.inspect() i.active() # retrieving active tasks -
How do I ensure that only certain domain names can sign up using django authentication tools?
I want to restrict my signups to certain colleges while building a product using django. I want to do something similar to how Autodesk approves its users. I have a list of the domain names. I tried manually allowing sign-ups for certain domain names. This was done in the code itself and not connected to a database of domain names. I saw an answer linking a model but for a blocklist. I need to do the opposite. -
Learning Django without DTL
I just finished my second React course and become more confident with it by creating a several web application. Now my plan is to go fullstack, I decided to start learning Django because am kinda good with python, the course is really straight forward and well explained, the problem started with lectures talking about DTL (Django Template Language), i ended up getting lost and bored because am already familiar with front-end library, is there any course that focuses on backend development side of django ? I tried to follow with those lectures and did understand but it conflict with my React knowledge -
Save DateTime in mysql database based on Asia/Tehran time zone
I have a Django project where I have used a DateTime field in one of its models. In this database field, I want to save the date and time of this moment. Also, my database is mysql type and on the server. First of all I have set Django settings. LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Tehran' USE_I18N = True USE_TZ = True Also, to be sure, I edited the database model as follows. class Register(models.Model): card = models.ForeignKey(Card, on_delete=models.CASCADE, db_index=True) member = models.ForeignKey('member.Members', on_delete=models.CASCADE, db_index=True) field = models.ForeignKey(Field, on_delete=models.CASCADE) start_date = models.DateTimeField(null=True, blank=True) end_date = models.DateTimeField(null=True, blank=True) session_count = models.IntegerField(null=True, blank=True) is_active = models.BooleanField(default=True) def save(self, *args, **kwargs): tehran_tz = pytz.timezone('Asia/Tehran') if self.start_date: self.start_date = self.start_date.astimezone(tehran_tz) if self.end_date: self.end_date = self.end_date.astimezone(tehran_tz) super(Register, self).save(*args, **kwargs) I have also set the time zone in the database using the following command. SET GLOBAL time_zone = 'Asia/Tehran'; SET time_zone = 'Asia/Tehran'; The result of executing the following command in the database is as follows. SHOW VARIABLES LIKE 'time_zone'; The interesting thing is that when I print the time and date in the terminal, it shows correctly, but when I save it in the database, it is saved as UTC. -
parser add_mutually_exclusive_group - how can I set a default value?
We use Python and Django for our websites. We set a test command that adds to the default Django test command: from django.core.management.commands import test class Command(test.Command): def add_arguments(self, parser): super().add_arguments(parser=parser) group = parser.add_argument_group('language options', 'These arguments are mutually exclusive. Default: --test-default-languages') language_group = group.add_mutually_exclusive_group() language_group.add_argument( "--test-all-languages", action="store_true", help="Run tests for all languages, and don't skip languages.", ) language_group.add_argument( "--test-default-languages", action="store_true", help="Run tests for default languages (English, French, Hebrew + randomly select one more language or none).", ) language_group.add_argument( "--test-only-english", action="store_true", help="Run tests for only English.", ) # ... Now, in the models we have this code: class SiteDiscoverRunner(DiscoverRunner): def __init__(self, *args, **kwargs): # ... super().__init__(*args, **kwargs) self.test_all_languages = kwargs.get('test_all_languages', False) self.test_default_languages = kwargs.get('test_default_languages', False) self.test_only_english = kwargs.get('test_only_english', False) if ((self.test_all_languages is False) and (self.test_only_english is False)): self.test_default_languages = True Tests must be run with one of the above command line arguments or none. If none then the test_default_languages value should be true. I would like to know if the parser can make self.test_default_languages True if none of the 3 arguments is given, so I can remove the command self.test_default_languages = True in the model? I searched and didn't find out how to do it. -
How to catch Django's OperationalError exception thrown in django-main-thread
I use a Postgres 16.2 database in my Django 5.0 project configured like so: ### settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DB_NAME', 'USER': 'DB_USER', 'PASSWORD': 'DB_PASS', 'HOST': 'DB_HOST', 'PORT': '5432', } } It works well, no issue here. However, when I simulate a database outage (typically, I'm stopping the database service on my computer), I end up with an exception that I cannot manage to catch: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/base.py", line 275, in ensure_connection self.connect() File "/usr/local/lib/python3.12/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/base.py", line 256, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/db/backends/postgresql/base.py", line 277, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError: could not translate host name "api-db" to address: Temporary failure in name resolution The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.12/threading.py", line 1073, in _bootstrap_inner self.run() File "/usr/local/lib/python3.12/threading.py", line 1010, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.12/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.12/site-packages/django/core/management/commands/runserver.py", line 136, in inner_run self.check_migrations() File "/usr/local/lib/python3.12/site-packages/django/core/management/base.py", line … -
Python (Django) project structure for web system
I going to satart to develop a web system using Python (Django) in the backend, but i want to start with fhe correct project structure or project tree. I will divide the project in two sections (Frontend and Backend), into the backend i pretend to add the templates and static files. What is the correct structure for a python (Django) web project? -
I have a problem in reverse function Django
i'm learning django and I spent a long time to let reverse() work but I failed. I don't want to use {% url ''....%}. this is the models.py I created 2 tables Category & Product from django.db import models class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name this is urls.py from django.urls import path from . import views app_name = 'myapp' urlpatterns = [ path('product' , views.all_products , name= 'products'), path('product/<int:product_id>/', views.product_detail, name='product_detail'), ] this is views.py from django.shortcuts import render, get_object_or_404 from django.urls import reverse , reverse_lazy from .models import Product def all_products(request): products = Product.objects.all() context = { 'products' : products } return render(request , 'index.html',context) def product_detail(request, product_id): product = get_object_or_404(Product, id=product_id) detail_url = reverse_lazy ('myapp:product_detail', args = [product_id]) return render(request, 'product_detail.html', { 'product': product, 'detail_url': detail_url, }) this is index.html The problem is reverse function when I click on achor tag i didn't opens the detail_page <!DOCTYPE html> <html> <head> <title>Product Detail</title> </head> <body> {% for product in products%} <a href="{% url 'myapp:product_detail' product.id%}" onclick="show()"><h1>{{ product.name }}</h1></a> {% endfor%} <!-- --> </body> </html> this is product_detail.html {{product}} type … -
MultiValueDictKeyError at /api/products/
I'm encountering a MultiValueDictKeyError in my Django project when trying to access the API at http://127.0.0.1:8000/api/products/. The error occurs on this line: category = self.request.GET['category']. Here is my view: class ProductList(generics.ListCreateAPIView): queryset = models.Product.objects.all() serializer_class = serializers.ProductListSerializer def get_queryset(self): qs = super().get_queryset() category = self.request.GET['category'] category = models.Product.objects.get(category) qs = qs.filter(category=category) return qs My Product model is defined as follows: class Product(models.Model): category = models.ForeignKey(ProductCategory, on_delete=models.SET_NULL, null=True, related_name='product_in_category') retailer = models.ForeignKey(Retailer, on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=200) detail = models.CharField(max_length=200, null=True) price = models.FloatField() def __str__(self) -> str: return self.title Here is my serializer: class ProductListSerializer(serializers.ModelSerializer): productreview = serializers.StringRelatedField(many=True, read_only=True) class Meta: model = models.Product fields = ['id', 'category', 'retailer', 'title', 'detail', 'price', 'productreview'] def __init__(self, *args, **kwargs): super(ProductListSerializer, self).__init__(*args, **kwargs) I am trying to call a list of products according to the product category from my React frontend, but I keep encountering the MultiValueDictKeyError. I tried using GET.get and various other approaches but haven't been able to resolve the issue. Here is the error traceback: Request Method: GET Request URL: http://127.0.0.1:8000/api/products/ Django Version: 4.2.13 Exception Type: MultiValueDictKeyError Exception Value: 'category' How can I fix this error and properly filter the products by category? -
Why does Swagger duplicate my documentation in endpoints using {format}?
I am creating documentation with Swagger in a Django project, I don't understand why it duplicates some endpoints by adding {format} at first sight they are the same endpoints: for example GET /profile/v1/{id} there is also a version with {format} settings.py: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ), "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework_simplejwt.authentication.JWTAuthentication", ] } on views.py: class ProfileDetailView(APIView): permission_classes = [FullProfilePermissionGroup] def get_object(self, pk): try: return Profile.objects.get(pk=pk) except Profile.DoesNotExist: raise Http404 @swagger_auto_schema( operation_description="Retrieve a single profile by ID.", responses={ 200: openapi.Response( description="Profile retrieved successfully", schema=ProfileSerializer ), 404: openapi.Response(description="Profile not found"), }, produces=["application/json"] ) def get(self, request, pk): profile = self.get_object(pk) serializer = ProfileSerializer(profile) return Response(serializer.data) It is not a blocking problem, but I would like to eliminate it, can you help me? Thanks -
Maintaining product data across AJAX requests for invoice creation
I'm working on a Django application for creating invoices. Users can add multiple products to an invoice before submitting it. I'm facing an issue where the product data isn't being maintained between AJAX requests when creating the invoice (this is my supposition). My current setup: 1- I have an add_product view that handles AJAX requests to add products. 2- I'm storing the added products in the session: if 'products' not in request.session: request.session['products'] = [] request.session['products'].append(product_details) request.session.modified = True 3- I have a create_invoice view that should use these stored products: products = request.session.get('products', []) if not products: return JsonResponse({'error': 'No products added'}, status=400) # Create invoice with products... 4- I'm making AJAX calls from the frontend to add products and create the invoice. The problem: When I call the create_invoice view, request.session.get('products', []) is always empty, even though I've added products. -
django stripe on deploy Error verifying webhook signature
i have django react app, i added stripe to django, react build files i set on static django i have tested on localhost with stripe cli is working fine but after i deploy my django project on vercel and create endpoint on https://dashboard.stripe.com/test/webhooks to handle stripe webhooks event i get error https://i.sstatic.net/51zS8MrH.png, (after i create new webhook endpoint i set new webhook_secret_key so problem not in webhook_secret_key) I searched on the Internet how to fix it, they advised to set on payload request.body.decode('utf-8) or request.data but nothing helped my code (this code on localhost is working fine but on deployed server i get error, for deployed server i changed webhook_secret_key to new secret_webhook_key from https://dashboard.stripe.com/test/webhooks and site_url to deployed server) from django.conf import settings from django.http import HttpResponse from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import DepositHistory from django.views.decorators.csrf import csrf_exempt from decimal import Decimal import stripe from rest_framework.decorators import api_view from usersAuth.models import AppUser stripe.api_key = settings.STRIPE_SECRET_KEY class StripeCheckoutView(APIView): def post(self, request): if self.request.user.is_authenticated: try: checkout_session = stripe.checkout.Session.create( line_items=[ { 'price': 'price_1PY4d6GKlfpQfnx9EFKpod75', 'quantity': 1, }, ], metadata={"user": f'{self.request.user}'}, mode='payment', success_url=settings.SITE_URL + '/?success=true&session_id={CHECKOUT_SESSION_ID}', cancel_url=settings.SITE_URL + '/?canceled=true', ) return Response({"url": checkout_session.url}) except: return Response( … -
django using aggregate() and distinct() together
I have a filterset that has following attributes: dosFromGte = filters.DateFilter(method="search_by_dos_from_gte", lookup_expr="gte") dosToLte = filters.DateFilter(method="search_by_dos_from_lte", lookup_expr="lte") # One of these methods: def search_by_dos_from_lte(self, queryset: Chart, name: str, value: str) -> Chart: return queryset.annotate(max_dos=Min("diagnosis__dos_from")).filter(max_dos__lte=value) # using annotate and aggregate Min(). I need to run few annotations and then only fetch distinct ids. queryset = self.filter_queryset(self.get_queryset().exclude(state__in=repo_exclude)) queryset = queryset.annotate( ChartId=F("chart_id"), MemberId=F("member__member_id"), ChartStatus=F("state__name"), ).values( "ChartId", "MemberId", "MemberName", "ChartStatus" ).distinct("id") When I apply these filters ?clientId=11&project=56&dosFromGte=2023-08-17&dosToLte=2023-08-19 this tries to run Min() and then distinct on ids. This gives NotImplementedError("aggregate() + distinct(fields) not implemented.") So I tried to work around a bit and queryset.values( "id", "ChartId", "MemberId", "MemberName", "ChartStatus" ) # remove duplicate charts based on pk, i.e. id df = df.drop_duplicates('id') df = df.drop('id', axis=1) which kind of felt like a hack and dirty work around. Is there a cleaner ORM way to do it? -
How to filter Categories and Subcategories using listview in Django
I have Category and SubCategory models in Django and I need to get descendant of Category model in 'class SubCategoriesListView' `models.py class Category(models.Model): name = models.CharField('Категория', max_length=150, default='name') url = models.SlugField(max_length=160, unique=True) class SubCategory(models.Model): name = models.CharField('SubCategory', max_length=150, default=True) url = models.SlugField(max_length=160, unique=True) image = models.ImageField('Pic', upload_to='img', null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) How to filter subcategories linked with category model? (I have to use detailview later, so solution must be with the using ListView model) `views.py class CategoriesListView(ListView): model = Category queryset = Category.objects.all() template_name = 'catalog/category_list.html' context_object_name = 'category_list' class SubCategoriesListView(Category, ListView): model = SubCategory queryset = SubCategory.objects.all() template_name = 'catalog/subcategory_list.html' context_object_name = 'subcategory_list'`