Displaying objects on maps in the Django views and administration site.

Overview

DjangoAdminGeomap library

GitHub Workflow Status GitHub Workflow Status Codacy Badge Codacy Badge

The free, open-source DjangoAdminGeomap library is designed to display objects on the map in the Django views and admin site.

objects on the map in the Django admin site

There is a full-fledged multifunctional GIS framework GeoDjango. When is used in the Django admin site, you can display objects on the map. However, GeoDjango has a large list of dependencies on various libraries and the specifics of installing these libraries on various platforms.

If you only need to display objects on the map in the Django admin site, then you can use the DjangoAdminGeomap library. It has no additional requirements for the names and data types of fields in the database tables, and there are no installation dependencies.

DjangoAdminGeomap uses the OpenLayers JavaScript framework to display map data. The source of the cartographic data is the data of the OpenStreetMap project.

Installation

pip install django-admin-geomap

After installation, you need to plug the library into your Django project by making changes to the settings.py file.

Changes to settings.py

To connect DjangoAdminGeomap to your project, you need to add to the file settings.py in the key TEMPLATES the path to the directory templates of the library.

TEMPLATES = [
  {
    'DIRS': ['path/to/installed/django_admin_geomap/templates'],
  },
]

An example of such a connection can be found in the file example/settings.py.

It is not necessary to include the library in the INSTALLED_APPS list in settings.py.

Initial data

Let's say we have a table in the database, the records of which contain data about coordinates.

# models.py
from django.db import models

class Location(models.Model):
    name = models.CharField(max_length=100)
    lon = models.FloatField()  # longitude
    lat = models.FloatField()  # latitude

On the main page of the site and when working with this table in the admin panel, we want to see a map with objects from this table located on it.

Main page with a list of objects on the map

To enable the display of Location objects on the map, you need to make changes to the model class in the models.py file.

Add the django_admin_geomap.GeoItem "mixin" class to the inheritance list of the Location class and define two properties: geomap_longitude and geomap_latitude. These properties should return the longitude and latitude of the object as a string.

# models.py
from django.db import models
from django_admin_geomap import GeoItem

class Location(models.Model, GeoItem):

    @property
    def geomap_longitude(self):
        return '' if self.lon is None else str(self.lon)

    @property
    def geomap_latitude(self):
        return '' if self.lon is None else str(self.lat)

After making these changes to the definition of the model, you can display a map with objects from the Location table in an arbitrary view. To do this, you need to include the file geomap/common.html in the page template. For example, the site root page template home.html might look like this:

<!DOCTYPE html>
<html lang="en">

<head>
<title>DjangoAdminGeomap example</title>
</head>

<body>
Hello, OpenStreetMap!
<div>{% include "geomap/common.html" %}</div>
</body>

</html>

In the view function, you need to pass to this template the context formed by calling the geomap_context function. As a required argument to the function, you need to pass an iterable sequence of objects to display on the map. For example a list or Django QuerySet.

# views.py
from django.shortcuts import render
from django_admin_geomap import geomap_context

from .models import Location


def home(request):
    return render(request, 'home.html', geomap_context(Location.objects.all()))

On the root page of the site, a map with markers in the locations of these objects will be displayed.

The geomap_context function accepts additional named arguments to customize the properties of the map.

  • map_longitude: map center longitude, default is "0.0"
  • map_latitude: map center latitude, default is "0.0"
  • map_zoom: map zoom level, default is "1"
  • map_height: vertical map size, default is "500px"

List of objects on the map in the admin panel

To display a map with objects in the site admin panel in the admin settings file admin.py, when registering a model, you need to use the django_admin_geomap.ModelAdmin class.

# admin.py
from django.contrib import admin
from django_admin_geomap import ModelAdmin
from .models import Location

admin.site.register(Location, ModelAdmin)

After making these changes, in the admin panel on the page with a list of Location objects, a map with markers at the locations of these objects will be displayed under the table.

Displaying the object on the map in the edit form in the admin panel

To display an object on the map in the edit/view form, you must additionally specify the field IDs in the Django form, which contain the longitude and latitude values of the object.

For our Location class, the Django admin automatically assigns the IDs id_lon and id_lat to these form fields. The following changes need to be made to the admin.py file.

# admin.py
from django.contrib import admin
from django_admin_geomap import ModelAdmin
from .models import Location

