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
django-idom allows Django to integrate with IDOM

django-idom allows Django to integrate with IDOM, a package inspired by ReactJS for creating responsive web interfaces in pure Python.

113 Jan 04, 2023
Radically simplified static file serving for Python web apps

WhiteNoise Radically simplified static file serving for Python web apps With a couple of lines of config WhiteNoise allows your web app to serve its o

Dave Evans 2.1k Dec 15, 2022
Simple XML-RPC and JSON-RPC server for modern Django

django-modern-rpc Build an XML-RPC and/or JSON-RPC server as part of your Django project. Major Django and Python versions are supported Main features

Antoine Lorence 82 Dec 04, 2022
🔥 Campus-Run Django Server🔥

🏫 Campus-Run Campus-Run is a 3D racing game set on a college campus. Designed this service to comfort university students who are unable to visit the

Youngkwon Kim 1 Feb 08, 2022
Bootstrap 4 integration with Django.

django-bootstrap 4 Bootstrap 4 integration for Django. Goal The goal of this project is to seamlessly blend Django and Bootstrap 4. Requirements Pytho

Zostera B.V. 980 Dec 29, 2022
django-tables2 - An app for creating HTML tables

django-tables2 - An app for creating HTML tables django-tables2 simplifies the task of turning sets of data into HTML tables. It has native support fo

Jan Pieter Waagmeester 1.6k Jan 03, 2023
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
Django-fast-export - Utilities for quickly streaming CSV responses to the client

django-fast-export Utilities for quickly streaming CSV responses to the client T

Matthias Kestenholz 4 Aug 24, 2022
A Redis cache backend for django

Redis Django Cache Backend A Redis cache backend for Django Docs can be found at http://django-redis-cache.readthedocs.org/en/latest/. Changelog 3.0.0

Sean Bleier 1k Dec 15, 2022
Modular search for Django

Haystack Author: Daniel Lindsley Date: 2013/07/28 Haystack provides modular search for Django. It features a unified, familiar API that allows you to

Haystack Search 3.4k Jan 08, 2023
Simple API written in Python using FastAPI to store and retrieve Books and Authors.

Simple API made with Python FastAPI WIP: Deploy in AWS with Terraform Simple API written in Python using FastAPI to store and retrieve Books and Autho

Caio Delgado 9 Oct 26, 2022
Django-pwned - A collection of django password validators

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

Quera 22 Jun 27, 2022
Django + Next.js integration

Django Next.js Django + Next.js integration From a comment on StackOverflow: Run 2 ports on the same server. One for django (public facing) and one fo

Quera 162 Jan 03, 2023
This "I P L Team Project" is developed by Prasanta Kumar Mohanty using Python with Django web framework, HTML & CSS.

I-P-L-Team-Project This "I P L Team Project" is developed by Prasanta Kumar Mohanty using Python with Django web framework, HTML & CSS. Screenshots HO

1 Dec 15, 2021
A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for quickly creating new images from the one assigned to the field.

django-versatileimagefield A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for creat

Jonathan Ellenberger 490 Dec 13, 2022
A Django backed for PostgreSQL using Psycopg 3

A Django backend for PostgreSQL using Psycopg 2 The backend passes the entire Django test suite, but it needs a few modifications to Django and to i

Daniele Varrazzo 42 Dec 16, 2022
A Django GraphQL (Graphene) base template

backend A Django GraphQL (Graphene) base template Make sure your IDE/Editor has Black and EditorConfig plugins installed; and configure it lint file a

Reckonsys 4 May 25, 2022
Django Login Api With Python

How to run this project Download and extract this project Create an environment and install all the libraries from requiements.txt pip freeze -r requi

Vikash Kisku 1 Dec 10, 2021
Exemplo de biblioteca com Django

Bookstore Exemplo de biblioteca feito com Django. Este projeto foi feito com: Python 3.9.7 Django 3.2.8 Django Rest Framework 3.12.4 Bootstrap 4.0 Vue

Regis Santos 1 Oct 28, 2021
Agenda feita usando o django para adicionar eventos

Agenda de Eventos Projeto Agenda com Django Inicio O projeto foi iniciado no Django, usando o models.py foi adicionado os dados dos eventos e feita as

Bruno Fernandes 1 Apr 14, 2022