Source

placeuvote / gaepuv / puv / poll / widgets.py

from django import forms
from puv.settings import DEFAULT_LAT, DEFAULT_LNG

class LocationWidget(forms.TextInput):
    def __init__(self, *args, **kw):
        super(LocationWidget, self).__init__(*args, **kw)
        self.inner_widget = forms.widgets.HiddenInput()

    def render(self, name, value, *args, **kwargs):
        if value is None:
            lat, lng = DEFAULT_LAT, DEFAULT_LNG
        else:
            if isinstance(value, unicode):
                a, b = value.split(',')
            elif isinstance(value, list) and len(value)==2:
                a, b = value
            else:
                a, b = DEFAULT_LAT, DEFAULT_LNG
            lat, lng = float(a), float(b)

        return self.inner_widget.render(name, "%f,%f" % (lat, lng), 
                                           dict(id='id_%s' % name))
        
class LocationFormField(forms.CharField):
    widget = LocationWidget

    def clean(self, value):
        if isinstance(value, unicode) or isinstance(value, str):
            a, b = value.split(',')
        else:
            a, b = value

        lat, lng = float(a), float(b)
        return "%f,%f" % (lat, lng)