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
Transparently use webpack with django

Looking for maintainers This repository is unmaintained as I don't have any free time to dedicate to this effort. If you or your organisation are heav

Owais Lone 2.4k Jan 06, 2023
English dictionary using Django based on freecodecamp

English Dictionary Hi there, i made this english dictionary using Django based on freecodecamp.org tutorial :) Table of Contents Preview Technologies

Aline Alencar 3 May 09, 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
Automated image processing for Django. Currently v4.0

ImageKit is a Django app for processing images. Need a thumbnail? A black-and-white version of a user-uploaded image? ImageKit will make them for you.

Matthew Dapena-Tretter 2.1k Jan 04, 2023
django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project. Inspired in the dashboard framework Dashing

django-dashing django-dashing is a customisable, modular dashboard application framework for Django to visualize interesting data about your project.

talPor Solutions 703 Dec 22, 2022
Актуальный сборник шаблонов для создания проектов и приложений на Django

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

Denis Kustov 16 Oct 20, 2022
It's the assignment 1 from the Python 2 course, that requires a ToDoApp with authentication using Django

It's the assignment 1 from the Python 2 course, that requires a ToDoApp with authentication using Django

0 Jan 20, 2022
Django app for building dashboards using raw SQL queries

django-sql-dashboard Django app for building dashboards using raw SQL queries Brings a useful subset of Datasette to Django. Currently only works with

Simon Willison 383 Jan 06, 2023
A simple app that provides django integration for RQ (Redis Queue)

Django-RQ Django integration with RQ, a Redis based Python queuing library. Django-RQ is a simple app that allows you to configure your queues in djan

RQ 1.6k Jan 06, 2023
A web app which allows user to query the weather info of any place in the world

weather-app This is a web app which allows user to get the weather info of any place in the world as soon as possible. It makes use of OpenWeatherMap

Oladipo Adesiyan 3 Sep 20, 2021
Django Livre Bank

Django Livre Bank Projeto final da academia Construdelas. API de um banco fictício com clientes, contas e transações. Integrantes da equipe Bárbara Sa

Cecília Costa 3 Dec 22, 2021
A starter template for building a backend with Django and django-rest-framework using docker with PostgreSQL as the primary DB.

Django-Rest-Template! This is a basic starter template for a backend project with Django as the server and PostgreSQL as the database. About the templ

Akshat Sharma 11 Dec 06, 2022
Money fields for Django forms and models.

django-money A little Django app that uses py-moneyed to add support for Money fields in your models and forms. Django versions supported: 1.11, 2.1,

1.4k Jan 06, 2023
Django-pwned - A collection of django password validators

Django Pwned A collection of django password validators. Compatibility Python: 3

Quera 22 Jun 27, 2022
Create a netflix-like service using Django, React.js, & More.

Create a netflix-like service using Django. Learn advanced Django techniques to achieve amazing results like never before.

Coding For Entrepreneurs 67 Dec 08, 2022
Template for Django Project Using Docker

You want a Django project who use Docker and Docker-compose for Development and for Production ? It's for you !

1 Dec 17, 2021
Sistema de tratamento e análise de grandes volumes de dados através de técnicas de Data Science

Sistema de tratamento e análise de grandes volumes de dados através de técnicas de data science Todos os scripts, gráficos e relatórios de todas as at

Arthur Quintanilha Neto 1 Sep 05, 2022
Redia Cache implementation in django.

django-redis Recipe APP Simple Recipe app which shows different kinds off recipe to the user. Why Cache ? Accessing data from cache is much faster tha

Avinash Alanjkar 1 Sep 21, 2022
Bootstrap 3 integration with Django.

django-bootstrap3 Bootstrap 3 integration for Django. Goal The goal of this project is to seamlessly blend Django and Bootstrap 3. Want to use Bootstr

Zostera B.V. 2.3k Jan 03, 2023
Example project demonstrating using Django’s test runner with Coverage.py

Example project demonstrating using Django’s test runner with Coverage.py Set up with: python -m venv --prompt . venv source venv/bin/activate python

Adam Johnson 5 Nov 29, 2021