Skip to content

Instantly share code, notes, and snippets.

@victorono
Created March 3, 2014 03:44
Show Gist options
  • Save victorono/9318056 to your computer and use it in GitHub Desktop.
Save victorono/9318056 to your computer and use it in GitHub Desktop.
Formats the RUT form to the common string representation.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import template
register = template.Library()
from django.utils.encoding import smart_unicode
def _verifier(rut):
rut = smart_unicode(rut).replace(' ', '').replace('.', '').replace('-', '')
return rut[:-1], rut[-1].upper()
def _format(code, verifier):
while len(code) > 3 and '.' not in code[:3]:
pos = code.find('.')
if pos == -1:
new_dot = -3
else:
new_dot = pos - 3
code = code[:new_dot] + '.' + code[new_dot:]
return u'%s-%s' % (code, verifier)
@register.filter(name='rut_format')
def rut_format(value):
rut, verificador = _verifier(value)
return _format(rut, verificador)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment