Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django with mypy: How to resolve incompatible types error due to redefined field for custom `User` model class that extends "AbstractUser"?
I have an existing Django project which uses a custom User model class that extends AbstractUser. For various important reasons, we need to redefine the email field as follows: class User(AbstractUser): ... email = models.EmailField(db_index=True, blank=True, null=True, unique=True) ... Typing checks via mypy have been recently added. However, when I perform the mypy check, I get the following error: error: Incompatible types in assignment (expression has type "EmailField[str | int | Combinable | None, str | None]", base class "AbstractUser" defined the type as "EmailField[str | int | Combinable, str]") [assignment] How can I make it so that mypy allows this type reassignment? I don't wish to just use # type: ignore because I wish to use its type protections. For context, if I do use # type: ignore, then I get dozens of instances of the following mypy error instead from all over my codebase: error: Cannot determine type of "email" [has-type] Here are details of my setup: python version: 3.10.5 django version: 3.2.19 mypy version: 1.6.1 django-stubs[compatible-mypy] version: 4.2.6 django-stubs-ext version: 4.2.5 typing-extensions version: 4.8.0 -
Argument of type "Literal['result']" cannot be assigned to parameter "__key" of type "SupportsIndex | slice" in function "__getitem__"
CODE def youtube(request): if request.method == "POST": form = DashboardFom(request.POST) text = request.POST['test'] video = VideosSearch(text,limit=10) result_list = [] for i in video.result()['result']: result_dict = { 'input':text, 'title':i['title'], 'duration':i['duration'], 'thumbnail':i['thumbnails'][0]['url'], 'channel':i['chanel']['name'], 'link':i['link'], 'views':i['viewCount']['short'], 'published':i['publishedTime'] } desc = '' if i['descriptionSnippet']: for j in i['descriptionSnippet']: desc += j['text'] result_dict['description'] = desc result_list.append(result_dict) context = { 'form':form, 'results':result_list } return render(request,"dashboard/youtube.html",context) else: form = DashboardFom() context = {'form':form} return render(request,"dashboard/youtube.html",context) From the above block of code the following code gives error for i in video.result()['result'] The error message is -- Argument of type "Literal['result']" cannot be assigned to parameter "__key" of type "SupportsIndex | slice" in function "__getitem__" Type "Literal['result']" cannot be assigned to type "SupportsIndex | slice" "Literal['result']" is incompatible with protocol "SupportsIndex" "__index__" is not present "Literal['result']" is incompatible with "slice"PylancereportGeneralTypeIssues) Also the following dictionary gives error--- result_dict = { 'input':text, 'title':i['title'], 'duration':i['duration'], 'thumbnail':i['thumbnails'][0]['url'], 'channel':i['chanel']['name'], 'link':i['link'], 'views':i['viewCount']['short'], 'published':i['publishedTime'] } The error message is --- Argument of type "Literal['title']" cannot be assigned to parameter "__key" of type "SupportsIndex | slice" in function "__getitem__" Type "Literal['title']" cannot be assigned to type "SupportsIndex | slice" "Literal['title']" is incompatible with protocol "SupportsIndex" "__index__" is not present "Literal['title']" is incompatible with "slice"PylancereportGeneralTypeIssues) -
pymongo count_doucment() not working with datetime
Hi i am trying to query data from mongodb using python = 3.8, django=4.2.2, arrow==1.2.3 pymongo = 3.13.0 this is my filter object filter['created_at']={ '$gte': arrow.now(settings.LOCAL_TIME_ZONE).shift(hours=-24).span('day')[0].to(settings.TIME_ZONE).datetime, '$lt': arrow.now(settings.LOCAL_TIME_ZONE).span('day')[1].to(settings.TIME_ZONE).datetime, } when i print filter['created_at'] i get output as 'created_at': {'$gte': datetime.datetime(2023, 11, 22, 18, 30, tzinfo=tzutc()), '$lt': datetime.datetime(2023, 11, 24, 18, 29, 59, 999999, tzinfo=tzutc())} and this is my count function def count(self, filters={}): q = self.collection.count_documents(filters) return q when i pass empty {} in filter i get count of documents -
Submit file on GitHub
I once uploaded a Django file to GitHub, and after making some changes, I want to upload it again, but it gives me this error. Can you tell me what I should do? C:\Users\Desktop\project1>git add . C:\Users\Desktop\project1>git commit -m "project1_new" C:\Users\Desktop\project1>git push origin --all Enumerating objects: 3, done. Counting objects: 100% (3/3), done. Writing objects: 100% (2/2), 233 bytes | 233.00 KiB/s, done. Total 2 (delta 0), reused 0 (delta 0), pack-reused 0 To https://github.com/me50/ZZZZZZZZ.git 2c0ea43..cfae680 check50/projects/2020/x/wiki -> check50/projects/2020/x/wiki ! [rejected] web50/projects/2020/x/search -> web50/projects/2020/x/search (fetch first) ! [rejected] web50/projects/2020/x/wiki -> web50/projects/2020/x/wiki (fetch first) error: failed to push some refs to 'https://github.com/me50/ZZZZZZZZ.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. -
sudo: python: command not found for django migration to mysql database
I want to connect my current project to mysql databse which I created before with root user I want to connect my current project to mysql databse which I created before with root user but every time I want to use it, I get the error sudo: python: command not found how could I fix this? (I don't want to run that with another user, because some reasons I want use root user) -
Is it possible to combine a regex url pattern with url converter
I have two different paths in django-project urls re_path(internal_site_url, internal_site), #for internal sites #internal_site_url is re_pattern path('<path:site_url>', external_site) #for external sites but re_path in first path would not include path converter path:site_url for further usage in a view, in comparison with the second one. So how could I achive combining re-pattern match with path conversion? -
Cookiecutter Django project postgres migrating to new host
I have a cookiecutter django template project working fine with a local postgres database. (https://cookiecutter-django.readthedocs.io/en/latest/) I've copied the git repository and recreated the docker images on a new host to run in production, but I would like to export/copy my data as well. What's the recommended way to move the data over from the postgres docker instance ? Thanks -
Django url issue while calling in Postman
I am creating CRUD operation in Django, REST API and Mongo DB. I have done the basic CRUD code. When I try to call the api in postman, I am not getting any responses. In the pycharm, I am seeing the below issue, "POST /emp/registration%0A HTTP/1.1" 404 2297 Not Found: /emp/registration Here is my project structure. DjangoAPI.urls.py from django.urls import path from django.urls import re_path from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('emp/', include('EmployeeApp.urls')), ] DjangoAPI.EmployeeApp.urls.py from EmployeeApp import views from django.conf.urls.static import static from django.conf import settings from django.urls import path urlpatterns = [ path('registration', views.registrationApi), ] DjangoAPI.settings.py Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os BASE_DIR=Path(__file__).resolve(strict=True).parent.parent MEDIA_URL='/Photos/' MEDIA_ROOT=os.path.join(BASE_DIR,"Photos") # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-@oxx-o(4f=mxha%-tlv97)x9m7x_fw=(@*k=*29q%r7c8*)%-&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', … -
REST api url not found issue
I am doing CRUD operation in Django + REST API + Mongo DB. I have done the basic CRUD code. When I try to call the api in postman, I am not getting any responses. In the pycharm, I am seeing the below issue, "POST /emp/registration%0A HTTP/1.1" 404 2297 Not Found: /emp/registration Here is my project structure. DjangoAPI.urls.py from django.urls import path from django.urls import re_path from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('emp/', include('EmployeeApp.urls')), ] DjangoAPI.EmployeeApp.urls.py from EmployeeApp import views from django.conf.urls.static import static from django.conf import settings from django.urls import path urlpatterns = [ path('registration', views.registrationApi), ] DjangoAPI.settings.py Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os BASE_DIR=Path(__file__).resolve(strict=True).parent.parent MEDIA_URL='/Photos/' MEDIA_ROOT=os.path.join(BASE_DIR,"Photos") # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-@oxx-o(4f=mxha%-tlv97)x9m7x_fw=(@*k=*29q%r7c8*)%-&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ … -
How to access a Django variable in an external JavaScript?
I am making a Django website. In it I am trying to access a variable in view.py file in an external static JS file linked to my template. I tried using the syntax var is_empty = "{{is_empty}}", but it didn't work in a if statement where if(Number(is_empty) == 1), and also I tried creating a div in my body(with id = "temp") and adding an attribute data-dj = {{is_empty}} and then using var is_empty = document.getElementById("temp").getAttribute("data-dj");, but it was showing an error that cannot call getAttribute on null. Please help! -
how to overwrite value filled with POST
I'm trying to pass list of ids into hidden field: the POST result is: POST in add_document:<QueryDict: {'csrfmiddlewaretoken': ['xxx', 'xxx'], 'person_ids': ['15129', '15161', '15177', '15217'], 'submit': ['Submit']}> views.py: (...) add_document_form = DocumentForm(request.POST or None, context = context, initial={'person_ids': '1'}) context['add_document_form'] = add_document_form print(add_document_form.fields['person_ids'].initial) html_template = loader.get_template('backend/' + context['load_template']) return HttpResponse(html_template.render(context, request)) (...) forms.py: class DocumentForm(forms.ModelForm): # person_ids = forms.MultipleChoiceField(widget = forms.HiddenInput()) person_ids = forms.CharField(widget = forms.HiddenInput()) def __init__(self, *args, **kwargs): context = kwargs.pop('context', None) super(DocumentForm, self).__init__(*args, **kwargs) print(self.fields['person_ids'].initial) self.fields['person_ids'].initial = '2' print(self.fields['person_ids'].initial) But whatever I do - finally I got <input type="hidden" name="person_ids" value="15217" id="id_person_ids"> Django totally ignores my initial settings... (while print always printing the correct values... My best solution would be: <input type="hidden" name="person_ids" value="['15129', '15161', '15177', '15217']" id="id_person_ids"> Changing widget to TextField changes nothing. The value of person_ids is still '15217' -
javascript request origin determination
I have a general Javascript question The setup Webserver ( number 1 ) with a website that uses html and javascript A second ( number 2 ) webserver with Apache and Django Webserver 1 with html / javascript page < ------- javascript applications requests data from Webserver 2 ---------- > Webserver 2 The website from point 1 runs a javascript application that sends data to the web server number 2. How can I make sure that web server number 2 only accepts http requests from the javascript application of web server number 1 ? For example I had thought of a csrf token. Is this already a good approach, are there any other possibilities I have? Thanks in advance. -
How to process secondary sourse links via django views?
Let's say I have the following home.html template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>home</title> <link rel="icon" type="image/png" href="{% static 'images/favicon-32x32.png' %}" > <link rel="stylesheet" href"/stylesheet_url"> </head> <body> </body> </html> and urls look like that: urls = [ path('home/', home) ] and home view is: def home(): return render(request, 'home.html') how should the any-referral view and any-referral url look like, so I could process request that uses any referral from inside of any resourse? The Idea for url is that if I firstly specify all the concreate urls, then the last url in urls could be matching any url left. But the main problem seems that the veiw does not trigger on any url pattern (currently my everymatching url looks like path('<path:referral>', any_refferal). Also I suspect that there stands a different mechanism behind using referrals from inside of page, compared to one that that processes the page -
How to do visudo edit in sudoers.d automatically in Python?
I have a complex django-application and want to add the option for the user to shutdown the server (a Raspberry Pi) from the django-webmenu. Because the django-process on the Raspi does not have sudo privileges, I decided to give the shutdown privilege to my user via an additional configfile in sudoers.d. So I added two lines to execute to my installation instructions: To create the new file with visudo: sudo visudo -f /etc/sudoers.d/shutdown_privilege And than add one line to that file: cam_ai ALL=(root) NOPASSWD: /sbin/shutdown This works nicely, but now I would like to move this complication into my (Python-)installation script. This does not work. What am I doing wrong? I tried several things: subprocess.call(['sudo', 'touch', '/etc/sudoers.d/shutdown_privilege']) subprocess.call(['sudo', 'sed', '-i', '$acam_ai ALL=(root) NOPASSWD: /sbin/shutdown' , '/etc/sudoers.d/shutdown_privilege']) cmd = 'echo "cam_ai ALL=(root) NOPASSWD: /sbin/shutdown" | sudo tee -a /etc/sudoers.d/shutdown_privilege' subprocess.call(cmd, executable='/bin/bash') The only thing that worked is the touch command in the first line. The rest stops the program execution or does just nothing... -
django-smart-selects query filter
I am using django-smart-selects to create chained dropdown forms, problem is I cannot filter querysets made by this package since it creates its own formsets. normally i would override init such : def __init__(self,*args, **kwargs): super(BookingForm, self).__init__(*args, **kwargs) self.fields['booked_time'].queryset = AvailableHours.objects.filter(status=True) in my forms.py but now this package is overriding entire form in admin and in user views. I need to filter the query so that only objects with Status=True are fetched my forms.py : class BookingForm(forms.ModelForm): class Meta: model = Bookings exclude = ('user','booking_code','confirmed',) def __init__(self,*args, **kwargs): super(BookingForm, self).__init__(*args, **kwargs) self.fields['booked_time'].queryset = AvailableHours.objects.filter(status=True) my models.py: AVAILABLE_DATE_CHOICES = ( (True, 'فعال'), (False, 'غیرفعال'), ) class AvailableDates(models.Model): free_date = jmodels.jDateField(null=True, verbose_name="تاریخ فعال",) status = models.BooleanField(choices=AVAILABLE_DATE_CHOICES,null=True,default=True, verbose_name="وضعیت",) class Meta: verbose_name_plural = "روزهای فعال" verbose_name = "روز فعال" ordering = ['-free_date'] def __str__(self): return f'{str(self.free_date)}' class AvailableHours(models.Model): free_date = models.ForeignKey(AvailableDates,verbose_name="تاریخ فعال", null=True, blank=True,on_delete=models.DO_NOTHING,related_name='freedate') free_hours_from = models.IntegerField(null=True, blank=True, verbose_name="از ساعت",) free_hours_to = models.IntegerField(null=True, blank=True, verbose_name="الی ساعت",) status = models.BooleanField(null=True,default=True, verbose_name="آزاد است؟",) class Meta: verbose_name_plural = "سانس ها" verbose_name = "سانس" def __str__(self): return f'{str(self.free_date)} - {self.free_hours_from} الی {self.free_hours_to}' class Bookings(models.Model): user = models.ForeignKey(User,on_delete=models.DO_NOTHING, null=True, verbose_name="کاربر",) booker_name = models.CharField(max_length=100, null=True, verbose_name="نام",) booker_service = models.ForeignKey(BarberServices, null=True, on_delete=models.DO_NOTHING, verbose_name='خدمات') booked_date = models.ForeignKey(AvailableDates, null=True, on_delete=models.DO_NOTHING,related_name='booked_date', verbose_name="روز",) booked_time = … -
Prevent Form Resubmission on Page Refresh - Django
I encountered an issue in my Django project where refreshing the page after a form submission would trigger a resubmission of the form, causing unexpected behavior. I found a workaround that involves redirecting to a success page and then back to the original form page. Step 1: Create a Success Page (success_page.html) html Copy code <title>Success Page</title> {% load static %} <script> window.location.href = '{% url "your_page_with_form_url_name_in_urls.py" %}'; </script> Step 2: Modify Your Django View In your Django view (views.py), modify it to redirect to the success page on form submission: python Copy code views.py from django.shortcuts import render def your_view(request): if request.method == 'POST': # Your logic for handling form submission return render(request, 'success_page.html') # Render your form page for normal requests return render(request, 'your_page_with_form.html', context) Explanation: Success Page: The success_page.html contains a simple JavaScript script to redirect to your form page using window.location.href. Django View: In your Django view, when the form is submitted (POST request), it renders the success_page.html. For normal requests, it renders your form page (your_page_with_form.html) along with the desired context. This approach avoids the form resubmission problem and allows you to display the latest data without needing to manually refresh the page. This solution … -
Very close to having a working django frontpage and Im not sure what is wrong
Im close to being able to spin up and iterate on this django website that I am trying to launch. I seem to be struggling with alternating 404 and 500 errors presenting as each of these two: [24/Nov/2023 11:19:56] "GET / HTTP/1.1" 500 145 [24/Nov/2023 11:20:07] "GET / HTTP/1.1" 404 179 respectively When I alternate my urls.py line 20 between path('randoplant_home', views.randoplant_home, name='randoplant_home'), # 404 path('', views.randoplant_home, name='randoplant_home'), # 500 I don't quite know what else I am missing to be able to spin up my app and I've not been able to isolate what is causing my code to still error. here is my project structure: randoplant/ ├── frontend/ │ ├── templates/ │ │ └── randoplant_home.html │ ├── views.py │ ├── urls.py │ └── ... ├── views.py ├── urls.py ├── settings.py └── ... here is my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('randoplant_home/', views.randoplant_home, name='randoplant_home'), #path('', views.randoplant_home, name='Home') ] and my views.py def randoplant_home(request): return render(request, 'frontend/templates/randoplant_home.html') ####################### MANAGEMENT ################################# class PlantPageView(TemplateView): template_name = 'randoplant_home.html' ``` Very close to spinning up my home page for the first time but Im really not sure what else is missing. -
Django channels close vs disconnect
Sorry for dumb question but I didn't get the idea of this two methods. I can't understand when I should call close and when disconnect. And also I can't understand why disconnect does not have implementation under the lib's hood? -
Django models: Create a custom json as a field in an exisiting model
I have an existing model in model.py as follows: class Work(models.Model): id = CustonUUIDField(default=uuid.uuid4, unique=True,editable=False, primary_key=True) level = models.CharField(max_length=100, null=True,blank=True) is_experienced = models.BooleanField(default=True) I want to add a custom Json field to this model. The json value is expected to be like this: is_experienced = {"is_enabled":True, unit:"months", no:10} I also want to specify some validations for this field: is_enabled should only be a boolean value unit should be an enum to select value from days, weeks, months but can also be none no should be a positive integer but can also be None if is_enabled is false then unit and no should be None -
Noob question regarding serializer Django
I have Customer model which has a foreign key for User model. I am trying to implement register feature as found below, Customer Model class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mobile = models.PositiveBigIntegerField() def __str__(self) -> str: return self.user.username Customer and User serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'first_name', 'last_name', 'username', 'email'] class CustomerSerializer(serializers.ModelSerializer): class Meta: model = models.Customer fields = ['id', 'user', 'mobile'] def __init__(self, *args, **kwargs): super(CustomerSerializer, self).__init__(*args, **kwargs) self.Meta.depth = 1 def create(self, validated_data): print(validated_data) mobile = validated_data.pop('mobile') print(mobile) serializer = UserSerializer(validated_data) serializer.is_valid(raise_exception=True) customer = models.Customer.objects.create(user=serializer.data, mobile=mobile) return customer RegisterAPIView class RegisterAPIView(APIView): def post(self, request): data = request.data customerSerializer = serializers.CustomerSerializer(data=data) customerSerializer.is_valid(raise_exception=True) For me the create function of CustomerSerializer is not getting called. Am I missing something? If I change my view to class RegisterAPIView(APIView): def post(self, request): data = request.data userSerializer = serializers.UserSerializer(data=data) userSerializer.is_valid(raise_exception=True) userSerializer.save() customerSerializer = serializers.CustomerSerializer(data=data) customerSerializer.is_valid(raise_exception=True) customerSerializer.save() return Response(customerSerializer.data) I get response data as "data":{"mobile":1111111111}, instead of the whole customer object (including user data). Also this creates possibility of User object being created without Customer object present (because of any issue while creating customer object) Is there a better way to do this? -
Don't know how to enable HTML tags and HTML attributes in Martor
I'm currently working on integrating Martor into my Django project, and I'm having some trouble with the rendering of HTML tags and attributes. Even though I've configured the ALLOWED_HTML_TAGS and ALLOWED_HTML_ATTRIBUTES settings, certain HTML, like <span style="color: red">I am red</span>, doesn't render as expected. I've checked the documentation, but there seems to be a lack of information on troubleshooting this specific issue. Has anyone encountered a similar problem or could provide guidance on how to debug and resolve this? -
how to darken the whole page behind a popup?
I have this sidebar that I want to make the whole background dark when it is clicked on I used this code but the posts remain white also the dark background does not get closed when I close the sidebar what should I do?? I post the html here please tell me if I need to post other pages Thanks in advance my post.html <script> function openModal() { $("#overlay").css({"display":"block"}); $("#modal").css({"display":"block"}); } </script> <style> #modal { position:fixed; left:50%; top:50%; transform:translate(-50%, -50%); border:solid 1px #000; display:none; background-color:#fff; } #overlay { position:fixed; left:0; top:0; width:100vw; height:100vh; display:none; background-color:#000; opacity:0.5; } </style> <div id="overlay"></div> <div id="modal"></div> <div class="container"> <div style="margin-top: 25px"></div> <div class="card-deck mb-3 text-center"> <div class="card mb-4 box-shadow"> <div class="card-header"> <h4 class="my-0 font-weight-normal">{{post.title}}</h4> </div> <div class="card-body"> {{ post.body|truncatewords_html:30 }} <hr> <p><img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}" width="75" height="75"> Author: {{ post.author }}</p> <a href="{% url 'detail' post.id %}" class="btn btn-info btn-small" >Read More <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-three-dots" viewBox="0 0 16 16"> <path d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 … -
django development server not initializing
whenever i am trying to start my local development server in django, i am getting this horrible error. Exception ignored in thread started by: <function check_errors..wrapper at 0x0000020946FB0D60> Traceback (most recent call last): File "C:\Users\anand\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) Can anyone help me out? In virtual environment it is running fine. I tried it in venv and it is working fine, but not in local development mode. -
how can i add active class to image slider dynamically in Django template?
i have an image slider which does not show anything if the image does not have active class on it as it slides through a list of images. {% for v in m.value.images %}<div class="carousel-item active"> <div class="container"> <div class="carousel-caption"> <h1>Another example headline.</h1> </div></div>{% endfor %} -
django render multiple templates with same context hitting db every time
guys. I am working on showing multiple tables in multiple tabs using htmx for lazy-load. The code is working properly, but I couldn't solve two things. the queryset is hitting db 4 times. I was trying to load in order of table one, two, three, four using hx-sync queue, but failed. So, I used delay to load the tabs instead using queue. That way, I could load table one first all the time, but rest of them are loading randomly ordered. Here is my view file. def test_view(request, id: int, table: str): data = Model.objects.filter(id=id).values() if table == "table_one": return render(request, "path/to/table-one.html", {"data": data}) elif table == "table_two": return render(request, "path/to/table-two.html", {"data": data}) elif table == "table_three": return render(request, "path/to/table-three.html", {"data": data}) elif table == "table_four": return render(request, "path/to/table-four.html", {"data": data}) else: raise Http404 If I print data to check, it is printing four times of queryset with all data because it is rendering all four tables. and here is the template. <div class="mb-4 border-b border-gray-200 dark:border-gray-700"> <ul class="flex flex-wrap -mb-px text-sm font-medium text-center" id="myTab" data-tabs-toggle="#tabs" role="tablist"> <li class="mr-2" role="presentation"> <button class="inline-block p-4 border-b-2 rounded-t-lg" id="tab-one" data-tabs-target="#table-one" type="button" role="tab" aria-controls="table-one" aria-selected="false">Table One</button> </li> <li class="mr-2" role="presentation"> <button class="inline-block p-4 border-b-2 …