Django – Insensitive Case

When using Django in Python there’s these awesome things called QuerySets that are a full blown ORM to make it so I don’t have to think in SQL to get things in and out of a database! One of the things I didn’t find documented very well was case sensitivity vs insensitivity.

If you’re using the MySQL backend the case-sensitive is implied, i.e. using BINARY LIKE instead of just LIKE

series = Series.objects.filter(name__contains=srch_str)

To make sure that you’re searching for some that’s case insensitive you can do the following:

series = Series.objects.filter(name__icontains=srch_str)

If you want it to work case insensitive no matter the backend, collation, or collection type just use icontain, istartswith, iendswith, iregex, iexact.

Django: Basic Template Tags

One of things I had the hardest time finding was a good example of Template Tags in Django; so here is my basic template tags file I add to every new project (GPLv2). A lot of people have their own, and I’m sure in the future I’ll add on to my basics; but for now these get me by. One of the things I’ve been wanting to do is write a good small primer for beginning Django, consider this my first foray in to making that a reality.

from django import template
from django.template import Variable, VariableDoesNotExist
register = template.Library()
 
@register.filter
def gVal(object, attr):
    """Check the array, dict, etc for a value"""
    quasai = { 'object' : object }
    #print "gVal :: " + str(attr) +" - "+ str(quasai)
    try:
        value = Variable('object.%s' % attr).resolve(quasai)
    except VariableDoesNotExist:
        value = None
    return value
 
@register.filter
def xVal(a,b):
    """Since Python resolves left to right in template tags: pass value and then the dick to check; returns value or 0"""
    #print "xVal",a,b
    if b.has_key(a):
        value = b[a]
    else:
        value = "0"
    return value
 
@register.filter
def hexVert(value):
    """Removes all values of # from the given string and replaces with %23"""
    if value != None:
        value = value.replace("#", '%23')
        value = value.replace("!", '%21')
        value = value.replace("&", '%26')
    return value