The code below searches for the word in dictionary, and render results on search.html, so I need to paginate results on that page, how can I do that? I read the arcticle here https://docs.djangoproject.com/en/1.9/topics/pagination/, but I have no idea how to embed the pagination code to mine.
def search(request):
if 'results' in request.GET and request.GET['results']:
results = request.GET['results']
word = words.objects.filter(title__icontains = results).order_by('title')
return render_to_response('myapp/search.html',
{'word': word, 'query': results })
else:
return render(request, 'myapp/search.html')
from django.core.paginator import Paginator
def search(request):
if 'results' in request.GET and request.GET['results']:
page = request.GET.get('page', 1)
results = request.GET['results']
word = words.objects.filter(title__icontains = results).order_by('title')
paginator = Paginator(word, 25) # Show 25 contacts per page
word = paginator.page(page)
return render_to_response('myapp/search.html',
{'word': word, 'query': results })
else:
return render(request, 'myapp/search.html')
I prefer using the ListView Class when i need pagination on a queried data, and overiding the query_set function. Something like this...
class FoodMenuView(generic.ListView):
paginate_by = 10 #use your paginated value here
template_name = 'order/_food_menu.html' # your own template
context_object_name = "list_of_food"
def get_queryset(self):
return Food.objects.filter(price=request.GET['price'])
Related
I want to add pagination to my search results in django. This is my search function form views.py for the relevant (Jobs) module:
def search(request):
queryset_list = Job.objects.order_by('-publishing_date')
if 'keywords'in request.GET:
keywords = request.GET['keywords']
if keywords:
queryset_list = queryset_list.filter(description__icontains=keywords)
if 'state' in request.GET:
state = request.GET['state']
if state:
queryset_list = queryset_list.filter(location__iexact=state)
if 'job_type' in request.GET:
job_type = request.GET['job_type']
if job_type:
queryset_list = queryset_list.filter(job_type__iexact=job_type_choices)
if 'industry' in request.GET:
industry = request.GET['industry']
if industry:
queryset_list = queryset_list.filter(industry__icontains=industry_choices)
if 'salary' in request.GET:
salary = request.GET['salary']
if salary:
queryset_list = queryset_list.filter(salary__lte=salary)
context = {
'location_choices':location_choices,
'salary_choices':salary_choices,
'job_type_choices':job_type_choices,
'industry_choices':industry_choices,
'jobs':queryset_list,
'values':request.GET,
}
return render(request, 'jobs/search.html', context)
This is pagination function from the same file:
def index(request):
jobs = Job.objects.order_by('-publishing_date').filter(is_published=True)
paginator = Paginator(jobs, 6)
page = request.GET.get('page')
paged_jobs = paginator.get_page(page)
context = {
'jobs': paged_jobs
}
return render(request, 'jobs/jobs.html', context)
Both of them work (search returns results and pagination works on listing page) however I want to have pagination too for my search results. I am very new to python and django, and assume there is more elegant way of writing my search function, so please do not hesitate to let me know your thoughts.
I want to add all the amount field during a date range query search. I have an Income Model with date and amount fields among others. And any time a user select between two dates, I want the amount fields of the query results added as total.
Here is what I have tried:
def SearchIncomeRange(request):
listIncome = Income.objects.all()
searchForm = IncomeSearchForm(request.POST or None)
if request.method == 'POST':
listIncome = Income.objects.filter(
description__icontains=searchForm['description'].value(),
date__range=[
searchForm['start_date'].value(),
searchForm['end_date'].value()
]
)
else:
searchForm = IncomeSearchForm()
paginator = Paginator(listIncome, 5)
page = request.GET.get('page')
paged_income = paginator.get_page(page)
context = {
'searchForm':searchForm,
}
return render(request, 'cashier/search_income_range.html', context)
I am able to get the correct search result but getting the total I don't know how to use the SUM in the above query and pass the total in pagination. So Someone should please help me out. Thanks
from django.db.models import Sum
total_amount = listIncome.aggregate(total=Sum('amount'))
where listIncome is your queryset
Edit:
You should pass queryset in pagination with filtered queryset if any filter you apply.
I changed your written code but you can write this code in a good way.
def SearchIncomeRange(request):
listIncome = Income.objects.all()
searchForm = IncomeSearchForm(request.POST or None)
if request.method == 'POST':
# you can get filter value by your form data
post_data = request.POST
description = post_data['description']
start_date = post_data['start_date']
end_date = post_data['end_date']
else:
# you can get filter value by your query params
query_params = request.GET
description = query_params.get('description')
start_date = query_params.get('start_date')
end_date = query_params.get('end_date')
# Apply filter before pagination
listIncome = listIncome.filter(
description__icontains=description,
date__range=[start_date, end_date]
)
# calculate total_amount
total_amount = listIncome.aggregate(total=Sum('amount'))
paginator = Paginator(listIncome, 5)
page = request.GET.get('page')
paged_income = paginator.get_page(page)
# you can access total_amount in template by passing in context data
context = {
'searchForm':searchForm,
'total_amount': total_amount
}
return render(request, 'cashier/search_income_range.html', context)
Is there any way to make django paginator to work with filtering and sorting without the involvement of
django-filter. This is my code now:
def check_filters(post, content):
if some_filter := post.gelist("some_filter"):
content = content.filter(some_filter=some_filert)
if ....basically the same ....
if ...basically the same ....
return content
def some_fun(response):
n = SomeQueryset.objects.all();
if post:= response.POST:
n = check_filters(post, n, )
paginator = Paginator(n, per_page=12)
page_number = response.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(response, 'store/store.html', {"page_obj": page_obj, "colors": get_colors()})
Hello everybody I keep having this problem with my search form in my website. The thing is that, based on the user input, i check if in the database there're some results. But if the input is both in band column and album colum I'd like the user to be redirected to a 'disambiguation' html page. This is my views.py but it doesn't work. Hope someone could help me, thanks!
Views.py
class searchesView(TemplateView):
template_name = "search/searches.html"
def post(self, request, *args, **kwargs):
print('FORM POSTED WITH {}'.format(request.POST['srh']))
srch = request.POST.get('srh')
if srch:
sr = Info.objects.filter(Q(band__icontains=srch))
sd = Info.objects.filter(Q(disco__icontains=srch))
if sr is sd:
return render(self.request, 'search/disambigua.html')
else:
paginator = Paginator(sr, 10)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return render(self.request, 'search/searches.html', {'sr':sr,
'sd': sd,
'page_obj': page_obj
})
else:
return render(self.request, 'search/searches.html')
I found a resource where it has code like this:
from django.contrib.auth.models import User
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def index(request):
user_list = User.objects.all()
page = request.GET.get('page', 1)
paginator = Paginator(user_list, 10)
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
return render(request, 'core/user_list.html', { 'users': users })
I have a code like this:
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all().order_by("-rating")
#paginator = Paginator(categories, 10)
products = Product.objects.all().order_by("-number")
users = User.objects.exclude(id=request.user.id)
query = request.GET.get('q')
if query=='':
return HttpResponseRedirect('/')
if query:
categories = Category.objects.filter(Q(slug__icontains=query)| Q(url__icontains=query)).order_by("-rating")
products = Product.objects.filter(Q(slug__icontains=query) | Q(name__icontains=query) | Q(description__icontains=query)).order_by("number")
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = Product.objects.filter(category=category)
categories_counter = products.annotate(Count('id'))
categories_count = len(categories_counter)
#contacts = paginator.get_page(query)
context = {
'category': category,
'categories': categories,
'products': products,
'categories_count':categories_count,
'query':query,
'users':users,
#'contacts':contacts,
}
return render(request, 'shop/product/list.html', context)
I have retrieved objects from two models, Category, and Product. How do I implement the pagination code in this view? It's not a normal pagination but pagination in search results.
user_list = User.objects.all() # this is the full queryset, contains all objects
page = request.GET.get('page', 1) # this is the page number of page whose data you want to retrieve, you need to pass page value as query params
paginator = Paginator(user_list, 10) # this will paginate the full queryset in pages of 10 objects
try:
users = paginator.page(page) # this will return data of that particular page
except PageNotAnInteger:
users = paginator.page(1) # if the passed page is not Integer then first page is returned, you can customize this
except EmptyPage:
users = paginator.page(paginator.num_pages) # if that page contains no element, then last page is returned, you can customize this also
You can apply same logic to retrieve categories in category_page and other data.