Categories
Python Answers

How to reference list item by index within Python Django template?

To reference list item by index within Python Django template, we can create our own filter.

For instance, we write

from django import template
register = template.Library()

@register.filter
def index(indexable, i):
    return indexable[i]

to create the index filter by applying @register.filter decorator to the index function in templatetags/index.py.

Then in our templaye, we use it by writing

{% load index %}
{{ my_list|index:x }}

{{ my_list|index:forloop.counter0 }}

to use the index decorator after loading it by using the index as its argument

Categories
Python Answers

How to set cookies with Python Django?

To set cookies with Python Django, we can use set_cookie and request.COOKIES.

For instance, we write

def view(request):
  response = HttpResponse('blah')
  response.set_cookie('cookie_name', 'cookie_value')

to call response.set_cookie with the cookie name and value.

And then we get the cookie by writing

def view(request):
  value = request.COOKIES.get('cookie_name')
  if value is None:
    # Cookie is not set

to call request.COOKIES.get with the cookie name to get the cookie.

Categories
Python Answers

How to add URL parameters to Python Django template url tag?

To add URL parameters to Python Django template url tag, we can add them after the URL name.

For instance, we write

url(r'^panel/person/(?P<person_id>[0-9]+)$', 'apps.panel.views.person_form', name='panel_person_form'),

to add a URL with url.

And then we add the parameter by writing

{% url 'panel_person_form' person_id=item.id %}

to add the person_id parameter after the URL name.

We separate multiple parameters with spaces.

Categories
Python Answers

How to redirect a post and pass on the post data with Python Django?

To redirect a post and pass on the post data with Python Django, we can redirect with HttpResponseRedirect.

For instance, we write

def some_view(request):
    #do some stuff
    request.session['_old_post'] = request.POST
    return HttpResponseRedirect('next_view')

def next_view(request):
    old_post = request.session.get('_old_post')
    #do some stuff using old_post

to create 2 views some_view and next_view.

In some_view, we return the HttpResponseRedirect response to redirect to next_view.

And in next_view we get the _old_post value from request.session that we saved in some_view.

And then we do stuff with the value.

Categories
Python Answers

How to fix Python Django CSRF Cookie Not Set?

To fix Python Django CSRF Cookie Not Set, we can add the csrf_exempt decorator to our view.

For instance, we write

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt 
def your_view(request):
    if request.method == "POST":
        # do something
    return HttpResponse("Your response")

to apply the @csrf_exempt to the your_view view to make Django ignore the CSRF token check on the view.