Mohd. Shoaib
Mohd. Shoaib

Reputation: 113

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

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))

Upvotes: 5

Views: 7499

Answers (2)

Diego Vinícius
Diego Vinícius

Reputation: 2243

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
...

Upvotes: 3

scharette
scharette

Reputation: 9997

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.

Upvotes: 6

Related Questions