Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest_framework, logout redirect doesnt work
I am trying to redirect to the home page after clicking on Logout urls.py urlpatterns = [ . . path("api-auth/", include("rest_framework.urls")), ] settigs.py . . LOGOUT_REDIRECT_URL = "/" ACCOUNT_LOGOUT_REDIRECT_URL = "/" The problem is it still redirect to /api-auth/logout/?next=/current-page. This will cause an error because this "current page" needs authentication (requires a login) unlike the home page which doesn't require a login I also tried path("api-auth/logout", RedirectView.as_view(url="/", permanent=True)) but this again didn't work(still redirected to the "current page"). How can I redirect to the home page? -
Telethon TelegramClient.sign_in deadlock
I'm trying to separate my account access logic with Telethon. Thus, first a user enters his phone number, password, and then, when he receives an SMS with a code, he enters it too, and I can work with TelegramClient. Here's my code inside a Django project (the code is incredibly awful since I'm writing it in haste and for myself): urls.py from django.urls import path from .views import main_page, verify urlpatterns = [ path("authenticate/", main_page), path("verification/", verify, name="verify") ] view.py from django.shortcuts import render, redirect from django.urls import reverse from telethon import TelegramClient global phone, password, hash_, client phone = None password = None hash_ = None client = TelegramClient( "Telegram Client", 0, "" ) async def main_page(request): global phone, password, client, hash_ if request.POST: phone = request.POST['phone'] password = request.POST['password'] print("Connecting to the client") await client.connect() print("Sending an SMS with the code") hash_ = await client.send_code_request(phone) return redirect(reverse("verify")) return render(request, "credentials.html") async def verify(request): global phone, password, client, hash_ if request.POST: print("Connecting to the client") await client.connect() print( "Data before signing in: " "phone {}, password {}".format(phone, password) ) # Here is a deadlock. client = await client.sign_in( phone, request.POST["code"], password=password, phone_code_hash=hash_.phone_code_hash ) print( "Check after signing in", await … -
Django. Updating the model instance
Let's say I have a model: class PurchaseOrder(models.Model): supplier = models.ForeignKey('Supplier', on_delete=models.DO_NOTHING) employee = models.ForeignKey('employees.Employee', on_delete=models.DO_NOTHING) total_price = models.FloatField(null=True, blank=True) creation_date = models.DateTimeField(auto_now_add=True) posted = models.BooleanField(default=False) required_shipment_date = models.DateField(null=True, blank=True) date_shipped = models.DateField(null=True, blank=True) date_of_receiving = models.DateField(null=True, blank=True) shipment_address = models.CharField(max_length=255) order_status = models.CharField(max_length=255, choices=OrderStatus.ORDER_STATUS_CHOICES, default='ACCEPTED') def __str__(self): return f"Purchase order {self.supplier} № {self.pk}" def get_absolute_url(self): return reverse('purchases:purchase-order-details', kwargs={'pk': self.pk}) def compute_total_price(self): total_price = PurchaseOrder.objects.annotate( value=models.Sum(models.F('purchaseorderitem__quantity') * models.F('purchaseorderitem__price_per_unit')) ) print("total price") self.total_price = total_price[0].value In my model I have a method "compute_total_price" which gets all order items and multiplies quantity and price for every item and then sum it. The issue is I don't know how to save value to my model's field "total_price". I thought accessing self will do that, but it doesn't. The method computes the value however field isn't updated. -
django.db.utils.IntegrityError: NOT NULL constraint failed: Eid_Post_name.massenger_name
i have this issue "django.db.utils.IntegrityError: NOT NULL constraint failed: Eid_Post_name.massenger_name " and these my codes views.py from .models import Name # Create your views here. def Home(request): name_input = request.POST.get('user_name') name_in_model = Name(massenger_name=name_input,) name_in_model.save() return render(request , 'index.html') and this models.py from datetime import datetime # Create your models here. class Name(models.Model): massenger_name = models.CharField(max_length=50) action_time = models.DateTimeField(default=datetime.now) def __str__(self): return self.massenger_name and this index.html <!DOCTYPE html> <html lang="en" dir="rtl"> <head> <meta charset="utf-8"> <title></title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous"> {% load static %} <link rel="stylesheet" href="{% static 'CSS/style.css' %}"> </head> <body> <div id="form"> <form class="row" method="POST"> <div class=""> <input type="textarea" class="form-control" placeholder="أكتب أسمك (مثلا/أخوكم عبدالله العتيبي)" id="text_name" name="user_name"> </div> <div class="col-auto"> <button type="submit" class="btn btn-primary mb-3" id="button">حمل الصورة</button> </div> </form> </div> </body> </html> -
Best way to use "context" on Django templates for many variables / dictionaries
I want to send a lot of data to 1 Django template (to show it on 1 specific page). The data comes from 2 sources: At least 1 list, with many dictionaries inside (I can't change any of this, it comes from Google Ads API). Many variables (I can change them, for example, to turn them into dictionaries or tuples if necessary). The variables are very simple, something like "variable = other_variable / 100" (just 1 value, no need for a key), so I don't need the variables to be turned into a dictionary. But I've understood (maybe wrong) that the "context" from Django's render needs dictionaries. The variables' data comes from the list (I do some calculations using some of the list values), but maybe this is not relevant for my question. Right now I'm doing something like this in my views.py: campaign_data = [] CODE TO FILL THAT LIST WITH API DATA (MANY DICTIONARIES INSIDE) clicks = sum(data['campaign_clicks'] for data in campaign_data) sum_clicks = {"sum_clicks" : clicks} context = { 'campaign_data' : campaign_data, 'sum_clicks' : sum_clicks } return render(request, 'testing.html', context) And then on the Django template I use the data from views.py like this: {% for element … -
Wierd behaviour in django
I am using SQLite in my Django project, I am gathering the data into the database manually with python. everything worked fine in that phase, now when I am trying to reach them in the templates file, something weird is happening, Django keeps giving me a NoReverseMatch match (because I am having a link that is referring to a view for some calculations, this view needs a URL which I have in my template), the weird thing is, when I open my 127.0.0.1:8000/admin and opening the data I've gathered and saved them, Django won't give me an error! it seems I have to do something like migrating my new data manually to project too, its very confusing -
Confirmation email works in localhost but not with ngrok django
I have this code. When I use it in localhost it works but when I use it with ngrok it shows a 400 error. It is strange because if I reload the page twice the error dissapears and it loads the url but it shows: Activation link is invalid!. In views.py: def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = CustomUser.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, CustomUser.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() login(request, user) return HttpResponseRedirect(reverse("index")) else: return HttpResponse('Activation link is invalid!') mail_subject = 'Activate your account.' message = render_to_string('twc/acc_active_email.html', { 'user': user, 'domain': request.get_host(), 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage(mail_subject, message, to=[to_email]) email.send() return HttpResponse('Please confirm your email address to complete the registration') In urls.py: path('activate/<uidb64>/<token>/', views.activate, name="activate"), Finally, acc_active_email: {% autoescape off %} Hi {{ user.username }}, Please click on the link to confirm your registration, http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} -
Multiple search with django foreign key (Related Field got invalid lookup: icontains)
I understand that you can't directly use icontains on a foreign key when searching but I haven't found a solution yet. Here is my search view in views.py (I have imported every model needed): def search(request): # if the user actually fills up the form if request.method == "POST": searched = request.POST['searched'] # author__icontains part is not working posts = Post.objects.filter(Q(title__icontains=searched) | Q(author__author__icontains=searched)) return render(request, 'blog/search.html', {'searched': searched, 'posts': posts}) else: return render(request, 'blog/search.html', {}) Here is my model in model.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) Mainly, this is not working: posts = Post.objects.filter(Q(title__icontains=searched) | Q(author__author__icontains=searched)) The error is Related Field got invalid lookup: icontains -
unresponsive mutation on graphql
When I am injecting values on useMutation it gives me Error 400 140. The data types does match. In appointment_booking argument, I am passing the its ID as a reference on the other table. Here is my Schema class CreateVideoConsultation(graphene.Mutation): id = graphene.Int() client = graphene.String() veterinarian = graphene.String() appointment_booking = graphene.Int() class Arguments: client = graphene.String() veterinarian = graphene.String() appointment_booking = graphene.Int() def mutate(self, info, client, veterinarian, appointment_booking): client_username = Client.objects.get(username = client) veterinarian_username = Veterinarian.objects.get(username = veterinarian) appointment_booking_id = Appointment_Booking.objects.get(id = appointment_booking) video_consultation = Video_Consultation(client = client_username, veterinarian = veterinarian_username, appointment_booking = appointment_booking_id) video_consultation.save() return CreateVideoConsultation(id = video_consultation.id, client = client_username, veterinarian = veterinarian_username, appointment_booking = appointment_booking_id) class Mutation (graphene.ObjectType): create_video_consultation = CreateVideoConsultation.Field() schema = graphene.Schema(query = Query, mutation = Mutation) Here is my model class Video_Consultation(models.Model): client = models.ForeignKey('Client', on_delete = models.DO_NOTHING) veterinarian = models.ForeignKey('Veterinarian', on_delete = models.DO_NOTHING) appointment_booking = models.ForeignKey('Appointment_Booking', on_delete = models.DO_NOTHING) def __str__(self): return str(self.client) Here is my mutation in Graphiql mutation{ createVideoConsultation(client:"GGGG",veterinarian:"Peppermint",appointmentBooking:29){ id client veterinarian appointmentBooking } } { "errors": [ { "message": "int() argument must be a string, a bytes-like object or a real number, not 'Appointment_Booking'" } ], "data": { "createVideoConsultation": { "id": 7, "client": "GGGG", "veterinarian": "Peppermint", "appointmentBooking": null } … -
Custom links in django
Here's my initial code class Article(models.Model): article_author = models.CharField(max_length=12) article_name = models.CharField(max_length=60) article_body = models.TextField() article_date = models.DateTimeField(auto_now_add=True) article_tags = models.CharField(max_length=25, choices=tags_, null=True) article_link = make_link() Turns out it won't be added to the db, and I can't make migrations (prob. because it's not part of .models). (I want the link to be made automatically as the instance of article class is created, and without user) I can just make it a CharField and then replace whatever was there with the function, but that just seems like a sloppy solution, also it'll give a usless field to the default admin-panel. -
Docker web server scale for distributed cpu
version: '3.7' services: web: command: python manage.py runserver 0.0.0.0:8000 build: . volumes: - ./:/usr/src/web/ ports: - "80-83:8000" env_file: - config/.env depends_on: - db restart: always static-file-server: restart: always image: halverneus/static-file-server:latest environment: - SHOW_LISTING=false - DEBUG=false volumes: - ./static/:/web ports: - 3000-3003:8080 db: restart: always image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - config/.env volumes: postgres_data: name: docker_database external: true My docker yml file is above. I have a server so people can download images. But there will be so many request for downloading images.I want to scale my web server to 3 or more. I can add new ports for scale but there is no distribution on the CPUs. Still only one cpu value increases and it comes to 150%. The docker stats for web_server are as below. How can I share the load to other cpu's CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS 9238c8f86a2f server_web_1 137.75% 2.94GiB / 7.714GiB 38.32% 799kB / 193kB 94.3MB / 8.19kB 41 d24e07a1eb55 server_web_2 2.96% 128.8MiB / 7.714GiB 1.63% 115kB / 28.9kB 582kB / 0B 17 1e00778f5d71 server_web_3 2.95% 291.1MiB / 7.714GiB 3.68% 352MB / 7.93GB 34.8MB / 0B 17 -
'Recipe' object has no attribute 'tags'
I am creating a recipe API. Here I have created a nested serializer, i.e. TagSerializer and RecipeSerializer. I am getting a error at "recipe.tags.add(tag_obj)" at the end of for loop. It is giving error " 'Recipe' object has no attribute 'tags'" Serializer.py """ Serializers for recipe APIs """ from rest_framework import serializers from core.models import (Recipe,Tag) class TagSerializer(serializers.ModelSerializer): #moved TagSerializer above to created nested serializer """Serializer for tags.""" class Meta: model = Tag fields = ['id', 'name'] read_only_fields = ['id'] class RecipeSerializer(serializers.ModelSerializer): """Serializer for recipes.""" tags = TagSerializer(many=True, required=False) # to make tags not necessary while creating recipe class Meta: model = Recipe fields = ['id', 'title', 'time_minutes', 'price', 'link','tags'] read_only_fields = ['id'] def create(self, validated_data): #creating function because nested serializer only allows read-only cannot be modified,but we want to modify the data """Create a recipe.""" tags = validated_data.pop('tags', []) #removes tag from validated data recipe = Recipe.objects.create(**validated_data) #created recipe from validated data auth_user = self.context['request'].user #authorising user for tag in tags: tag_obj, created = Tag.objects.get_or_create( #if tag is their it gets or if not creates,helps in removing duplicates user=auth_user, **tag, ) recipe.tags.add(tag_obj) return recipe class RecipeDetailSerializer(RecipeSerializer): """Serializer for recipe detail view.""" class Meta(RecipeSerializer.Meta): #reusing recipe serializer fields fields = … -
Page not found (404) adding a Django page
So I am trying to link up a page on my blog. I have created the template, view and URL for the page but it keeps throwing a 404 error. Could someone please look over my code and help me figure out the issue? add_post.html: {% extends "base.html" %} {% block content %} <header> <div class="post-caption mt-4"> <div class="text-center-caption"> <h1 class="display-5 fw-bolder text-shadow">Add Your Post</h1> <p class="lead text-shadow fw-bold">Tell us about your favourite game</p> </div> </div> </header> {%endblock%} views.py: from django.shortcuts import render, get_object_or_404, reverse from django.views.generic import View, CreateView, ListView from django.http import HttpResponseRedirect from .models import Post from .forms import CommentForm class AddPost(CreateView): model = Post template_name = 'about.html' fields = '__all__' urls.py: from .views import AddPost, PostList, PostDetail, PostLike from django.urls import path urlpatterns = [ path('', PostList.as_view(), name='home'), path('<slug:slug>/', PostDetail.as_view(), name='post_detail'), path('like/<slug:slug>/', PostLike.as_view(), name='post_like'), path('add_post/', AddPost.as_view(), name='create_post'), ] -
Installed both Miniconda and Anaconda
After running the Conda info --envs command I can see that I have both mini- and anaconda installed. Is this a problem? if so how do I remove one? code: (base) ********-MacBook-Pro ~ % conda info --envs # conda environments: # /Users/****/miniconda3 base * /Users/****/opt/anaconda3 -
When i am trying to integrate django with react when i am run webpack got error like below
WARNING in DefinePlugin Conflicting values for 'process.env.NODE_ENV' 1 warning has detailed information that is not shown. Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it. webpack 5.73.0 compiled with 1 warning in 2053 ms -
how to add fix numbers of django channels we can add in every group?
class MySyncConsumer(SyncConsumer): def websocket_connect(self): async_to_sync( self.channel_layer.group_add)('programer',self.channel_name) self.send({ "type" : "websocket.accept" }) -
How to customize the appearance of the password fields of a Django custom registration form?
I want to change the appearance of the input fields in the registration form, but why is the decoration not being applied to the password fields? forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = User fields = ['email', 'username', 'password1', 'password2'] widgets = { 'email': forms.EmailInput(attrs={ 'type': 'email', 'class': 'form-control', 'id': 'exampleInputEmail', }), 'username': forms.TextInput(attrs={ 'type': 'text', 'class': 'form-control', 'id': 'exampleInputUsername', }), 'password1': forms.PasswordInput(attrs={ 'type': 'password', 'class': 'form-control', 'id': 'exampleInputPassword1', }), 'password2': forms.PasswordInput(attrs={ 'type': 'password', 'class': 'form-control', 'id': 'exampleInputPassword2', }), } HTML <label for="exampleInputEmail" class="form-label">Email</label> {{ form.email }} <label for="exampleInputUsername" class="form-label">Username</label> {{ form.username }} <label for="exampleInputPassword1" class="form-label">Password</label> {{ form.password1 }} <label for="exampleInputPassword2" class="form-label">Confirm password</label> {{ form.password2 }} Result -
Django properly remove treebeard
I was using Django treebeard, which then i decided i no longer need it and just went a head reformed the class model that was using it and deleted my migrations and cash files, however my app keeps trying to use django treebeard and throw and error how i can tell my App to actually start fresh. P.S i dont care about the database inside, i just dont want to write the app all over again. This how it looked before : from django.db import models from vessels.models import Vessel from treebeard.mp_tree import MP_Node # Create your models here. class Component(MP_Node): name = models.CharField(max_length=255, blank=True, null=True) manufacturer = models.CharField(max_length=200, blank=True, null=True) model = models.CharField(max_length=200, blank=True, null=True) type = models.CharField(max_length=200, blank=True, null=True) remarks = models.TextField(blank=True, null=True) parent = models.ForeignKey( 'self', null=True, blank=True, on_delete=models.CASCADE, related_name='children') vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_components') def __str__(self): return self.name this is how i want it to be : class Component(models.Model): name = models.CharField(max_length=255, blank=True, null=True) manufacturer = models.CharField(max_length=200, blank=True, null=True) model = models.CharField(max_length=200, blank=True, null=True) type = models.CharField(max_length=200, blank=True, null=True) remarks = models.TextField(blank=True, null=True) parent = models.ForeignKey( 'self', null=True, blank=True, on_delete=models.CASCADE, related_name='children') vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_components') def __str__(self): return self.name … -
Strawberry Django specific Graphql queries other than pk not working
I am having issues making specific queries using the Strawberry library. Lets say I have two Django models: class Address(models.Model): name = models.CharField() class Person(models.Model): name = models.CharField() address = models.ForeignKey('Address', on_delete=models.CASCADE, blank=False, null=False) with my type.py file: @strawberry.django.type(models.Address) class Address: id: auto name:auto @strawberry.django.input(models.Address) class AddressInput: id: auto name:auto @strawberry.django.type(models.Person) class Person: id: auto name: auto address:'Address' @strawberry.django.input(models.Person) class Person: id: auto name: auto address:'AddressInput' and schema.py: @strawberry.type class Query: address: Address = strawberry.django.field() addresses: List[Address] = strawberry.django.field() person: Person = strawberry.django.field() persons: List[Person] = strawberry.django.field() schema = strawberry.Schema(query=Query) In the graphiql terminal if I wanted id for Person it works fine: #Query query MyQuery { person(pk: "1") { address { id name } id name } } #Return value { "data": { "person": { "address": { "id": "1", "name": "Compound" }, "id": "1", "name": "William" } } } But if I try searching by address id or person name it does not work. All of these query following do not work query MyQuery { person(name: "William") { address { id name } id name } } query MyQuery { person(data: {name: "William"}) { address { id name } id name } } query MyQuery { person(address: {id: "1"}) … -
how to get price range with django?
i have price model class Product(models.Model): price = models.IntegerField membership_discount = models.DecimalField if i get price parameter, (ex. min_price = 100000, max_price = 500000) I want to get the products multiplied by the price fields and membership_discount fields. not this Product.objects.filter(price__range = (min_price, max_price)) i want Product.objects.filter(price * (1+membership_discount)__range = (min_price, max_price)) -
How to combine two different models on the basis of user and send a single response- Django Rest Framework
I have two different models in my project. The StudentDetail model has an one-to-one connection with the student-user and the EnrollmentList has a foreign key connection with the student user. I want to combine information from both the models for that specific student-user and send them as as a single response rather than sending different responses. Below are the models and their serializers StudentDetail/models.py class StudentDetail(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, blank=True) StudentDetailSerializer class StudentDetailSerializer(serializers.ModelSerializer): class Meta: model = StudentDetail fields = "__all__" Enrollment/models.py class EnrollmentList(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) student = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='student') EnrollSerializer class AllReqs(serializers.ModelSerializer): class Meta: model = EnrollmentList fields = ['id','student_name', 'student_parent_name', 'standard', 'applying_for_standard', "board", 'home_tuition', 'address'] Now suppose a request is made, I want to combine the information from the StudentDetail and EnrollmentList for that specific student user to get a serialized data which may look like below example and send this as a single response { "student_name": name, #from StudentDetail "home_tuition": home_tuition #from EnrollmentList } Please suggest to me the correct way to do it -
Delivery management in Python
I want to develop an open source delivery management, python web-based (Django) software to have multi-point pick up and multi-point drop. Is this an already developed opensource free project? If not, how do I start? -
Django django.db.utils.IntegrityError
We've a table with thousands of rows. Now we are in need to make 1 existing field to be Foreign Key from another table. Table 'list' got all the names and their details. Table 'State' is a new table included later and used to link it to the existing 'List' table. Model is as below, class List(models.Model): Lid = models.AutoField(primary_key=True) Name = models.CharField(max_length=100) addr1 = models.CharField(max_length=100) addr2 = models.CharField(max_length=100) City = models.CharField(max_length=40) State = models.ForeignKey(State,blank=True, on_delete=models.DO_NOTHING, default=None,to_field="state",db_column="State") #,to_field="state",db_column="State" Below is the error appears when tried to migrate, IntegrityError( django.db.utils.IntegrityError: The row in table 'list' with primary key '1' has an invalid foreign key: list.State contains a value '' that does not have a corresponding value in State.state. How to fix this issue? I did add those 'blank=True' and on_delete=models.DO_NOTHING after searching for a solution in google, still no luck. -
Is there any way to perform operation on django model on read
I am using a model something like this class MyModel(models.Model): text=models.CharField(max_length=200) viewed=models.BooleanField(default=False,editable=False) I want to set viewed=True when user gets the text. I tried to do it in views.py. But the problem is I need to write the same logic twice for admin site. Is there any way I can perform this in model. Thank you. -
Django and waypoints Infinite scroll not working
I have tried all the answers on stack and the infinite scroll is still not working. My home.html is still displaying the pagination. I suspect the problem is with jquery or the js files or with how the static file is loaded? Here is my home.html: {% block content %} {% load static %} <div class="infinite-container"> {% for post in posts %} <div class="infinite-item"> <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> </div> {% endfor %} </div> <div class="d-flex d-none position-fixed" style="top:35vh;left:46vw"> <button class="btn btn-primary loading"> <span class="spinner-border spinner-border-sm"></span> Please wait... </button> </div> <!--pagination logic --> <div class="col-12"> {% if page_obj.has_next %} <a class="infinite-more-link" href="?page={{ page_obj.next_page_number }}">next</a> {% endif %} </div> <script src="/static/js/jquery.waypoints.min.js"></script> <script src="/static/js/infinite.min.js"></script> <script> var infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0], offset: 'bottom-in-view', onBeforePageLoad: function () { $('.loading').show(); }, onAfterPageLoad: function () { $('.loading').hide(); } }); </script> {% endblock content %} In my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [Path(BASE_DIR, 'static'),] The directory of my js files. I have added the following …