Allowing front-end geographic input

As great as the Django Admin is, it’s not for most of your users. So what do we do to allow user-submitted geometries?

Cue django-floppyforms which contains handy widgets we can use with our own forms and modelforms to allow geographic input.

Consider this model:

class MyArea(models.Model):
    name = models.CharField(max_length=64, unique=True)
    point = models.PointField(srid=4326)
    polygon = models.MultiPolygonField(srid=4326)

Throw this in

import floppyforms as forms

from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext

from formstuff.myarea.models import MyArea

class OSMPointWidget(forms.gis.PointWidget, forms.gis.BaseOsmWidget):
    map_srid = 900913

class OSMMultiPolygonWidget(forms.gis.MultiPolygonWidget, forms.gis.BaseOsmWidget):
    map_srid = 900913

class AreaForm(forms.ModelForm):
    point = forms.gis.PointField(widget=OSMPointWidget)
    polygon = forms.gis.MultiPolygonField(widget=OSMMultiPolygonWidget)

    class Meta:
        model = MyArea

def editing(request):
    form = AreaForm(request.POST or None)
    if form.is_valid():
        return HttpResponseRedirect('/')

    return render_to_response('area.html', {
        'form': form,
    }, context_instance=RequestContext(request))

and users can drop points and polygons on your model, which will be saved into the database. Do you want the Google basemap instead? Extend BaseGMapWidget instead of¬†BaseOsmWidget, remove the srid attrib, and you’re set. It’s amazing how easy those widgets make it – you don’t even have to know you’re dealing with a geometry in your save method.

Leave a Reply

Your email address will not be published. Required fields are marked *