Home > Blockchain >  Three strings of code repeat in three different view-functios
Three strings of code repeat in three different view-functios

Time:05-13

I have three view-functions in views.py in django project that using a same three arguments in them:

paginator = Paginator(post_list, settings.POSTS_LIMIT)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)

How can I put em in a single function (make an utility) to use one string of code in my view-functions, instead of repeat using three? Thats my first question here, thank you :)

CodePudding user response:

As you note, you can create a single function to handle this, taking the info it needs as arguments. You can include this as a helper function in your views.py or separate it out into a utils.py and then import it. Assuming the latter, for tidiness and future-proofing

utils.py

from django.core.paginator import Paginator
from django.conf.settings import POSTS_LIMITS #you may have another place for your settings
from .utils import make_pagination #utils.py file in same directory

def make_pagination(request, thing_to_paginate, num_per_page=POSTS_LIMITS)
    paginator = Paginator(thing_to_paginate, num_per_page)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    return page_obj

views.py

from .utils import make_pagination

def records(request):
   ...
   #we'll use the provided settings-based default for num_per_page
   page_obj = make_pagination(request, post_list)
   return render(request, 'template.html', {'page_obj': page_obj})

If you wanted more than just the page_obj for some reason, you can return more than the one value, eg,

utils.py

...
return page_obj, paginator

views py

...
page_obj, paginator = make_pagination(request, post_list)

I've gotten the page number in the function itself, but you can also do that either in the view itself, or even in the function call in the view eg,

make_pagination(request.GET.get('page') or 1, post_list)

(If you go this path, don't forget to change the function to accommodate the different argument)

  • Related