Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does request.GET.get('page', '1') means here?

Tags:

python

django

views.py

from django.core.paginator import Paginator

def index(request):

    posts_list = Post.objects.all().order_by('-id')

    paginator = Paginator(posts_list, 5)

    try:
        page = int(request.GET.get('page', '1'))
    except:
        page = 1

    try:
        posts = paginator.page(page)
    except(EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)

    return render_to_response('home/index.html',
        { 'posts' : posts },
        context_instance=RequestContext(request))
like image 896
Mohd. Shoaib Avatar asked Mar 06 '23 17:03

Mohd. Shoaib


2 Answers

Well this is a mix between Python's get method features and GET of Django,

Basically, since GET is a A dictionary-like object containing all given HTTP GET parameters, what you are trying to achieve here is find the value for the given key 'page'. If it doesn't exist it will fallback to the default value 1 which is what get intends to do.

like image 137
scharette Avatar answered Mar 15 '23 23:03

scharette


In simple way... you are using get() method that will check if the element that you want exists if not return None (null), so you are searching for GET (HTTP) Paramter if "page" exists, if not exists it return 1

mypage.com/?page=2

request.GET['page'] # That will force get page param, and you will if not found
request.GET.get('page', '1') # Tha will check if param exists, and return 1 if not found

Using GET.get() is a bad pratice, since your erros will silent fail, better your GET['page'] and handle the errors using try/except

try:
    page = request.GET['page']
    ...
except Exception as e:
    print(e) # handle your errors
    page = 1 # The Default value when erros comes
...
like image 23
Diego Vinícius Avatar answered Mar 15 '23 22:03

Diego Vinícius