Login

Name Capitalize Filter

Author:
hotani
Posted:
April 28, 2007
Language:
Python
Version:
.96
Score:
4 (after 4 ratings)

This is to be used as a template filter. See django documentation for adding custom filters.

Example of use:

name = "bart simpson" {{ name|cap }} will convert 'name' to "Bart Simpson"

It works on space-separated names, as well as the following:

  • converts "mcfly" to "McFly";
  • converts "o'neill" to "O'Neill";
  • converts "barker-bradley" to "Barker-Bradley"
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@register.filter
def cap(value):
    namelist = value.split(' ')
    fixed = ''
    for name in namelist:
        name = name.lower()
        # fixes mcdunnough
        if name.startswith('mc'):
            sub = name.split('mc')
            name = "Mc" + sub[1].capitalize()
        # fixes "o'neill"
        elif name.startswith('o\''): 
            sub = name.split('o\'')
            name = "O'" + sub[1].capitalize()

        else: name = name.capitalize()
        
        nlist = name.split('-')
        for n in nlist:
            if len(n) > 1:
                up = n[0].upper()
                old = "-%s" % (n[0],)
                new = "-%s" % (up,)
                name = name.replace(old,new)

        fixed = fixed + " " + name
    return fixed

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

onlinehero (on July 13, 2009):

Thanks, this is much more useful than Pythons own capitalization methods!

#

Please login first before commenting.