Django

Django/Python – changing pages

Posted on Updated on

Just learned a new Django trick from my sempai at work. For confidentiality I’ve rewritten new code to show this example. Lets say users want to switch back and forth to 2 different pages or more.. like at a movie theatre. Users order either salt or caramel popcorn. In out views.py, code would look something like this:

def popcorn_test(request, page=1):
    ...
    if request.is_salt_popcorn_lover:
        return render(popcorn_1.html, context)
    elif request.is_caramel_popcorn_lover:
        return _render(popcorn_2.html, context)

It’s not so bad, but if we want to add more crazy flavors we need more pages and eventually our code would grow bigger and might turn into something like this:

def popcorn_test(request, page=1):
    ...
    if request.is_salt_popcorn_lover:
        return render(popcorn_1.html, context)
    elif request.is_caramel_popcorn_lover:
        return _render(popcorn_2.html, context)
    elif request.is_chocolate_popcorn_lover:
        return _render(popcorn_3.html, context)
    elif request.is_toffee_crisp_popcorn_lover:
        return _render(popcorn_4.html, context)

This makes engineers hostile and angry. So to avoid repeating ourselves we can do this instead:

def popcorn_test(request, page=1):
    ...
    if request.is_salt_popcorn_lover:
        return _render(‘popcorn_{}.html'.format(page) context)    

then in our urls.py page, where parameters will be passed in, we change what we had before from this:

url(r'^ popcorn_test/$', 'popcorn_test', name=‘popcorn_page’),

to this:

url(r'^ popcorn_test/$', 'popcorn_test', name=‘popcorn_page’),
url(r'^ popcorn_test/(?P<page>\d+)/$', 'popcorn_test', name=‘popcorn_page’), 

Now we can pass parameters into our views and our new code can determine which page to jump to depending on the choices the user makes.

Advertisements