Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when trying to annotate a dict with Subquery
I have the following models: class Location(models.Model): system_key = models.CharField(max_length=20, unique=True) active = models.BooleanField(default=True) name = models.CharField(max_length=256) account = models.ForeignKey(Account,on_delete=models.CASCADE) ... class LocationScores(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE,related_name=LOCATION_SCORES) date = models.DateField(default=now) first_score = models.PositiveSmallIntegerField(default=0) second_score = models.PositiveSmallIntegerField(default=0) third_score = models.PositiveSmallIntegerField(default=0) I'm looking for a way to annotate on a location a given list of scores from it's latest entry most efficiently (DB queries wise). Since a Prefetch Object can't filter the latest object I don't want to do the following: locations =Location.objects.filter(account=account).prefetch_related(Prefetch(lookup=LOCATION_SCORES, queryset=LocationScores.objects..order_by('-date'), to_attr='scores_by_date') )) this would maybe be an efficient query, but since each location might have thousands of records and the endpoint could serve a lot of locations it becomes very memory heavy. so I tried using Subquery, the closest I came is: class LocationScoresManager(models.QuerySet): def get_latest_location_scores(self, location_scores_names): scores_query = LocationScore.objects.filter(location=OuterRef('pk')).order_by('-date').values(*location_scores_names)[0] annotations = {score: Subquery(scores_query)[score] for score in location_scores} return self.annotate(**annotations) # adding it to the Location Model: class Location(models.Model): # same as before... scores = LocationScoresManager.as_manager() scores_list = ['first_score','third_score'] locations = Locations.scores.filter(account=account).get_latest_location_scores(scores_list) This raises: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. -
I have problem with django login view about auth lib
I have problem about auth system. It only work by username and password, but I need use email rather than username def login_view(request): if request.user.is_authenticated or request.user.is_staff or request.user.is_superuser: return redirect('/account/') elif request.method == "POST": email = request.POST['email'] password = request.POST['password'] user = authenticate(request, email=email, password=password) if not grecaptcha_verify(request): context = {'message_bad':'...'} if user is not None: login(request, user) return redirect('/account/') else: context = {'message_bad':'...'} else: context = {} return render(request, "login.html", context) Please help me or how can I change login() codes at auth lib . -
Custom Password Hash using MD5 and TripleDES
I know it may not be the best combination for password storing but how can I build a password hash using those two? -
Which pattern is implemented in Django Middleware? (Chain of responsibility or Decorator)
I'm trying to figure out what pattern is used in Django Middleware. Maybe there is combination of patterns? -
Linking a Vue file with Django template
I have a Django project contains multiple templates like this: <body> <div> <ul> <li> <a href="#"> customers </a> </li> </ul> </div> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> <!-- place project specific Javascript in this file --> <script src="{% static 'js/project.js' %}"></script> <script> {% include 'vue_dashboard.js' %} </script> </body> the vue_dashboard.js file is the following var app = new Vue({ el: '#vue_app', delimiters: ["{(", ")}"], data: function () { return { selected: 'group', } }, methods: { change_selected: function (type) { this.selected = type; }, } Now, I'm trying to use this vue method inside my <a> tag for example like this: <a href="#" onclick="change_selected(type='customers')"> customers </a> then inside some other div obtain the value of the selected variable in the data section: <div> {{selected}} </div> I've also tried: {% verbatim %} {{ selected }} {% endverbatim %} and few other things, I know I'm using it wrong, but what's the right way to do so? I'm not even sure if my template can communicate with the vue file like this -
Permission-Based Class Based Views Django
How do I make it such that you can only view the members list if you are part of the member list. I don't even know what the "permission required" in my MemberListView as this part was done by my expert friend, so I commented it out. (Hope someone can share what that is as well, super new to writing class based views) Basically for my current code, I tried to make it such that if the user that is currently logged in don't belong in the list, they will be redirected away. models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False, unique=True) body = models.TextField(max_length=5000, null=False, blank=False) members = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="members") class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) views.py class MemberListView(LoginRequiredMixin,BlogPostMixin, DetailView): login_url = 'must_authenticate' template_name = "HomeFeed/membersof_yourpost.html" #permission_required = ('blogpost.view_all_blogpost_members') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.user in object.members.all: return render('HomeFeed/membersof_yourpost.html', context) else: return render('HomeFeed/snippets/home.html', context) template: <ul> {% for member in object.members.all %} <li>{{member.username}}</li> {% endfor %} </ul> -
Build an FTP client in Django Project
I'm developping a Django App/Website with Python just locally, for myself, not for work or anything. For now, everything is perfect and all my features are functionals (LDAP authentication, store infos and pictures in database, etc..). I have an LDAP server, an FTP server and my "Django server". Now, I would like to build in my Django project a page which will be able to upload/download files on my FTP server. I've already built a Tkinter app to upload/download file throught an FTP server when I was learning Python. But now, I'm feeling lost because I really don't know how to put a such interface in Django MVT structure... Maybe is it possible in others languages (Java, PHP,.. ?) ? I really don't know so I'm asking to the community if anyone has an idea. Hope you understand evrything. -
Is there any django app for internal notification in the website?
I have created a simple blog and inside I need to add a notification system that user gets informed when: create a post, when his/her post get declined by admin, when his/her post receives any upvote/downvote and etc. I have found three choices: django-notification django-notification-system Create a model manually like this old tutorial in youtube If you have experience in this topic, can you please guid me, which one should II choose, or is there any easy(with a well written documentation) and better solution? -
How to solve the Identical URL Pattern Conflict in Django?
while practicing on Django I have faced the following problem of Identical URL Pattern. I have tried but fail to solve. My project has one apps and the models are class Category(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(unique=True,blank=True, max_length=255) class Post(models.Model): title = models.CharField(max_length=200) cats = models.ForeignKey(Category, on_delete=models.CASCADE) slug = models.SlugField(unique=True,blank=True, max_length=255) My urls.py from django.contrib import admin from django.urls import path from post import views as apps urlpatterns = [ path('admin/', admin.site.urls), path('<slug:slug>/', apps.categoryView, name='category'), path('<slug:slug>/',apps.PostView, name='calc_detail'), ] Problem: When I Put '/' in the second line of the urlpattern for Category View, category View works but post View doesn't work (404). If remove '/' urlpattern for CategoryView , then post view Works but Category Views shows 404. How should I configure these urls. I am using function based views -
Fieldset values displaying in profile page but if another person registered it showing error in profile page -django
I have member table for registered persons.. I want to display that member table values of particular person in profile page who is logged in... i used Member.objects.get() data is displaying in the profile page of the person who is logged in. but if another person registered it showing error in profile page like.. MultipleObjectsReturned at /web/profile/ get() returned more than one Member -- it returned 2! this is views.py code def profile(request): member = Member.objects.get() print(member.Email) return render(request, 'web/profile.html',{'member':member} ) Thanking You in Advance. You will be highly appreciated, if you could suggest the implementation -
Django contact form not showning the sender's email
am working on a contact form that sends emails, when i try sending emails, both the sender and the receiver is same value of henryochieng8@gmail.com, kindly help out here is my settings.py file ALLOWED_HOSTS = [] EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'henryochieng8@gmail.com' EMAIL_HOST_PASSWORD = '*******' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' views.py def Contacts(request): if request.method == "POST": message_name = request.POST.get('message-name') message_subject = request.POST.get('message-subject') from_email = request.POST.get('from-email') message = request.POST.get('message') send_mail( message_subject, message, from_email, ['henryochieng8@gmail.com'], fail_silently=False, ) return render(request, 'Contacts/index.html', {'message_subject':message_subject}) else: return render(request, 'Contacts/index.html', {}) my html form <form method="post" action="{% url 'Contacts' %}"> {% csrf_token %} <div class="form-group"> <label class="sr-only" for="fname">First Name *</label> <input class="required form-control" id="message-name" name="message-name" placeholder="First Name&nbsp;*" type="text" required="required"> </div> <div class="form-group"> <label class="sr-only" for="lname">Last Name *</label> <input class="required form-control" id="message-lname" name="message-lname" placeholder="Last Name&nbsp;*" type="text" required="required"> </div> <div class="form-group"> <label class="sr-only" for="contactEmail">Email *</label> <input class="required form-control h5-email" id="from-email" name="from-email" placeholder="Email&nbsp;*" type="text" required="required"> </div> <div class="form-group"> <label class="sr-only" for="contactPhone">Subject *</label> <input class="required form-control h5-phone" id="message-subject" name="message-subject" placeholder="Subject&nbsp;*" type="text" required="required"> </div> <div class="form-group"> <label class="sr-only" for="comment">Type your message here</label> <textarea class="required form-control" id="message" name="message" placeholder="Type your message here&nbsp;*" rows="6" required="required"></textarea> </div> <button class="btn btn-accent" type="submit">Submit</button> </form> </div> -
Unable to get progress count in django admin
I want to track the company refreshed data under each source in a progress bar. Company Model class Company(models.Model): name=models.CharField(db_index=True,max_length=50000,blank= True,null=True) source_name= models.ManyToManyField(Source, blank= True) def __str__ (self): return str(self.name) def source(self): # return self.source_name.get() return ",".join([p.source_name for p in self.source_name.all()]) Source Model class Source(models.Model): source_name = models.CharField(max_length=285, blank= False,null=True) slug = models.CharField(max_length=32,blank=True,null=True) modified_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) missing_data = models.BooleanField(default=False) refresh_data = models.BooleanField(default=False) email_refresh_days = models.IntegerField(default=0, null=True, blank = True) def refreshed_data(self): if self.refresh_data and self.missing_data: percentage = round((self.refresh_data / self.missing_data * 100), 2) else: percentage = 0 return format_html( ''' <progress value="{0}" max="100"></progress> <span style="font-weight:bold">{0}%</span> ''', percentage ) Admin class SourceAdmin(admin.ModelAdmin): list_display= ('id','source_name','missing_data','refresh_data','email_refresh_days','modified_date_refresh','modified_date_search','date_added',refreshed_data') search_fields = ['id','source_name',] readonly_filds =('refreshed_data') ordering = ['-date_modified'] def save_model(self, request, obj, form, change): if 'missing_data' in form.changed_data: obj.modified_date_missing = timezone.now() if 'refresh_data' in form.changed_data: obj.modified_date_refresh = timezone.now() if 'search_appearance' in form.changed_data: obj.modified_date_search = timezone.now() obj.modified_by = request.user obj.save() admin.site.register(Source, SourceAdmin) I want to show the percentage like below format Refreshed Data -
deployment of django-channles in AWS
I have the real time chat application which runs on django channels ,I need to deploy in aws but i cannot find the clear documentation or video for that,https://medium.com/@elspanishgeek/how-to-deploy-django-channels-2-x-on-aws-elastic-beanstalk-8621771d4ff0 when I was following the above link it doesn't help me this was the ouput when i follow this post -
'django' is not recognized as an internal or external command, operable program or batch file.(module error)
I have freshly installed python version 3.9 and it shows up in my CMD (command prompt), but when I try to install django via command pip install django (also tried sudo doesn't work either) command line screenshot but when I try to check my version via django --version command line screenshot I have already tried to configure my environment path variable added every possible path in it. Environment path variable screenshot P.S : I don't want to create virtual environment please don't suggest me that the same thing happen's there too. I have been stuck for many days with this problem if anybody actually know how to solve it please help -
How can I GET external data and combine it with my current view?
I have a view that I want to use to pull Model data + get data from an external API. Using the same URL path to get database data + external API data, as they are both relatively connected in terms of business logic. This is how I tried implementing it: class BucketList(generics.ListAPIView): permission_classes = [IsAuthenticated] serializer_class = BucketListSerializer filter_backends = [OwnerOrUserFilterBackend] queryset = Bucket.objects.all() # I use a field in my model as part of my GET request def get(self, request, *args, **kwargs): bucket_symbols = Bucket.objects.only('stock_list') symbols_unicode = (','.join(map(str, bucket_symbols))) postgrest_urls = f"http://localhost:3000/rpc/bucketreturn?p_stocks=%7B{symbols_unicode}%7D" response = requests.get(postgrest_urls, headers={'Content-Type': 'application/json'}).json() return Response(response, status=status.HTTP_200_OK) The idea of def get(), is to extract every stock_list field in objects, and feed that into my other API on localhost. To clarify, I want every stock_list in object passed into my get requests and returned, for each object. However I keep getting undefined errors in my JSON response. How can I properly implement a two-in-one view solution for my view, I still want to keep my original queryset = Bucket.objects.all() in my view. -
Fresh installation of Django-CMS as instructed at the url latest
Good Day. I am using djangocms for the first time... using https://docs.django-cms.org/en/latest/introduction/01-install.html I did exactly as instructed above and logged in but, as soon as i log in the following error occurs... Request Method: GET Request URL: http://127.0.0.1:8000/en/admin/cms/page/3/change/?language=en Raised by: cms.admin.pageadmin.change_view page object with primary key '3' does not exist. any idea.. Thanks for help... -
ERROR: Failed building wheel for psycopg2 (Ubuntu 20.04 + Python 3.8.5 + venv)
Greetings wisdom from Stackoverflow! I'm having issues building wheel for psycopg2 thru pip install -r requirements.txt. I'm on ubuntu 20.04 + python 3.8.5 + venv. This is my requirements.txt: amqp==2.6.1 anyjson==0.3.3 asgiref==3.2.10 billiard==3.6.3.0 brotlipy==0.7.0 celery==4.4.7 celery-progress==0.0.12 certifi==2020.6.20 cffi==1.14.2 chardet==3.0.4 cryptography==3.1 Django==3.0.3 dj-database-url==0.5.0 django-celery-results==1.2.1 django-cors-headers==3.5.0 django-crispy-forms==1.9.2 django-heroku==0.3.1 django-rest-framework==0.1.0 django-templated-mail==1.1.1 djangorestframework==3.11.1 djoser==2.0.5 fake-useragent==0.1.11 future==0.18.2 gunicorn==20.0.4 httpie==2.2.0 idna==2.10 kombu==4.6.11 lxml==4.5.2 pika==1.1.0 psycopg2==2.8.5 pycparser==2.20 Pygments==2.7.0 pyOpenSSL==19.1.0 PySocks==1.7.1 python-dateutil==2.8.1 python-decouple==3.3 pytz==2020.1 requests==2.24.0 six==1.15.0 SQLAlchemy==1.3.19 sqlparse==0.3.1 urllib3==1.25.10 vine==1.3.0 whitenoise==5.2.0 This is the output when I pip install -r requirements.txt: [...] Collecting urllib3==1.25.10 Using cached urllib3-1.25.10-py2.py3-none-any.whl (127 kB) Collecting vine==1.3.0 Using cached vine-1.3.0-py2.py3-none-any.whl (14 kB) Collecting whitenoise==5.2.0 Using cached whitenoise-5.2.0-py2.py3-none-any.whl (19 kB) Requirement already satisfied: setuptools>=3.0 in ./venv/lib/python3.8/site-packages (from gunicorn==20.0.4->-r requirements.txt (line 24)) (44.0.0) Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/pierre/Workspace/campground_scavanger/venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-1xr9yjk0/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-1xr9yjk0/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-b8g9assp cwd: /tmp/pip-install-1xr9yjk0/psycopg2/ Complete output (6 lines): usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- ERROR: Failed building wheel for psycopg2 Running setup.py clean for … -
Can I deploy Django to heroku that retrieve data from firebase?
my django is retrieve data in realtime from firebase can i deploy it to heroku. I don't know what Add-ons I should select -
How to return username instead of user object in DRF?
I want to set a username for each object. Here is my models.py from django.contrib.auth.models import User from django.conf import settings # Tweet Model class TweetModel(models.Model): text = models.TextField(max_length=300, blank=False) created_at = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True) username = models.CharField(max_length=100, blank=True) And viewset.py from .models import TweetModel from rest_framework import viewsets, permissions # TweetViewset class TweetViewset(viewsets.ModelViewSet): permission_classes = [ permissions.IsAuthenticated ] serializer_class = TweetSerializer def get_queryset(self): ordered = TweetModel.objects.order_by('-created_at') return ordered def perform_create(self, serializer): serializer.save(owner=self.request.user, username=self.request.user.username) But it is not working. Error is django.db.utils.ProgrammingError: column tweets_tweetmodel.username does not exist LINE 1: ...el"."created_at", "tweets_tweetmodel"."owner_id", "tweets_tw... Can you help, please? -
How to accept both csv or xlsx files as input files? (Pandas)
I have a Django application that converts CSV files to other delimiter files. Now I want to improve a feature that can accept and convert both CSV or XLSX files. views.py def submit(request): #form that uploads files csv_form = '' if request.method == 'POST': csv_form = CsvForm(request.POST, request.FILES) if csv_form.is_valid(): csv_file = TextIOWrapper(request.FILES['csv_file'].file, encoding='ascii', errors='replace') data = pd.read_csv(csvfile,delimiter=',') #converts I tried: try: data = pd.read_csv(csv_file, delimiter = ',') except: data = pd.read_excel(csv_file) It shows error: OSError: [Errno 22] Invalid argument: "<_io.TextIOWrapper name='C:\\\\Users\\\\admin\\\\AppData\\\\Local\\\\Temp\\\\wtsrfox8.upload.xlsx' encoding='cp1252'>" templates: <div class="form-row"> <div class="name">Upload CSV file</div> <div class="value"> <div class="input-group js-input-file"> <input class="input-file" type="file" name="csv_file" required="required" id ="file" accept=".csv"> <label class="label--file" for="file">Choose file</label> <span class="input-file__info">No file chosen</span> </div> <div class="label--desc">Upload your file</div> </div> </div> Is there any way to accept and convert both CSV or XLSX files in both views and templates? -
Django get returns ValueError: Field 'id' expected a number but got <string>
Here is my models.py class Car(models.Model): name = models.CharField(max_length = 100) country = models.CharField(max_length = 100) def __str__(self): return str(self.name) class Model(models.Model): name = models.CharField(max_length = 50) car = models.ForeignKey(Car, on_delete = models.CASCADE) def __str__(self): return f"{self.car}-{self.name}" Here is some code I tried in shell that is returning some unexpected results from models import Model print(Model.objects.all()) returns <QuerySet [<Model: Toyota-Previa>, <Model: Toyota-Supra>, `<Model: Toyota-Camery>, <Model: Ford-Torous>, <Model: Ford-Mustang>, <Model: Ford-GT>, <Model: Mercedes-SLR>,` <Model: Mercedes-AMG>, <Model: Mercedes-C-Class>]> but print(Model.objects.get(car = 'Toyota')) returns ValueError: Field 'id' expected a number but got 'Toyota'. I don't understand why this happens, I thought this would return a queryset that gives all of the cars made by Toyota in the database. -
"source code string cannot contain null bytes" in file that has no null bytes
I'm working on a disassembler that prints a series of Python dictionaries calculated from parsing a chunk of hex code from a certain SNES rom file. These dictionaries are written to individual .py files so that they can be imported in the main codebase of a randomizer. I'm using django's manage.py command to run this code, eventassembler: from django.core.management.base import BaseCommand from randomizer.logic.enscript import EventScript from randomizer.logic.osscript import ObjectSequenceScript as OSCommand from randomizer.data.eventscripts.events import scripts class Command(BaseCommand): def handle(self): e = EventScript() print (e.assemble_from_table(scripts)) (not complete, just trying to print to console to test my progress on the assemble_from_table method I'm in the middle of writing) Where scripts comes from an autogenerated file, events.py, that follows this format: from randomizer.data.eventscripts.script_0 import script as script_0 from randomizer.data.eventscripts.script_1 import script as script_1 from randomizer.data.eventscripts.script_2 import script as script_2 ... (all the way up to 4095) scripts[0] = script_0 scripts[1] = script_1 scripts[2] = script_2 ... (all the way up to 4095) Where each of the 4096 import files are also autogenerated files, with each one basically structured like this: from randomizer.data.eventtables import ControllerDirections, RadialDirections, Rooms, ... from randomizer.data.objectsequencetables import SequenceSpeeds, VramPriority, ... from randomizer.data import items script = [ { "identifier": 'EVENT_3_ret_0', … -
django-cacheops return None
Django==2.2.12 django-cacheops==4.2 python 3.7.5 cacheops return None turn Redis off, it works fine. but values exist in both mysql and redis. cacheops option CACHEOPS = { 'user.userinfo': {'ops': 'all', 'timeout': 60 * 60 * 24 * 30}, } CACHEOPS_DEGRADE_ON_FAILURE = True ErrorCode @staticmethod def getUserInfo(userUID): userInfo = userInfo.objects.filter( userUID=userUID, ).first() return userInfo userInfo = getUserInfo(userUID) if not userInfo: raise NameError('userInfo not exist') Restarting uwsgi solves the problem. But I can't keep monitoring the situation, so I need a fundamental solution. It doesn't seem to be a problem with redis as it gets resolved when uwsgi is restarted. It is expected that the connection between django and redis is broken or there is some other problem. Please tell me how to fix cacheops return none differently from the actual value, or how to use mysql value when cacheops return none. -
Django: active Home link
This is my first project with django, I wanted my static site html/css/js to turn it into a dynamic website. However, in navMenu I want to have 'home' link only if the user is not on the index page. Here is my attempt: <style> #hm{ display:none; } .activate{ display:block; } </style> <div id="navMenu" class='py px'> <ul> {% url 'home' as home_view %} <li id = 'hm' {% if request.get_full_path != home_view%} class = 'activate' {% endif%}>Home</li> <li class='brd'>Alumni</li> <li class='brd'>Staff</li> <li class='brd'>Services</li> <li class='brd'>About</li> <li><a id='btnSearch' href="#"><i class="fa fa-search searchUpdate"></i></a></li> </ul> </div> the urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from pages.views import home_view from events.views import events urlpatterns = [ path('admin/', admin.site.urls), path('', home_view, name = 'home'), path('events/', events, name = 'events') ] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Any help is appreciated! -
How to make user-adjustaple pagination in Django?
I have pagination, html: {% extends 'base.html' %} {% load pagination_tags %} {% block title %}NewsLine{% endblock title %} {% load humanize %} {% block content %} {% autopaginate news news_on_page %} {% paginate %} News on page: <input type="submit" value="10" /> <input type="submit" value="20" /> <input type="submit" value="50" /> <div class="container mt-3"> <div class="row my-5"> <div class="col-11"> <p>News overall {{ paginator.count }}</p> <p>Number of pages {{ paginator.num_pages }}</p> <p>Page range {{ paginator.page_range }}</p> {% for peace_of_news in news %} <div class="p-3"> <h2>{{ peace_of_news.title }}</h2> <p><small>{{ peace_of_news.date|naturaltime }}</small></p> <p>{{ peace_of_news.text }}</p> </div> {% endfor %} </div> </div> </div> {% endblock content %} views.py: {% extends 'base.html' %} {% load pagination_tags %} {% block title %}NewsLine{% endblock title %} {% load humanize %} {% block content %} {% autopaginate news news_on_page %} {% paginate %} News on page: <input type="submit" value="10" /> <input type="submit" value="20" /> <input type="submit" value="50" /> <div class="container mt-3"> <div class="row my-5"> <div class="col-11"> <p>News overall {{ paginator.count }}</p> <p>Number of pages {{ paginator.num_pages }}</p> <p>Page range {{ paginator.page_range }}</p> {% for peace_of_news in news %} <div class="p-3"> <h2>{{ peace_of_news.title }}</h2> <p><small>{{ peace_of_news.date|naturaltime }}</small></p> <p>{{ peace_of_news.text }}</p> </div> {% endfor %} </div> </div> </div> {% endblock content …