How to get limited results per page in django using pagination? - python

I am following a udemy course where I am making a real estate website using Django. I have come so far and have been fighting with the errors but I am stuck with the pagination error that I am facing right now.
I see everything is working fine in the video but when I follow it exactly it does not work. The issue is that when I set a limit on items per page, it does not seem to be working as I see all the results on the same page.
Here is my views.py
from django.shortcuts import render
from django.core.paginator import Paginator
from .models import Listing
def index(request):
listings = Listing.objects.all().order_by('-id')
paginator = Paginator(listings, 3)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
context = {
'listings': listings
}
return render(request, 'listings/listings.html', context)
It's my Urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='listings'),
path('<int:listings_id>', views.listing, name='listing'),
path('search', views.search, name='search')
As you can see, I have set maximum 3 listings per page but I am getting all of them on a single page which is not what I want. It would be great if anyone could help. Thanks for your time and efforts.

You are returning whole listings instead of Paginator page inside of context
context = {
'listings': page_obj
}
More regarding pagination you can check also in documentation

Related

How to solve NoReverseMatch at / (Error during template rendering) in django 3.2?

Here is the screenshots of error i am getting.
and
App Name is greeting_app
Now greeting_app/urls.py has the following code
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('about/<int:id>/', views.about, name="about"),
]
greeting_app/views.py has the following code
from django.shortcuts import render, HttpResponse
from .models import basicinformation
# Create your views here.
def home(request):
information = basicinformation.objects.all()
return render(request, 'index.html', {"info":information})
def about(request, id):
data = basicinformation.objects.get(id=id)
return render(request, 'about.html', {"data":data})
templates/index.html has the following code. I have included only the url part in index.html file.
Description
data.id does not contain an ID. From the error message it contains ('',) (or possibly (",) - it's hard to tell from an image. Please don't use images!).
You do for all in info, then reference all in every other template line, then suddenly try and use data.id.
Since you haven't posted your whole template, it's hard to tell, but I suspect you want to use all.id in your URL here, and not data.id.
Add this to urls.py above urlpatterns
app_name=“ greeting_app”
Fix template url to this:
<a href="{% url "greeting_app:about" data.id %}">Description

Django unexpected characters in URL

I am making a blog and trying to make pagination operations on post listing page. When I run my app, my URL contains unexpected characters. For example ;
http://127.0.0.1:8000/blog/%5E$
I couldn't understand why %5E$ is there.
Here my urls.py (this is in blogapp):
from django.urls import path,include
from django.contrib import admin
from . import views
urlpatterns = [
path(r'^$',views.getPosts,name="bloghome"),
path(r'^(?P<selected_page>\d+)/?$',views.getPosts,name="bloghome"),
path('<slug>',views.postDetailPage,name="post_detail")
]
getPost function in views.py
def getPosts(request,selected_page=1):
# latest_post = Posts.objects.get(id=1)
posts = Posts.objects.all().order_by('-pub_date')
pages = Paginator(posts,5) #Show 5 post per page
try:
returned_page = pages.page(selected_page)
except EmptyPage:
returned_page = pages.page(pages.num_pages)
#content = pages.page(selected_page)
return render(request,'blog.html',{'page':returned_page,
'posts':returned_page.object_list
})
And finally, this bloglist page is being entered from homepage with <a> tag. Here it's one line of code:
Blog
Based upon https://docs.djangoproject.com/en/dev/ref/urls/#django.urls.path, you need to use re_path() instead of path(), as it is interpreting ^$ literally, per zvadym's prior comment. This is new in Django 2.0, so it depends on your version.

Can't display new html page with href from homepage

The only examples I find. are related to issues with login page and iteration to other pages but not in the way I have the problem, so here is the issue I have to deal with -
I want to display a form for creating an account with multiple steps, using modals, when a user access the button "subscribe"
on my homepage.html I have this:
<a onClick="window.location.href='account'" target="_blank">
<input type="submit" value="account">
</a> `
...which is supposed to go to a new account.html page, in the same folder as my homepage.html
in my app's urls.py, where the apps' name is homepage I have:
from django.conf.urls import patterns, url
from homepage import views
urlpatterns = patterns('',
url(r'^$', views.homepage, name='homepage'),
url(r'^account$', views.account, name='account'),
)
and in my views I have:
from django.shortcuts import render
from homepage.models import Email
def tmp(request):
latest_email_list = Email.objects.order_by('-pub_date')[:0]
context = {'latest_email_list': latest_email_list}
return render(request, 'home_page/homepage.html', context)
def homepage(request):
return render(request, 'home_page/homepage.html')
def account(request):
return render(request, 'home_page/account.html')`
when I click on the button I get
Not Found
The requested URL /account was not found on this server.
I am a complete beginner in django and python so I really haven't yet wrapped my mind on how to work properly with the urls, views, and models together but I assume I have something wrongly defined in my views
would be grate if someone could help me setting this up,
Thanks
I only want to thank all those who took time to check my question and tried to give a solution.
I think it was my mistake that I did not post the code I have in my main urls.py file, so here it is:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^$', include('home_page.urls', namespace="homepage")),
url(r'^admin/', include(admin.site.urls)),
)
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
Apparently, the problem was in that first prefix of the first url in the list:
I changed
url(r'^$'
for
url(r''
and now it calls whatever links I provide in my html pages.
Thanks all again

Django - Reusing views in different templates

It's probably a stupid question but its really late here and my brain died after my 6th coffee.
I'm building (or trying to) a simple blogging application that would display an article index on the homepage - aka. recent articles - and on the main blog page. To do so I've managed to scribble out a following view:
def index(request):
'''Article index'''
archive_dates = Article.objects.datetimes('date_publish','month', order='DESC')
categories = Category.objects.all()
page = request.GET.get('page')
article_queryset = Article.objects.all()
paginator = Paginator(article_queryset, 5)
try:
articles = paginator.page(page)
except PageNotAnInteger:
#If page requested is not an integer, return first page.
articles = paginator.page(1)
except EmptyPage:
#If page requested is out of range, deliver last page of results.
articles = paginator.page(paginator.num_pages)
return render(
request,
'blog/article/index.html',
{
'articles': articles,
'archive_dates': archive_dates,
'categories': categories
}
)
However to display the index within two different URLs I've copied the code changing only few variables, ie. name and template to render.
What could I do to render this view within both URLs yet not duplicate it in my views.py?
Am I right in thinking that I'd have to have 3 views, a main one and two sub ones that would import the code from the main one?
Or should I be using a custom template tag instead?
EDIT
As requested, adding urls.py
from django.conf.urls import *
from django.contrib import admin
from settings import MEDIA_ROOT
from django.views.generic import TemplateView
from blog.views import *
admin.autodiscover()
urlpatterns = patterns('',
#Blog URLs
url('^$', home_index, name='blog-preview'),
url('^blog/archive/(?P<year>[\d]+)/(?P<month>[\d]+)/$', date_archive, name='blog-date-archive'),
url('^blog/archive/(?P<slug>[-\w]+)/$', category_archive, name='blog-category-archive'),
url('^blog/categories/', category_list, name='blog-category-list' ),
url('^blog/(?P<slug>[-\w]+)/$', single, name='blog-article-single'),
url('^blog/$', index, name='blog-article-index'),
url(r'^contact/', include("contact_form.urls", namespace="contact_form")),
url(r'^admin/', include(admin.site.urls)),
)
It's very simple: map two urls in your conf to the view like this:
urlpatterns = patterns('',
url(r'first_expression', index, name='first'),
url(r'second_expression', index, name='second'),
)
Also, a little advise on your code: try to avoid wildcard imports. They are dangerous...
Insead use:
from package import MyClass, my_function, my_etc

Django; Will not make the correct request

I am just beginning to learn how to use django. I have set up my views.py, urls.py, settings.py, and relative HTML pages. I am able to get the index page to come up but not the about page (only outputs some text) or my category page. I am assuming that the problem is affecting them both.
Views.py:
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from rango.models import Category
from rango.models import Page
def index(request):
# Obtain the context from the HTTP request.
context = RequestContext(request)
category_list = Category.objects.order_by('id')[:5]
context_dict = {'categories': category_list}
# Render the response and send it back!
return render_to_response('index.html', context_dict, context)
def about(request):
# Request the context of the request.
# The context contains information such as the client's machine details, for example.
context = RequestContext(request)
context_dict = {'boldmessage': "I am from the context"}
return render_to_response('/about.html', context_dict, context)
def category(request, category_name_url):
# Request our context from the request passed to us.
context = RequestContext(request)
category_name = category_name_url.replace('_', ' ')
context_dict = {'category_name': category_name}
try:
category = Category.objects.get(name=category_name)
pages = Page.objects.filter(category=category)
# Adds our results list to the template context under name pages.
context_dict['pages'] = pages
context_dict['category'] = category
except Category.DoesNotExist:
# Go render the response and return it to the client.
return render_to_response('rango/category.html', context_dict, context)
urls.py:
from django.conf.urls import patterns, url
from rango import views
# At the top of your urls.py file, add the following line:
from django.conf import settings
urlpatterns = patterns('',
url(r'$', views.index,name='index'),
url(r'about/$', views.about,name='about'))
#url(r'category/$', views.category,name='category'))
# UNDERNEATH your urlpatterns definition, add the following two lines:
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )
My template directory has been hard coded so it really shouldn't be a problem
TEMPLATE_DIRS = ('C:/Users/aharon/Desktop/TEMP',)
Keep in mind that I am very noob so please be easy on me and I would like as much explanation as possible. Thank You!
You have not anchored your regexes with ^ at the start. Without that, your first pattern will match every single URL. You should makes sure they all start with ^.

Categories