Fixing the OSMWidget in Django Admin



This site utilizes Google Analytics, Google AdSense, as well as participates in affiliate partnerships with various companies including Amazon. Please view the privacy policy for more details.

I was setting up an admin for some Django models that had a PointField the other day, and I ran into an issue that took a little digging to figure out.

Here’s how I initially set up the admin, setting the gis_widget_kwargs like the OSMWidget documentation says:

@admin.register(AddressModel)
class AddressModelAdmin(GISModelAdmin):
    gis_widget_kwargs = {
        "default_lon": -85.3148324,
        "default_lat": 40.3374484,
        "default_zoom": 20,
    }

But when I loaded the admin page for a given object of the model, I got the following error:

TypeError: OSMWidget.__init__() got an unexpected keyword argument 'default_lon'

Diggin into the source code for OSMWidget I noticed that the __init__ function takes a keyword argument attrs which itself is a dict (or something that getattr can be used):

class OSMWidget(OpenLayersWidget):
    """
    An OpenLayers/OpenStreetMap-based widget.
    """

    template_name = "gis/openlayers-osm.html"
    default_lon = 5
    default_lat = 47
    default_zoom = 12

    def __init__(self, attrs=None):
        super().__init__()
        for key in ("default_lon", "default_lat", "default_zoom"):
            self.attrs[key] = getattr(self, key)
        if attrs:
            self.attrs.update(attrs)

So I had to modify my gis_widget_kwargs to be a single-value dict with a value that itself is the dict I previously thought I had to use:

@admin.register(AddressModel)
class AddressModelAdmin(GISModelAdmin):
    gis_widget_kwargs = {
        'attrs': {
            "default_lon": -85.3148324,
            "default_lat": 40.3374484,
            "default_zoom": 20,
        }
    }

After this change, my admin page loaded correctly.

Leave a Reply

Note that comments won't appear until approved.