Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I write a Django ORM query that returns a match based on an intersection of lists?
If I have, for example: from django.contrib.postgres.fields import JSONField class MyModel(models.Model): data = JSONField() GIVEN a model instance obj1, where data == ['apple', 'banana', 'orange'] GIVEN a model instance obj2, where data == ['banana', 'orange'] GIVEN a model instance obj3, where data == ['apple'] How can I write an ORM query that returns all model instances whose data includes at least one item from a given list, ['apple', 'strawberry']? It should return obj1 and obj2 because both of those objects include 'apple', despite the argument including 'strawberry', which is not represented in any of the objects. -
Should I really use React/Vue with Django instead of Alpine.js?
I have a page where user creates an instance. An instance has a bunch of characteristics and foreign key to product (which has category and name itself) and all the fields are static - just stylized selects and inputs, but there is just a change event handler which saves any changes in session so that user could go back to editing With Alpine.js I replaced two selects (where user chooses product category and product name) with a single button - "select a product" and after clicking a modal appears with options depending on the step - either category or name, once both category and name are selected a card with this product appears and a button turns into "change a product". Everything worked just fine until I started filling this with initial values from draft form, so that you need to combine Django {% if %} with Alpine.js x-if which caused flickering. Is it really worth it to switch React/Vue + DRF or am I missing something? Considering my codebase it would be painful, but pretty much possible. The only negative thing that stops me from doing it right now is Django features I don't want to rewrite in JS … -
How can I convert the last / any row of a model / queryset into one dictionary?
Good day! I have a table model. I plan to take one row from it - one set of elements. To place it in an object - a dictionary. How can I place the last or first or a specific one row from a model / queryset into a dictionary - not in a list of dictionary sets, but in one dictionary. One row of a model / queryset into one dictionary? How can I convert the last / any row of a model / queryset into one dictionary? -
React + React Native + Django AllAuth
I'm running a Django server which has API's I consume through a React Native and React applications. I want it to work for Google, Facebook, Instagram and Twitter. For this question I want to focus on the React Application and Google Authentication and hopefully it will be repeatable for my other social options. My React Application manages to login just fine for Google It returns field called "credentials". My thinking was I can send this to Django AllAuth, which would call google and then return user data, which I can create a Django User and sign in and if that user already has an account it just login. Some features on the API require users to have loggedin. I have the same client_id for my React and Django app. Does AllAuth do this already ? How do I work with it? When I try forward my 'credentials' (the one google returned to my React) to auth/google/ I get a 403. I would imagine I don't have to do this pragmatically as this seems like a pretty common setup . Any guidance on how I can make these React and Django AllAuth work together would be great. -
Django Sitemap issue: GSC fail to fetch sitemap with error "Sitemap could not be read"
I created sitemap using django default sitemap from django.contrib.sitemaps.views import sitemap Here is the complete process #urls.py sitemaps = { 'static': StaticViewSitemap, 'blogpost_detail': BlogSitemap, 'portfolio-details': PortfolioSitemap, # Add others like 'posts': PostSitemap if needed } path( "sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.sitemap") I can access sitemap at https://dataguru.cc/sitemap.xml but upon submission i get "Sitemap could not be read", I have tried these few things so far Reduced the size of sitemap to single link to verify Added rule in cloudflare to bypass compression and cache for /sitemap.xml since its created by django but still verified syntex of xml using online tools Used static sitemap.xml from template view changed the name from sitemap.xml to site_map.xml So far nothing is working so i would appreciate any help, if it has something to do with my django app or something else.. Additionally i have a middleware that doesn't interfere with requests but i have disabled it and result is just the same. -
Django admin site is looking for a template: <project_name>.html ...I want to use the default template
My project's admin site was working earlier with everything kept at default. But I'm building the site and after lots of coding I get an error where it is asking for a template that has the name of the project. Maybe this template was created by default earlier in .venv and it was somehow deleted or moved? TemplateDoesNotExist at /admin/ admin/<project_name>.html Request Method: GET Request URL: http://localhost:8000/admin/ Django Version: 4.2.23 Exception Type: TemplateDoesNotExist Exception Value: admin/<project_name>.html This is the admin.py in the main app. It imports from two secondary apps. from django.contrib import admin from user.models import Profile admin.site.register(Profile) from flights.models import Flight admin.site.register(Flight) from airports.models import Airport admin.site.register(Airport) Any ideas on how to get the admin site working again? -
How Does Connection Pooling Work In Django?
If I'm not wrong, currently there are two ways to have connection pooling in Django: Native Connection Pooling (Django 5.x) Using PGBouncer I want to know that how connection pooling works behind the scene in Django. In FastAPI, there is one "permanent" process that handles all requests. We can have a connection pool using for example asyncpg driver. In its simplest form, it creates like 10 connections to the Postgresql database(using 10 unix socket connections), then when a coroutine request a connection, it gives it from the pool. +-------------------------+ | +------------+ | ---------------> +------------+ | | | | | | | FastAPI | Connection | | ---------------> | Database | | | Pool | | | | | | (asyncpg) | | ---------------> +------------+ | +------------+ | +-------------------------+ But in Django, there is no single permanent process. If we use Gunicorn with sync workers, every worker instantiates a Django application to handle one request at a time. There is no shared memory between them. How can psycopg3 driver creates a connection pool in one worker and all other workers communicate with that? I guess PGBouncer is a separate process that creates connection pool inside its memory, then all Django workers … -
How can I fill in related models separately through forms (OneToOneField)?
I have two table models. I write data to one of them using a form. I also want to write data to the other model table using a form. But I'm trying to link these tables. Use the first one as a base. And fill in their two tables in two stages. In the first stage, I write the first model. In the second stage, the second model. It is important for me to be able to select a field from the first model in order to display it when filling out the second form. But I can't do it. I want both tables to have the same size by row when filling out. In the future, I plan to add new models and forms - as well as the second form using a field from the first model. What can I do? I take OneToOneField as a link. What can I do to link the models but write data to them not in one form, in one template. But in different ones in two forms and in two templates. When filling out a form as shown in the screenshot, I would like to display a drop-down list according to … -
Gunicorn + Gevent + Opentelemetry
Anyone using Django + Gunicorn + Gevent + Opentelemetry in production? Would love to know how you got it to work. Seems like I can't seem to use BatchSpanProcessor or BatchLogRecordProcessor. I'm getting errors which seem to have many open issues but didn't find a solution. I get this after the gunicorn is started but the server still accepts requests and serves them. Traceback (most recent call last): File "src/gevent/_abstract_linkable.py", line 287, in gevent._gevent_c_abstract_linkable.AbstractLinkable._notify_links File "src/gevent/_abstract_linkable.py", line 333, in gevent._gevent_c_abstract_linkable.AbstractLinkable._notify_links AssertionError: (None, <callback at 0xffffb32b0640 args=([],)>) 2025-06-09T14:58:34Z <callback at 0xffffb32b0640 args=([],)> failed with AssertionError 2025-06-09T14:58:34Z <callback at 0xffffb32903c0 args=([],)> failed with AssertionError When I start hitting it with many requests, then the following error comes up which is problematic. 2025-06-09T14:40:18Z <Greenlet at 0xffff65bb5b20: <bound method Thread._bootstrap of <Thread(OtelBatchSpanRecordProcessor, stopped daemon 281472388520736)>>> failed with KeyError Traceback (most recent call last): File "src/gevent/greenlet.py", line 900, in gevent._gevent_cgreenlet.Greenlet.run File "/usr/local/lib/python3.11/threading.py", line 1002, in _bootstrap self._bootstrap_inner() File "/usr/local/lib/python3.11/threading.py", line 1037, in _bootstrap_inner del _limbo[self] ~~~~~~^^^^^^ KeyError: <Thread(OtelBatchSpanRecordProcessor, stopped daemon 281472388522016)> I am starting the otel code from wsgi.py with preload app being false. So, the code is being executed after the forking and gevent monkey patching occurs. This I have validated. Below is the … -
Role and Permission in Django DRF
I am implementing permission-roles in Django using DRF but not sure where i got stuck here Here are models: class User(): class Staff() user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="staffs") business = models.ForeignKey( "Business", on_delete=models.CASCADE, related_name="staffs" ) role = models.PositiveSmallIntegerField (superadmin, admin, regular) class Business() name = models.CharField(max_length=150) class BusinessGallery() business = models.ForeignKey( Business, on_delete=models.CASCADE, related_name="gallery" ) here is BusinessViewSet class BusinessViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): serializer_class = BusinessSerializer def get_permissions(self): action_permissions = { "retrieve": [IsSuperAdmin | IsAdmin | IsRegular], "list": [IsSuperAdmin | IsAdmin], "partial_update": [IsAdmin | IsSuperAdmin], "create": [IsAuthenticated], "destroy": [IsSuperAdmin], } self.permission_classes = action_permissions.get(self.action, [IsSuperAdmin]) return super().get_permissions() def get_queryset(self): return Business.objects.filter(staffs__user=self.request.user) here is permissions.py class RolePermission(BasePermission): required_role = None def has_permission(self, request, view): user = request.user if not user or not user.is_authenticated: return False def has_object_permission(self, request, view, obj): if not request.user or not request.user.is_authenticated: return False business = self.get_business_from_object(obj) if not business: return False return request.user.staffs.filter( business=business, role=self.required_role ).exists() def get_business_from_object(self, obj): if isinstance(obj, Business): return obj if hasattr(obj, "business"): return obj.business return None class IsSuperAdmin(RolePermission): required_role = ROLE_SUPER_ADMIN class IsAdmin(RolePermission): required_role = ROLE_ADMIN class IsRegular(RolePermission): required_role = ROLE_REGULAR Assume that i already have all setup correctly. but for some reason i can not get this … -
Is there a way to test blog post permissions in PyTest?
I've been trying to make the final test pass. I seem to be getting a 403 error, nothing that I'm not authorized to make a post. Even though I gave the test user authorization to post tests. I don't understand why it's still giving me the 403, even when I coded the authorization of the posts. Here's the test proper: @pytest.mark.django_db def test_add_post_permission(self, test_client, test_user, contributor_group, add_post_permission): add_post_url = reverse("posts:add_post") post_list_url = reverse("posts:post_list") #Test 1: Not logged in - Redirect to login response_not_logged_in = test_client.get(add_post_url) assert response_not_logged_in.status_code == 403 # Redirect to login # Test 2: Logged in logged_in = test_client.login(email=test_user.email, password="pass123") assert logged_in # Test 3: Logged in, but without permission post_data = {"title": "CBV Post Title", "content": "CBV Post content"} response_no_perm = test_client.post(add_post_url, post_data) assert response_no_perm.status_code == 403 assert Post.objects.count() == 0 contributor_group.permissions.add(add_post_permission) contributor_group.save() # Assign user to the Contributor Group and give them permission to add posts test_user.groups.add(contributor_group) test_user.save() test_user.get_all_permissions() # Ensure permissions are loaded # Test 4: Test with permission response_with_perm = test_client.post(add_post_url, post_data) print(response_with_perm.status_code) assert response_with_perm.status_code == 302 assert response_with_perm.url == post_list_url assert Post.objects.count() == 1 # Test the post new_post = Post.objects.first() assert new_post.title == "CBV Post Title" assert new_post.content == "CBV Post content" … -
How do I prevent a user from creating multiple objects within 24 hours in Django
I'm trying to prevent users from creating more than one Mining object within a 24-hour period in my Django project. I chose to use Django signals, specifically the pre_save signal, to enforce this rule globally—regardless of whether the object is created through the admin panel, a view, or an API endpoint. Here is my Mining model: class Mining(models.Model): mining_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) amount_mine = models.DecimalField(max_digits=12, decimal_places=2, default=0.00) status = models.CharField(max_length=20, choices=STATUS_CHOICES) duration_seconds = models.PositiveIntegerField(null=True, blank=True) verified = models.BooleanField(default=False) ip_address = models.GenericIPAddressField(null=True, blank=True) hardware_info = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user} mined {self.amount_mine} AFC on {self.created_at.strftime('%Y-%m-%d')}" My Signals: from django.db.models.signals import pre_save from django.dispatch import receiver from django.utils import timezone from datetime import timedelta from .models import Mining @receiver(pre_save, sender=Mining) def prevent_multiple_mining_per_day(sender, instance, **kwargs): if not instance.pk: last_24_hours = timezone.now() - timedelta(hours=24) has_recent = Mining.objects.filter( user=instance.user, created_at__gte=last_24_hours ).exists() if has_recent: raise ValueError("User has already mined in the last 24 hours.") I chose signals because I want this restriction to apply no matter where the object is created from—views, admin panel, or REST API, to ensure consistency across the whole app. Even with the signal in place, I’m still able to create multiple Mining … -
Trying to send basic string to Django Backend via POST request using axios but no data is sent
I've been trying a basic string to Django backend from frontend using axios.post call. Connection is ensured and backend side detects the request but the data is empty. Frontend side: const axios = Axios.create({ baseURL: API_URL, headers: { 'Content-Type': 'application/json', }, }); export class MessageService { static async sendMessage(message: string): Promise<any> { try { const data = {question: message} // Uncomment the line below to use the actual API call const response = await axios.post('/chatbot/rest_handler', data); return response; } catch (error) { console.error('Error sending message:', error); throw error; } } Backend side: @csrf_exempt def rest_handler(request): print("REQUEST IS SENT FROM FRONTEND") req_data = request.body q_info = req_data.decode("utf-8") print("QUESTION:"+ q_info) return JsonResponse(request) But in the output screen, I see an empty string: [09/Jun/2025 10:49:33] "OPTIONS /chatbot/rest_handler HTTP/1.1" 200 2 REQUEST IS SENT FROM FRONTEND QUESTION: -
django-allauth - How to get Custom Adapter to respect the 'next' url query parameter
I am using allauth in my Django project and I have setup a custom account adapter which I have specified in settings.py - ACCOUNT_ADAPTER. My issue is once the user logins in at a url like - /accounts/login/?next=/checkout/ , my Custom Adapter has a get_login_redirect_url method defined, to redirect users based on their user type. The thing is I would like this adapter to respect the next url parameter. But when I look at the values - request.GET, request.POST, request.session, the next parameter is blank or empty. Can anyone suggest how to achieve this? -
Django Field errors not displaying
Here is my forms.py code: from .models import User class userRegistrationForm(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput()) confirm_password = forms.CharField(widget = forms.PasswordInput()) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email','password'] ``` Here is my views.py code: ``` def registerUser(request): if request.method == 'POST': print(request.POST) #request.POST, WE ARE GETTING THE DATA HERE. form = userRegistrationForm(request.POST) if form.is_valid(): # CREATE THE USER, USING THE FORM # password = form.cleaned_data['password'] # user = form.save(commit=False) #FORM IS READY TO BE SAVED, BUT NOT YET SAVED. BCZ OF COMMIT # user.role = User.CUSTOMER # user.set_password(password) # user.save() # CREATE THE USER, USING create_user METHOD. first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = User.objects.create_user(first_name=first_name, last_name=last_name, username=username, email=email, password=password) user.role = User.CUSTOMER user.save() #print("User is created") return redirect('registerUser') else: print("Invalid form") print(form.errors) else: form = userRegistrationForm() form = userRegistrationForm() context = { 'form':form } return render(request, 'accounts/registerUser.html', context) Here is my registerUser.html code: <ul class="errorlist"> {% for field in form %} {% if field.errors %} {% for error in field.errors %} <li style="color: red;">{{error}}</li> {% endfor %} {% endif %} {% endfor %} </ul> Technically my error should be shown here in red color: [enter image … -
Django - Testing async management command not working as expected
To give some context, i made a async function which works fine when testing manually but when I use Django's testcases, the query is not returning anything back inside the async block, if I try the same query outside, it returns the objects class Command(BaseCommand): help = "Update companies' website field using LLM + Annual reports content" def add_arguments(self, parser): parser.add_argument("-c", type=int, default=10) def handle(self, *args, **kwargs): rows = list( CompanyInfo.objects.filter(website="") .select_related("company_code") .exclude(company_code__bse_code="", company_code__nse_code="") ) print(BseAnnouncement.objects.all()) #This is working, returns 1 object asyncio.run(self._handle_async(rows, kwargs["c"])) async def _handle_async(self, rows, concurrency): if not len(rows): logger.info("No companies with missing websites found.") return await _update_websites(rows, concurrency) logger.info("Website update process completed.") async def _filter_recent(company): if company.bse_code: model = BseAnnouncement elif company.nse_code and company.is_sme: model = NseEmergeAnnouncement else: model = NseAnnouncement print(f"Fetching announcements for {model}") print(f"Company is {company}") print(f"Company ID is {company.id}") queryset = model.objects.filter(company_code_id=company.id).order_by("-create_date") #Empty return -> No object print(BseAnnouncement.objects.all()) #Empty return -> No object results = await sync_to_async(list)(queryset) return results -
Add functionality to model creation in django admin site
I creating a website using django. I want to add extra functionality to model creation and changing pages in standard admin site, that is input text field and button. Idea is to paste a link to post on another website and press button to fill some fields with fetched data and than continue creation. I`m new to django and really have no idea how to add extra field and button for this purpose. Question is how to add field, button and js to admin site, not how to fetch data and process link. -
How to efficiently combine Redis-based recommendation scoring with Django QuerySet for paginated feeds?
I'm building a marketplace app (think classified ads with negotiations) and trying to implement a personalized recommendation feed. I have a hybrid architecture question about the best way to handle this: Current Setup: Django backend with PostgreSQL for product data Redis for user preferences, actions, and computed recommendation scores Celery for background recommendation generation The Challenge: I need to serve a paginated feed where the order is determined by Redis-based scoring (user preferences, trending items, negotiation activity), but the actual product data comes from Django models. My Current Approach: Celery task generates ordered list of product IDs based on Redis metrics Cache this ordered list in Redis (e.g., [123, 456, 789, ...]) For each page request, slice the cached ID list Use Django's Case/When to maintain the Redis-determined order: preserved_order = models.Case( *[models.When(pk=pk, then=pos) for pos, pk in enumerate(page_product_ids)], output_field=models.IntegerField() ) products = Product.objects.select_related('seller').filter( id__in=page_product_ids ).annotate(preserved_order=preserved_order).order_by('preserved_order') Questions: Is using Case/When with enumerate() the most efficient way to preserve Redis-determined order in Django? Should I be caching the actual product data in Redis instead of just IDs? Any better patterns for this Redis scoring + Django data combination? How do you handle the "cold start" problem when recommendations aren't ready yet? … -
'User' object has no attribute 'profile' django profile update problem
i am new to django and currently learning and i have encountered a problem that i just cant seem to solve. from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.contrib.auth.decorators import login_required def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account Successfully created for {username}!') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required() def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm() context = { 'u_form': u_form, 'p_form': p_form } return render(request, 'users/profile.html',context) in this code, in the else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm() part, whenever i add instance in the p_form as p_form = ProfileUpdateForm( instance=request.user.profile) it gives this error in browser: AttributeError at /profile/ 'User' object has no attribute 'profile' Request Method: GET Request URL: http://127.0.0.1:8000/profile/ Django Version: 5.2.1 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'profile' Exception Location: D:\Documents\pycharm\venv\Lib\site-packages\django\utils\functional.py, line 253, in inner Raised during: users.views.profile and yes, the change in the p_form is what creates … -
How to integrate a PyTorch YOLO ensemble model (.pt file) into a Django web app for real-time image predictions?
I'm building a Django web app where users can upload images to detect objects using a YOLO ensemble model saved as a .pt file. This model includes keys like 'model', 'names', 'stride', and 'ensemble_info'. So far, I can load the model with torch.load(), but I'm unsure how to: Preprocess the uploaded image in a Django view, Run inference using the loaded ensemble model, and Return bounding box results to the frontend (ideally as JSON or a drawn image). Environment: Python 3.10, Django 4.x, Torch 1.13+ Has anyone done something similar, or can you point to an example repo/tutorial? Any help or code snippets would be appreciated! -
How to make a one-off charge (no UI) reusing the saved customer after initial Checkout?
I’m implementing payments with Stripe and I’ve run into a flow I don’t know how to solve. I’d like to know the right or recommended way. Scenario First payment with UI: The user goes to my frontend, I use the normal Checkout Session flow. Stripe shows the card form, the customer pays, I store the customer_id. Extra charges (no UI): After that first payment, in the frontend I have “extra purchase” buttons (e.g., pay $20 for another advice), but in this case I do not want the user to enter card details again or see the Stripe form. Just click and charge (one-click, not subscription, just a second one-off charge). My problem: When I create the customer in Stripe, I see the payment_method is null. I try to create a new PaymentIntent to charge, but it needs a payment_method. ChatGPT says I should get the PaymentMethod ID, but I don’t know how. When I try to list the customer’s payment methods, it’s empty or null. If I try to reuse the PaymentMethod ID from the first charge, Stripe says I can’t use it again. I don’t know if I’m doing something wrong, or if it’s really not possible to charge … -
Wagtail - How can I use a custom StructBlock with programmatically assignable default values?
I have created a StreamField for some of the site's settings. This StreamField contains a collection of a custom StructBlock, named FacetBlock. FacetBlock contains a BooleanBlock, a CharBlock, an IntegerBlock and a ChoiceBlock. Now I need to make the CharBlock translatable, which means the admin will be able to enter one text for each language available on the site. The way I was thinking of doing this is by using another custom StructBlock, this time called TranslatableTextBlock. It would contain a ChoiceBlock, a CharBlock and some hidden input to store the complete value. Using javascript, the admin would select a language, enter the text for that language and then move on to the next language. I'm not sure yet how that would be saved the database, but I'm not even able to get that far. Right now, I can have either the fields show up with no default value or I get a javascript error (TypeError: e is null) in vendor.js, which triggers the same error in comments.js. Here is the code I have so far. I have omitted the FacetBlock definition, because it works perfectly when reverting TranslatableTextBlock to a CharBlock. Python code: class TranslatableTextBlock(StructBlock): def __init__(self, default_text:str = … -
What’s the recommended Python naming convention for variables vs constants in large projects?
I’m working on a Python project and want to enforce consistent naming conventions for variables, constants, and class names. I am refering this https://rkoots.github.io/styleguide/ There are several conventions out there (PEP8, Google style, etc.), but I’m curious: What are the widely accepted best practices for naming constants vs variables? How do teams usually enforce and document these conventions in codebases? -
Performance issues when using Django's Min('id') in big table
I have a model Table which gets a new entry every few seconds, so it's a quite big table. class Table(models.Model): id: int pk: int timestamp = models.PositiveBigIntegerField(db_index=True) Now what i am trying to do is get the first entry for the last 24h. And for some reason it takes way to much time. Like we are talking about seconds. But if i try to get last i get it instantly. I've tried following queries: from_ts = int(time.time()) - 24 * 60 * 60 first_entry = Table.objects.filter(timestamp__gte=from_ts).first() first_entry = Table.objects.filter(timestamp__gte=from_ts).aggregate(Min('id')) They both take a few seconds to complete but if I try .aggregate(Min('timestamp')) it returns almost instantly. I tried .filter(timestamp__gte=from_ts)[0] which is quick and does work but i know its undefined behaviour because the entries aren't sorted and in some edge cases it might not work. Then i tried to just get the whole query in python and find min in python and it was almost instant. first_entry = min(list(Table.objects.filter(timestamp__gte=from_ts))) Can anyone explain what exactly is happening here and what is the cleanest/best solution? -
CS50W Project network, can't figure how to implement the Paginator
I've been trying to implement the paginator function for about two months now. I've tried many different approaches, but they always lead to new bugs. In views.py, I load the posts and send them to JavaScript. In loadPosts and loadProfile, I pass the fetch function as a parameter to the buttons. Everything else works fine. The buttons call the fetch function, and the posts are displayed. The issue is: once I load the second page of profile posts, then switch to loadPosts and click "next" again, it loads the profile posts instead. I’ve already tried using removeEventListener and flags, but I couldn’t figure out how to properly reset the event listener when switching between the functions. [06/Jun/2025 09:01:10] "GET /post?start=0&end=9 HTTP/1.1" 200 825 [06/Jun/2025 09:01:10] "GET /post/new?start=0&end=9 HTTP/1.1" 200 810 // Switch between the pages: document.querySelector("#profile-link").addEventListener('click', function(event) { // Top left username, to load the profile loadProfile(loggedInUsername) }); document.querySelector("#index").addEventListener('click', function(event) { event.preventDefault(); loadPosts() }); @csrf_exempt def post_view(request, username = None): if request.method == "GET": # Loading all posts if username == None: posts = Post.objects.all().order_by('-date') start = int(request.GET.get("start") or 0 ) end = int(request.GET.get("end") or (start + 9)) posts_in_range = posts[start:end+1].values("text","date","user__username") return JsonResponse({"posts": list(posts_in_range)}) else: # Loading a profile user …