Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am trying to work with Django CMS and templates. but get an error while editing a template
I want the css and js file to load. It will display the error "Invalid block tag on line 15: 'static'. Did you forget to register or load this tag?" is displayed. but I have created the data correctly. does anyone see the error in my html file? Here is the code where I suspect the problem <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'css/modern-business.css' %}" rel="stylesheet"> Here is the complete code {% load cms_tags menu_tags sekizai_tags %} <!DOCTYPE html> <html lang="{{ LANGUAGE_CODE }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content="{% page_attribute 'meta_description' %}"> <meta name="author" content="Life Imaging Services GmbH"> <title>{% page_attribute "page_title" %}</title> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <!-- Custom styles for this template --> <link href="{% static 'css/modern-business.css' %}" rel="stylesheet"> {% render_block "css" %} </head> <body> {% cms_toolbar %} <!-- Navigation --> <nav class="navbar fixed-top navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="index.html">Start Bootstrap</a> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> {% show_menu 0 100 100 100 %} </ul> </div> … -
Django Update Form, show current value with choicefield
I have a django form (updating a record in the database) where I'm displaying different values instead of true/false for a boolean field. Is there a way for me to display the "old"/current value instead of always displaying the first choice in the list? If checked is FALSE in the database, going to the edit form shows "Successful", instead of "Still needs to be checked". This should be the other way around. class SuccesfullCheckForm(forms.ModelForm): TRUE_FALSE_CHOICES = ( (True, 'Successful'), (False, 'Still needs to be checked')) checked = forms.ChoiceField(choices=TRUE_FALSE_CHOICES, required=True) class Meta: model = SuccesfullCheck fields = ["checked"] -
custom user authentication work fine with python3.5 but doesn't work well with python3.6
I just download this git project here this is a demo of the project here after I install requirements.txt work very fine with python3.5 but if I switch to python3.6 or 3.8, can not see user profile and if try to click on user view profile, its just download the file or show profile.html template script tagged, I thought python3.5 and python 3.6 should be almost same how come it's not work in python 3.6 already I checked all package which I have in python 3.5 moved to python 3.6 I tried this comment pip3.5 list | awk '{print $1}' | xargs -I{} pip3.8 install {} to move all package and also I tried manually check if I don't have any uninstall package -
Resizing the photo by protecting the aspect ratio on Django
How can I resize image when I upload with ImageField by protecting aspect ratio of image. Example: (Width x Height) from 1100x600 to 550x300 And, is it possible with [ImageKit] ? https://github.com/matthewwithanm/django-imagekit -
python replace two list data from another list
In python in one variable i am getting list like : stop_address_type = ['1','2'] and in another variable i am getting like : stop_facility_name = ['A','B'] Result : this is what i actually want stop_address_type = ['1','2'] stop_facility_name = ['','B'] another situation like : stop_address_type = ['2','1'] stop_facility_name = ['A',''] what i actually want is when i ll get the 1 value in stop_address_type variable i want to blank the same value of list stop_facility_name like : -
Django: how to remove the space between project urls.py and app urls.py
Django 2.7, I have below project urls.py from main.main_config import main_config from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'keypad.views.home', name='home'), # url(r'^keypad/', include('keypad.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^%sactivation/' % main_config.url_prefix, include('activation.urls', namespace='activation')), url(r'^%sac6590e0/' % main_config.url_prefix, include('activation.urls', namespace='activation')), url(r'^%sreport/' % main_config.url_prefix, include('report.urls', namespace='report')), url(r'^%srpccb4a9/' % main_config.url_prefix, include('report.urls', namespace='report')), url(r'^%scloudctl/' % main_config.url_prefix, include('cloudctl.urls', namespace='cloudctl')), url(r'^%sct8a8d6a/' % main_config.url_prefix, include('cloudctl.urls', namespace='cloudctl')), url(r'^%sadmin/data/' % main_config.url_prefix, include('explorer.urls')), url(r'^%sadmin/' % main_config.url_prefix, include(admin.site.urls)), url(r'^%s' % main_config.url_prefix, include('main.urls', namespace='main')), ) and the app's urls.py is as below: from django.conf.urls import patterns, url from main import views urlpatterns = patterns('', url(r'checkConnection/$', views.checkConnection, name='checkConnection'), url(r'c94372af/$', views.checkConnection, name='checkConnection'), url(r'get_data_everyday/$', views.get_data, name='get_data_everyday'), url(r'downloads/(?P<color>[yb]{1})/(?P<placeID>[0-9]{4})/$', views.downloads, name='downloads'), url(r'suggestion/(?P<ver1>[0-9])/(?P<ver2>[0-9])/(?P<ver3>[0-9])/$', views.suggestion, name='suggestion') ) And the picture shows the problem I got. There is a space between project urls and "include" urls. I have no idea how this happen. Can anyone help? Thanks. Error -
Implementing pagination in Django with Oracle database
I have a project utilizing Oracle as database, and inside the db, they have a view. For that view, I have a Django model like this: class MyOrmModel(models.Model): # fields class Meta: db_table = 'target_oracle_view' managed = False The corresponding viewset: class LogRecordNewItemViewSet(ListModelMixin, GenericViewSet): serializer_class = # ... pagination_class = None def get_queryset(self): qs = MyOrmModel.objects.all() return qs I use cx-Oracle==7.3.0 to connect to the target database. Now my goal is to implement pagination. But when I do so, I run into an error class LogRecordNewItemViewSet(ListModelMixin, GenericViewSet): serializer_class = # ... pagination_class = LimitOffsetPagination django.db.utils.DatabaseError: ORA-00933: SQL command not properly ended I have come across this discussion, but downgrading Django to version 2.0.6 does not work. Here are my requirements.txt content: appdirs==1.4.3 asgiref==3.2.9 CacheControl==0.12.6 certifi==2019.11.28 chardet==3.0.4 colorama==0.4.3 contextlib2==0.6.0 cx-Oracle==7.3.0 distlib==0.3.0 distro==1.4.0 Django==2.0.6 django-cors-headers==3.4.0 djangorestframework==3.11.0 djangorestframework-camel-case==1.2.0 djangorestframework-jwt==1.11.0 html5lib==1.0.1 idna==2.8 ipaddr==2.2.0 lockfile==0.12.2 msgpack==0.6.2 packaging==20.3 pep517==0.8.2 progress==1.5 PyJWT==1.7.1 pyparsing==2.4.6 pytoml==0.1.21 pytz==2020.1 requests==2.22.0 retrying==1.3.3 sentry-sdk==0.16.2 six==1.14.0 sqlparse==0.3.1 urllib3==1.25.8 webencodings==0.5.1 psycopg2 -
Facebook Login with custom user model
m trying to create a new user with Social-Auth and my custom user model required a phone number but facebook does not allow it so i get this error TypeError at /social-auth/complete/facebook/ create_user() missing 1 required positional argument: 'phone' settings.py SOCIAL_AUTH_FACEBOOK_KEY = 'XXXXXXXXXX' SOCIAL_AUTH_FACEBOOK_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXX' SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] # add this SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email, picture.type(large), link' } SOCIAL_AUTH_FACEBOOK_EXTRA_DATA = [ ('name', 'name'), ('email', 'email'), ('picture', 'picture'), ('link', 'profile_url'), ] how can i pass a default parameter to avoid this error or any solution to work around this problem -
Problem sending information using POST method in django rest framework
Hi i'm knew in django rest framework: views.py: from django.shortcuts import render from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from .models import Book from .serializers import BookModelSerializers . . . # for posting data class PostModelData(APIView): def post(self, request): serializer = BookModelSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py: from django.db import models from datetime import datetime class Book(models.Model): name = models.CharField(max_length=150, blank=True) store_name = models.CharField(max_length=50, blank=True) description = models.TextField(blank=True) image = models.ImageField( default='', upload_to='store_image/', null=True, blank=True) fav = models.BooleanField(default=False, blank=True) created_at = models.DateTimeField(default=datetime.now()) def __str__(self): return self.name urls.py: from django.urls import path from .views import GetAllData, Getfavdata, UpdateFavData, PostModelData urlpatterns = [ path('getalldata/', GetAllData.as_view()), path('getfavdata/', Getfavdata.as_view()), path('updatefavdata/<int:pk>/', UpdateFavData.as_view()), path('postmodeldata/', PostModelData.as_view()), ] serializers.py: from rest_framework import serializers from .models import Book class BookModelSerializers(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' when i post ('name','store_name','description','fav') whit postman, The data that is stored is without details. I wanted to know what the problem is? I also removed (blank = True) in models.py, nothing is saved. -
How to update and save model's field in Django
Following is my code, Every time I click Like (or Dislike) link, both Dislike and Like are incremented. I am new to django, your help will be much appreciated. Thank you Here is my models.py, from django.db import models from django.urls import reverse # Create your models here. class Movies(models.Model): Director=models.CharField(max_length=30) Cast_I=models.CharField(max_length=30) Cast_II=models.CharField(max_length=30) Name=models.TextField() ReleaseYear=models.IntegerField() ImdbRating=models.CharField(max_length=2) Genre=models.TextField(null=True) Language=models.CharField(max_length=20,null=True) Like=models.IntegerField() Dislike=models.IntegerField() def like_this_movie(self): self.Like+=1 self.save() return reverse ('list',kwargs={}) def dislike_this_movie(self): self.Dislike+=1 self.save() return reverse ('list',kwargs={}) Here is the template, {% block content %} <p> <a href="{{ object.like_this_movie }}">Like</a> <a href="{{ object.dislike_this_movie }}">Dislike</a> </p> {% endblock %} Here is my view class, class MovieDetailView(DetailView): template_name='movie/detail.html' queryset=Movies.objects.all() -
Django logs print statemeents are not writing to file
In django i am adding logging and storing logs to file. It is writing to files the infor and errors But not print statements. No print statements are coming. I wants to write all including print statements also. LOGGING = { 'version': 1, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'logs.log', 'formatter': 'simple' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, } } Please have a look, how i can achive this. -
Problem integraing Wiris math type and chem type with django using tiny mce editor
I am new to Django. I want to integrate wiris math type plugin in tinymce into the Django template. Same thing works in Laravel framework but in django it is giving problem. error messages It is giving Failed to initialize plugin: tiny_mce_wiris SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Can anyone help me out? -
python manage.py runserver is not working
so before anyone point it out my question is really similar to this question but the error message is slightly different so i just started learning Django this day and i got stuck because when i ran python manage.py runserver it didn't display anything until i hit "CTRL + C" then this message showed up Performing system checks... System check identified no issues (0 silenced). July 30, 2020 - 15:51:40 Django version 2.1.5, using settings 'trydjangofcc.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. (mine) I tried to go to the http://127.0.0.1:8000/ and it didn't work, I've tried python manage.py migrate still nothing . I've waited an hour to see if it makes a difference and it don't. it seems stupid but I've been stuck here for a while Thank you -
Wrong: /admin/login/, Expected: /accounts/login/
Django==3.0.8 django-comments-xtd==2.6.2 views.py @csrf_protect @login_required def like(request, comment_id, next=None): """ Like a comment. Confirmation on GET, action on POST. Templates: :template:`django_comments_xtd/like.html`, Context: comment the flagged `comments.comment` object """ comment = get_object_or_404(get_comment_model(), pk=comment_id, site__pk=get_current_site_id(request)) if not get_app_model_options(comment=comment)['allow_feedback']: ctype = ContentType.objects.get_for_model(comment.content_object) raise Http404("Comments posted to instances of '%s.%s' are not " "explicitly allowed to receive 'liked it' flags. " "Check the COMMENTS_XTD_APP_MODEL_OPTIONS " "setting." % (ctype.app_label, ctype.model)) # Flag on POST if request.method == 'POST': perform_like(request, comment) return next_redirect(request, fallback=next or 'comments-xtd-like-done', c=comment.pk) # Render a form on GET else: flag_qs = comment.flags.prefetch_related('user')\ .filter(flag=LIKEDIT_FLAG) users_likedit = [item.user for item in flag_qs] return render(request, 'django_comments_xtd/like.html', {'comment': comment, 'already_liked_it': request.user in users_likedit, 'next': next}) Problem When an incognito user presses a like button, they are redirected to http://localhost:8000/admin/login/?next=/%5Ecomments/like/3/ I expect it to be redirected to http://localhost:8000/accounts/login/ In settings.py LOGIN_URL is absent. I'm at my wit's end about where this admin/login comes from. Could you help me here& -
Recaptcha v3 is backend implementation necessery?
I am building a site using django and I have a form where I want to use reCAPTCHA v3. Google's documentation states that there are two options. Either automatically bind the challenge to a button or to programmatically invoke the challenge. My question is whether I need to implement any backend changes while using the first option (automatic binding), cause by reading the documentation I can't figure it out. Thanks for your time! -
DevTools failed to load sourcemap problem: Could not load content
I have downloaded the free theme that can run to my Django server. I debug all things using static but the only front background image is not appearing on the server due to these problems in the console. Help me to get rid of this please. -
How to determine best batch_size for a queryset?
I have a model with 1M+ records. Whenever I do query on this model, I make sure not to get all the objects at once, so I use batching. Right now I use hard coded batch size of 100,000. But is there a way to determine best batch_size for any model I use. I mean on what factors does my batch_size depend on? I use MySQL as database. -
table * has no column named user_id,django
i have a app in which i have a foodpost model which has a foreign key for user. now when i m trying to save instance of foodpost model i m getting "table Food_foodpost has no column named user_id" i tried deleting migrations,makemigrations and migrate here is my foodpost model from django.db import models from django.contrib.auth.models import User # Create your models here. class FoodPost(models.Model): title = models.CharField(max_length=100,null=False) details = models.TextField() image = models.ImageField(upload_to='Food/',blank = True) quantity = models.IntegerField() category = models.CharField(max_length=100) location = models.CharField(max_length=100) price = models.IntegerField() # slug = models.SlugField(unique=True) created_post = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE,related_name='FoodPost') # likes, no. of views def __str__(self): return self.title def delete(self,*args, **kwargs): self.image.delete() super().delete(*args,**kwargs) serializer class FoodPost_seriallizer(serializers.ModelSerializer): class Meta: model = FoodPost fields =['title', 'details', 'image', 'quantity', 'category', 'location', 'price', 'created_post', 'status', ] def create(self,validated_data): # print() # print(validated_data) foodPost = FoodPost(**validated_data,user=self.context.get("user")) foodPost.save() # foodPost.save() return foodPost and the view @api_view(['POST']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) # @parser_classes([JSONParser,FormParser,MultiPartParser]) def create_post(request): serializer = FoodPost_seriallizer(data = request.data,context = {"user":request.user}) if serializer.is_valid(raise_exception=True): foodpost = serializer.save() return Response(serializer.data) and of course the error File "/home/j0/anaconda3/envs/foodagram/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/j0/anaconda3/envs/foodagram/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: table Food_foodpost … -
Django webpage only displays properly if a character is placed after {% load static %}
If I structure the first two lines of my HTML doc like this: {% load static %} <!DOCTYPE html> It appears that none of the javascript or CSS run properly, and the webpage displays like this: However, if I put any character after the {% load static %} expression, For example, if I structure the first two lines of my HTML doc like this: {% load static %}. <!DOCTYPE html> Then the scripts and CSS components run properly and the webpage displays as it should. Why is this? -
How to make comments serializer work with post serializer in django rest framework.?
I have this comment serializer which is not working. It is showing this error { "post": [ "This field is required." ] } I am quite new to this, so can't really figure out how to properly link both the post and comment model. this is my serializer class CommentCreateSerializer(serializers.ModelSerializer): content = serializers.CharField() post = PostSerializer(many=True) class Meta: model = Comment fields = ['id', 'post', 'content', 'reply'] def create(self, validated_data): user = self.context['request'].user content = validated_data['content'] reply = validated_data['reply'] if reply: comment = Comment(user=user, content=content, reply=reply, post=post) comment.save() else: comment = Comment(user=user, content=content, post=post) comment.save() return validated_data view @api_view(['POST']) def comment_post_api(request, slug): try: post = get_object_or_404(Post, slug=slug) except Post.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = CommentCreateSerializer(post,data=request.data, context={'request':request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls path('<slug>/comment/', views.comment_post_api, name='comment_post'), Thanks -
Django when using python-ffmpeg-video-streaming get error The system cannot find the file specified in
In Django im using python-ffmpeg-video-streaming. AND this is my CODE: from django.conf import settings import ffmpeg_streaming from ffmpeg_streaming import Formats, Bitrate, Representation, Size video_file_path = settings.MEDIA_ROOT + '/' + self.video_path video = ffmpeg_streaming.input(video_file_path + 'video.mp4') _480p = Representation(Size(854, 480), Bitrate(750 * 1024, 192 * 1024)) _720p = Representation(Size(1280, 720), Bitrate(2048 * 1024, 320 * 1024)) hls = video.hls(Formats.h264(), hls_list_size=10, hls_time=5) hls.representations(_480p, _720p) hls.fragmented_mp4() hls.output(video_file_path + 'hls.m3u8') when i run my i get this error. but i can see 'hls.m3u8' in file path directory. FileNotFoundError at /cpanel/videos/new/ [WinError 2] The system cannot find the file specified Request Method: POST Request URL: http://127.0.0.1:8000/cpanel/videos/new/ Django Version: 3.0.8 Exception Type: FileNotFoundError Exception Value: [WinError 2] The system cannot find the file specified -
Development wsgi server is getting stuck while returning a HttpResponse() in Django (debug=True)
I am sending username and password from the frontend using an ajax call to backends login() (in view.py) in django . where first I am authenticating the username and password and then setting the session variables for the same. After this, I am returning a message whether login is successful or not using: def login(request): user = request.POST.get('user') pwd = request.POST.get('pwd') msg = verify_user_credentials(user, pwd) if msg == True: reuest.session['user'] = user request.session['pwd'] = pwd return HttpResponse(msg) But while returning it is getting stuck and holding a terminal. So, the whole tool is getting hung. login() successfully checking the credentials and adding them up in session successfully each and every time but don't know why it is getting stuck while returning the HttpResponse(msg) in some cases. Additional Information: verify_user_credentials() is an internal function that verifies the user credentials. I am using debug = True, As tool is running in development mode. -
django error 1146 "Table 'buysell.sell_sellform' doesn't exist"
I am trying to create a form and store its data in the database I have created the model but then also it is showing error. models.py from django.db import models from django.contrib.auth.models import User class SellForm(models.Model): FICTION = 'fiction' Course = 'course' Non_Fiction = 'nonfic' book_category = [ (FICTION, 'Fiction'), (Course, 'Course'), (Non_Fiction, 'Non fiction'), ] NEW = 'new' OLD = 'old' book_condition =[ (NEW,'new'), (OLD, 'old'), ] ENGLISH = 'eng' HINDI = 'Hindi' book_lang =[ (ENGLISH,'english'), (HINDI,'hindi'), ] title = models.CharField(max_length=100) author = models.CharField(max_length=100) price = models.IntegerField() Category = models.CharField(max_length=20,choices=book_category,default=Course,) Condition = models.CharField(max_length=20,choices=book_condition,default=OLD) Language = models.CharField(max_length=20,choices=book_lang,default=HINDI) Description =models.CharField(max_length=200) book_img = models.ImageField(upload_to='images/') user = models.ForeignKey(User, on_delete=models.CASCADE) forms.py from django import forms from .models import SellForm class FromSellForm(forms.ModelForm): class Meta: model = SellForm fields = ["title","author","price","Category","Condition","Language","Description","book_img"] views.py from django.shortcuts import render,redirect from django.http import HttpResponse from .forms import FromSellForm # Create your views here. def sell_book(request): if request.method == 'POST': form = FromSellForm(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = FromSellForm() context = {'form':form} return render(request,'buy/sellbook.html',context) sellbook.html <form method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> urls.py of sell app from django.urls import path from . import views urlpatterns = [ path('sell_book/', views.sell_book,name="sell_book"), ] … -
Django reset password: invalid token
I have deployed my Django project on production and test password reset using Django authentication I receive an email with link but I got the message 'Invalid token' meaning that link is invalid Settings.py ALLOWED_HOSTS = ['192.xxx.xx.xx','http://example.com/','https://example.com/'] #example.com replace by my real domain CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = ['example.com'] password_reset_email.html Une demande de modification de mot de passe a été demandé par {{ email }}. Veuillez suivre ce lien : {{ protocol}}://example.com{% url 'password_reset_confirm' uidb64=uid token=token %} PS : Merci de ne pas répondre à cet email -
making normal paginator buttons in django and bootstrap
i use django Paginator and use bootstrap4 in my templates projects. this my paginator code in my view : if request.method == "GET": orders = ProductOrder.objects.filter(status=1).order_by('-created_at') orders = Paginator(orders,5) page = request.GET.get('page') if page is None : page = 1 order_list = orders.page(page) print(len(orders.page_range)) index = order_list.number - 1 max_index = len(orders.page_range) start_index = index - 3 if index >= 3 else 0 end_index = index + 3 if index <= max_index - 3 else max_index page_range = list(orders.page_range)[start_index:end_index] for o in order_list: o.product.name = get_product_name(o.product) statuses = Status.objects.all() context = { 'orders' : order_list, 'page_range' : page_range, 'statuses' : statuses } return render(request,'staff/orders/products.html',context) and this is paginator section in html template : <ul class="pagination"> {%if orders.has_previous%} <li class="page-item"> <a class="page-link" href="?page={{orders.previous_page_number}}" tabindex="-1">قبلی</a> </li> {%else%} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1">قبلی</a> </li> {%endif%} {% for pg in page_range %} {% if blogs.number == pg %} <li class="page-item active"><a href="?page={{pg}}" class="page-link">{{pg}}<span class="sr-only">(current)</span></a></li> {% else %} <li class="page-item"><a href="&page={{pg}}" class="page-link">{{pg}}</a></li> {% endif %} {% endfor %} {%if orders.has_next%} <li class="page-item"> <a class="page-link" href="?page={{orders.next_page_number}}" tabindex="-1">بعدی</a> </li> {%else%} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1">بعدی</a> </li> {%endif%} </ul> code above render a paginator like this : paginator section as well you see last …