class Admin(ModelAdmin):
    geomap_field_longitude = "id_lon"
    geomap_field_latitude = "id_lat"

admin.site.register(Location, Admin)

After making these changes, in the admin panel on the page for viewing/editing the Location object, a map with a marker at the location of the object will be displayed.

When editing, you can change the position of an object by dragging its icon across the map with the mouse (you need to move the mouse cursor over the bottom of the icon until a blue dot appears on it).

When adding a new object, its position can be set by clicking on the map. Further, the marker of the new object can be dragged, similar to editing.

Additional customization

The library allows you to customize the view of the map and objects by setting special properties for the model class and the django_admin_geomap.ModelAdmin class.

Object icon on the map

The geomap_icon property of the model class sets the path to the marker icon. You can use different icons depending on the state of a particular object.

The default is https://maps.google.com/mapfiles/ms/micons/red.png.

# models.py
from django.db import models
from django_admin_geomap import GeoItem

class Location(models.Model, GeoItem):

    @property
    def geomap_icon(self):
        return self.default_icon

Text in a pop-up panel when you click on a marker on the map

When you click on a marker on the map, a pop-up panel is displayed. The HTML code used in this panel can be set by defining three properties on the model class.

  • geomap_popup_common displayed in regular views
  • geomap_popup_view displayed in the admin panel for a user without permission to edit the object
  • geomap_popup_edit displayed in the admin panel for a user who has permission to edit

By default, all these properties return the string representation of the object.

# models.py
from django.db import models
from django_admin_geomap import GeoItem

class Location(models.Model, GeoItem):

    @property
    def geomap_popup_view(self):
        return "<strong>{}</strong>".format(str(self))

    @property
    def geomap_popup_edit(self):
        return self.geomap_popup_view

    @property
    def geomap_popup_common(self):
        return self.geomap_popup_view

New object icon

The geomap_new_feature_icon property of the django_admin_geomap.ModelAdmin class sets the path to the marker icon when adding a new object in the admin panel.

# admin.py
from django_admin_geomap import ModelAdmin

class Admin(ModelAdmin):
    geomap_new_feature_icon = "/myicon.png"

Default map zoom level and center of the map when displaying a list of objects in the admin panel

You can change the zoom level and position of the center of the map by setting the properties geomap_default_longitude, geomap_default_latitude and geomap_default_zoom in the class django_admin_geomap.ModelAdmin.

By default, the center of the map is located at the point with coordinates "0.0", "0.0" and the scale is "1".

# admin.py
from django_admin_geomap import ModelAdmin

class Admin(ModelAdmin):
    geomap_default_longitude = "95.1849"
    geomap_default_latitude = "64.2637"
    geomap_default_zoom = "3"

Default map zoom level when editing/viewing an object in the admin panel

In object edit form the center of the map coincides with the location of the object. The zoom level of the map can be set by using the geomap_item_zoom property of the django_admin_geomap.ModelAdmin class.

The default is "13".

# admin.py
from django_admin_geomap import ModelAdmin

class Admin(ModelAdmin):
    geomap_item_zoom = "10"

Vertical map size in the admin panel

When displayed, the map occupies the maximum possible horizontal size. The vertical size can be set via the geomap_height property of the django_admin_geomap.ModelAdmin class. The value must be a string valid in the CSS style definition.

The default is "500px".

# admin.py
from django_admin_geomap import ModelAdmin

class Admin(ModelAdmin):
    geomap_height = "300px"
You might also like...
Store model history and view/revert changes from admin site.

django-simple-history django-simple-history stores Django model state on every create/update/delete. This app supports the following combinations of D

Store model history and view/revert changes from admin site.

django-simple-history django-simple-history stores Django model state on every create/update/delete. This app supports the following combinations of D

Generate generic activity streams from the actions on your site. Users can follow any actors' activities for personalized streams.

Django Activity Stream What is Django Activity Stream? Django Activity Stream is a way of creating activities generated by the actions on your site. I

Helps working with singletons - things like global settings that you want to edit from the admin site.
Helps working with singletons - things like global settings that you want to edit from the admin site.

Django Solo +---------------------------+ | | | | | \ | Django Solo helps

Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App 💛 We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, celery and redis.

Django Channels Websocket Chatbot A Django chatbot that is capable of doing math and searching Chinese poet online. Developed with django, channels, c

