Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override django.contrib.gis

I modified some code in ../contrib/gis/admin/options.py and also the openlayers.js file in ../contrib/gis/templates/admin.

It works fine like this but I can't let them that way because they will be replaced in case of django update! So I want a copy of those files in my project and leave the original ones in /django/contrib...

Any help will be appreciated.

like image 245
jcs Avatar asked Dec 01 '25 06:12

jcs


1 Answers

Here is an example where we want to change the default map layers used in the admin area. The default OSMWidget use the template django/contrib/gis/templates/gis/openlayers.html, as its attribute template_name is set to gis/openlayers-osm.html. It looks like this:

{% extends "gis/openlayers.html" %}
{% load l10n %}

{% block options %}{{ block.super }}
options['default_lon'] = {{ default_lon|unlocalize }};
options['default_lat'] = {{ default_lat|unlocalize }};
options['default_zoom'] = {{ default_zoom|unlocalize }};
{% endblock %}

{% block base_layer %}
var base_layer = new ol.layer.Tile({source: new ol.source.OSM()});
{% endblock %}

We want here to change the base_layer variable. Instead of directly modifying this template, override it! Create a template file inside your project's templates directory, say gis/custom_layers.html ; and modify base_layer with any tiles you want:

{% extends "gis/openlayers-osm.html" %}
{% load l10n %}

{% block base_layer %}
var base_layer = new ol.layer.Tile({
    source: new ol.source.XYZ({
        attributions: '<a href="https://www.thunderforest.com/">Thunderforest</a>',
        url: "https://tile.thunderforest.com/cycle/{z}/{x}/{y}.png?apikey=<your API key>"
    })
});
{% endblock %}

Then in admin.py you can subclass OSMWidget and specify the custom template. Using GISModelAdmin with Django 4.0, admin.py may look like this:

from django.contrib.gis import admin
from django.contrib.gis.forms.widgets import OSMWidget
from .models import MyModel

class CustomGeoWidget(OSMWidget):
    template_name = 'gis/custom_layers.html'

class CustomGeoModelAdmin(admin.GISModelAdmin):
    gis_widget = CustomGeoWidget
    gis_widget_kwargs = {
        'attrs': {
            'default_zoom': 14,
            'default_lon': 3.4825,
            'default_lat': 50.1906,
        },
    }

@admin.register(MyModel)
class MyModelAdmin(CustomGeoModelAdmin):
    pass
like image 152
nonin Avatar answered Dec 03 '25 19:12

nonin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!