Blog focused on skills enhancement and knowledge sharing. Tech Stack's: Vue.js, Django and Django-Ninja

Blog focused on skills enhancement and knowledge sharing. Tech Stack's: Vue.js, Django and Django-Ninja

Meta package to combine turbo-django and stimulus-django

Hotwire + Django This repository aims to help you integrate Hotwire with Django 🚀 Inspiration might be taken from @hotwired/hotwire-rails. We are sti

django-quill-editor makes Quill.js easy to use on Django Forms and admin sites
django-quill-editor makes Quill.js easy to use on Django Forms and admin sites

django-quill-editor django-quill-editor makes Quill.js easy to use on Django Forms and admin sites No configuration required for static files! The ent

Comments
  • Ссылки на скрипты на работают

    Ссылки на скрипты на работают

    Подключил по инструкции, джанго никаких ошибок не выдает. В консоли браузера есть ошибки GEThttps://cdn.jsdelivr.net/gh/openlayers/[email protected]/en/v6.6.1/build/ol.js [HTTP/2 403 Forbidden 3289ms] GEThttps://cdn.jsdelivr.net/gh/openlayers/openlayers.git[email protected]/en/v6.6.1/css/ol.css [HTTP/2 403 Forbidden 4311ms]

    Скрипты из базового шаблона походу не доступны

    opened by hackoffme 9
  • Auto-zoom of Admin Map?

    Auto-zoom of Admin Map?

    First of all, thanks for such a great tool. I've got it hooked in to WhatThreeWords on my admin panel and it's working brilliantly!

    I've seen the docs about setting the admin zoom and I'm wondering if it's possible to have it "auto-zoom" based on the coordinates of the objects that are returned to it?

    For example, if I've only got objects that have locations in central London, is it possible to have it auto-zoom to a level where all the objects are displayed on the map at a sensible level?

    opened by proffalken 3
  • Template Directory

    Template Directory

    First, thanks for an excellent package! It was (fairly) easy to install, and bam! Instance maps! I would like to point out that adding django_admin_geomap to INSTALLED_APPS removes the need edit ``TEMPLATES```. I find this easier/robust because I was not able to add a template directory that supported both dev and deployment environments.

    Thanks again!

    opened by NadavK 2
  • Pop-up on Marker Click

    Pop-up on Marker Click

    The pop-up window is not visible when clicking on a marker. This is the HTML that changes when clicking an element:

    <div class="popover fade bs-popover-top show" role="tooltip" id="popover906644" x-placement="top" x-out-of-boundaries="" style="position: absolute; transform: translate3d(2128px, 4041px, 0px); top: 0px; left: 0px; will-change: transform;">
    <div class="arrow" style="left: 0px;">
    </div><h3 class="popover-header">
    </h3><div class="popover-body">ABCDEF</div></div>
    

    The left position (2128) is too far right. When I change it manually to something smaller, then the pop-up does appears. Looks like something is wrong with the pop-up position? BTW, the top position (4041) looks to be correct.

    opened by NadavK 2
Releases(v1.3)
  • v1.3(Sep 27, 2022)

    By default, this mode is disabled. You can enable autozoom mode when displaying objects on the map both in regular views and in the Django admin panel.

    The autozoom mode works differently depending on the number of objects that you want to display on the map.

    If the list of displayed objects is empty, the autozoom mode is disabled.

    If the list contains one object, then the map center is set to the coordinates of this object, and the map scale is set to the value of the autozoom parameter (10 for the examples above).

    If the list contains more than one object, the program determines the minimum rectangle that contains all the displayed objects. The center of the map is set to the coordinates of the center of this rectangle. The scale of the map is set in such a way as to contain the given rectangle with some indents along the edges.

    Source code(tar.gz)
    Source code(zip)
  • v1.2.1(Aug 24, 2022)

Owner
Vitaly Bogomolov
Vitaly Bogomolov
Send push notifications to mobile devices through GCM or APNS in Django.

django-push-notifications A minimal Django app that implements Device models that can send messages through APNS, FCM/GCM and WNS. The app implements

Jazzband 2k Dec 26, 2022
GameStop clone with Django

GameStop clone with Django This is my side project with GameStop clone Author: HackerApe GitHub Profile: View Profile LinkedIn Profile: View Profile

Dmitriy Shin 2 Dec 26, 2021
Code coverage measurement for Python

Coverage.py Code coverage testing for Python. Coverage.py measures code coverage, typically during test execution. It uses the code analysis tools and

Ned Batchelder 2.3k Jan 05, 2023
Inject an ID into every log message from a Django request. ASGI compatible, integrates with Sentry, and works with Celery

Django GUID Now with ASGI support! Django GUID attaches a unique correlation ID/request ID to all your log outputs for every request. In other words,

snok 300 Dec 29, 2022
An insecure login and registration website with Django.

An insecure login and registration website with Django.

Luis Quiñones Requelme 1 Dec 05, 2021
Django-Audiofield is a simple app that allows Audio files upload, management and conversion to different audio format (mp3, wav & ogg), which also makes it easy to play audio files into your Django application.

Django-Audiofield Description: Django Audio Management Tools Maintainer: Areski Contributors: list of contributors Django-Audiofield is a simple app t

Areski Belaid 167 Nov 10, 2022
Django models and endpoints for working with large images -- tile serving

Django Large Image Models and endpoints for working with large images in Django -- specifically geared towards geospatial tile serving. DISCLAIMER: th

Resonant GeoData 42 Dec 17, 2022
An orgizational tool to keep track of tasks/projects and the time spent on them.

Django-Task-Manager Task Tracker using Python Django About The Project This project is an orgizational tool to keep track of tasks/projects and the ti

Nick Newton 1 Dec 21, 2021
Template de desarrollo Django

Template de desarrollo Django Python Django Docker Postgres Nginx CI/CD Descripción del proyecto : Proyecto template de directrices para la estandariz

Diego Esteban 1 Feb 25, 2022
A reusable Django model field for storing ad-hoc JSON data

jsonfield jsonfield is a reusable model field that allows you to store validated JSON, automatically handling serialization to and from the database.

Ryan P Kilby 1.1k Jan 03, 2023
Full featured redis cache backend for Django.

Redis cache backend for Django This is a Jazzband project. By contributing you agree to abide by the Contributor Code of Conduct and follow the guidel

Jazzband 2.5k Jan 03, 2023
💨 Fast, Async-ready, Openapi, type hints based framework for building APIs

Fast to learn, fast to code, fast to run Django Ninja - Fast Django REST Framework Django Ninja is a web framework for building APIs with Django and P

Vitaliy Kucheryaviy 3.8k Jan 01, 2023
A music recommendation REST API which makes a machine learning algorithm work with the Django REST Framework

music-recommender-rest-api A music recommendation REST API which makes a machine learning algorithm work with the Django REST Framework How it works T

The Reaper 1 Sep 28, 2021
Customize the behavior of django.contrib.auth permissions.

Customizando o comportamento do django.contrib.auth. O que queremos? Não criar as permissões padrões automaticamente (add, delete, view, read). Criar

Henrique Bastos 7 Nov 26, 2022
Comparing Database performance with Django ORM

Comparing Database performance with Django ORM Postgresql MySQL MariaDB SQLite Comparing database operation performance using django ORM. PostgreSQL v

Sarath ak 21 Nov 14, 2022
Django project starter on steroids: quickly create a Django app AND generate source code for data models + REST/GraphQL APIs (the generated code is auto-linted and has 100% test coverage).

Create Django App 💛 We're a Django project starter on steroids! One-line command to create a Django app with all the dependencies auto-installed AND

imagine.ai 68 Oct 19, 2022
Актуальный сборник шаблонов для создания проектов и приложений на Django

О чем этот проект Этот репозиторий с шаблонами для быстрого создания Django проекта. В шаблоне проекта настроены следующий технологий: Django gunicorn

Denis Kustov 16 Oct 20, 2022
📝 Sticky Notes in Django admin

django-admin-sticky-notes Share notes between superusers. Installation Install via pip: pip install django_admin_sticky_notes Put django_admin_sticky_

Dariusz Choruży 7 Oct 06, 2021
Advanced school management system written in Django :)

Advanced school management system written in Django :) ⚙️ Config the project First you should make venv for this project. So in the main root of proje

AminAli Mazarian 72 Dec 05, 2022
Median and percentile for Django and MongoEngine

Tailslide Median and percentile for Django and MongoEngine Supports: PostgreSQL SQLite MariaDB MySQL (with an extension) SQL Server MongoDB 🔥 Uses na

Andrew Kane 4 Jan 15, 2022