Location field and widget for Django. It supports Google Maps, OpenStreetMap and Mapbox

Overview

logo

django-location-field

Let users pick locations using a map widget and store its latitude and longitude.

Stable version: django-location-field==2.1.0
Documentation: https://django-location-field.readthedocs.io/en/latest/
License: MIT

Status

Build Status Documentation Status Say Thanks!

Tests are performed with Python 2 and 3, Django 1.11 and 2, and SpatiaLite.

Features

  • Support for multiple map engines, like Google Maps, OpenStreetMap and Mapbox.
  • Support for multiple search engines, like Google, Nominatim, Yandex and Addok.
  • Works with both Spatial and non-Spatial databases.

Compatibility

  • Django >= 1.11
  • Python 2.7, 3.6, 3.7

Spatial Databases

  • PostGIS
  • SpatiaLite

Installation

  1. Install through pip (or manually place it on your PYTHONPATH).

    pip install django-location-field

  2. Add location_field.apps.DefaultConfig to INSTALLED_APPS your settings.py file

For example, PostGIS:

https://docs.djangoproject.com/en/dev/ref/contrib/gis/install/postgis/

Basic usage (using Spatial Database)

from django.contrib.gis.db import models
from django.contrib.gis.geos import Point
from location_field.models.spatial import LocationField

class Place(models.Model):
    city = models.CharField(max_length=255)
    location = LocationField(based_fields=['city'], zoom=7, default=Point(1.0, 1.0))

Basic usage (without Spatial Database)

from django.db import models
from location_field.models.plain import PlainLocationField

class Place(models.Model):
    city = models.CharField(max_length=255)
    location = PlainLocationField(based_fields=['city'], zoom=7)

Screenshot

Screenshot


Nick Frost has credit over the image used as logo for this project. CC BY

Comments
  • the map does not appear

    the map does not appear

    Hi, since 3 days ago the map does not appear, and it does not throw me any errors in the google chrome console, any idea or where find error?

    Django version 2.1.1, using settings 'mywebsite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [19/Nov/2018 21:39:41] "GET /static/admin/css/dashboard.css HTTP/1.1" 200 412 [19/Nov/2018 21:39:41] "GET /static/admin/img/icon-changelink.svg HTTP/1.1" 200 380 [19/Nov/2018 21:39:41] "GET /static/admin/img/icon-addlink.svg HTTP/1.1" 200 331 Not Found: /robots.txt [2018-11-19 21:39:42,142] log: WARNING - Not Found: /robots.txt [19/Nov/2018 21:39:42] "GET /robots.txt HTTP/1.1" 404 4172 [19/Nov/2018 21:39:42] "GET /admin/ HTTP/1.1" 200 16892 [19/Nov/2018 21:39:46] "GET /admin/dlf_app/place/add/ HTTP/1.1" 200 10300 [19/Nov/2018 21:39:46] "GET /static/admin/js/inlines.js HTTP/1.1" 200 13813 [19/Nov/2018 21:39:46] "GET /static/location_field/js/form.js HTTP/1.1" 200 19650 [19/Nov/2018 21:39:46] "GET /admin/jsi18n/ HTTP/1.1" 200 7047 [19/Nov/2018 21:40:16] "GET /static/admin/img/inline-delete.svg HTTP/1.1" 200 560

    captura de pantalla 2018-11-19 a la s 21 45 11
    opened by CARocha 15
  • Browser autocomplete creates incorrect point

    Browser autocomplete creates incorrect point

    Hi Team, thanks for creating a cool app.

    I have found an issue recently where if browser autocomplete is used then the location field point is incorrect.

    screenshot - good point created on typing typing in - address works

    screenshot - bad point created on autocomplete (Note: the fields in yellow were the browser autocomplete fields) autocomplete - address does not work

    I have <form ... autocomplete="off">... but a lot of browsers ignore this anyway.

    Thanks for your assistance in advance.

    opened by lukeaus 12
  • Issue when upgrade to 2.0.1

    Issue when upgrade to 2.0.1

    I just upgraded the library from 1.6 and got this error:

    'Settings' object has no attribute 'LOCATION_FIELD'

    Seems is not taking the default value since I don't have any LOCATION_FIELD setting.

    opened by camilonova 7
  • Missing leaflet static files causing errors with ManifestStaticFilesStorage

    Missing leaflet static files causing errors with ManifestStaticFilesStorage

    When you're using the ManifestStaticFilesStorage, collectstatic fails because it can't find two files. Namely:

    • location_field/images/layers.png
    • location_field/images/layers-2x.png

    The solution would be either to remove those lines from leaflet.css or include the images with the package.

    Here's a relevant issue: https://github.com/evansd/whitenoise/issues/96

    opened by mixxorz 7
  • install_requires shouldn't reference Django itself

    install_requires shouldn't reference Django itself

    Currently pip installing django-location-field downgrades Django itself:

    $ pip install django-location-field
    Installing collected packages: Django, django-location-field
      Found existing installation: Django 1.9.2
        Uninstalling Django-1.9.2:
          Successfully uninstalled Django-1.9.2
    Successfully installed Django-1.8.9 django-location-field-1.6.1
    

    Even if django-location-field really doesn't work on Django 1.9 this is still surprising behaviour. See similar discussions:

    https://github.com/charettes/django-admin-enhancer/issues/23

    https://github.com/carljm/django-model-utils/issues/183

    (yeah - it's me each time ;-) )

    opened by andybak 7
  • How to load static files?

    How to load static files?

    I'm sure I'm missing the obvious here. My form displays a blank space where the map should go, essentially because the static files do not get loaded (or referenced for that matter) in my template. How should I link them? How should I configure the static files?

    opened by JoseTomasTocino 6
  • max_length error

    max_length error

    Django 1.9.1

    from location_field.models.plain import PlainLocationField
    ...
    city = models.ForeignKey(City, blank=True, null=True)
    region = models.ForeignKey(Region, blank=True, null=True)
    location = PlainLocationField('place',
                                 based_fields=['city'],
                                 zoom=7
                                 )
    

    When I try to makemigrations I'm got:

    ERRORS:
    trips.TripExpence.location: (fields.E121) 'max_length' must be a positive integer.
    

    Second question: Name of city defined in another model and linked through ForeignKey. Is this will work?

    And third: Can I set the place for location field using both entites: city and region?

    opened by Guest007 6
  • location field map not working with bootstrap 4 modal

    location field map not working with bootstrap 4 modal

    HI all,

    I am using the forms inside a bootstrap 4 modal. The Map is not render in the modal.

    Example code:

    <html>
        <head>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
            <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
            {{form.media}}
        </head>
        <body>
         <div class="modal fade" id="modal1" role="dialog">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                                {% for f in  form %}
                                    <label for="{{ f.auto_id }}" class="bmd-label-static">{{ f.label }}</label>
                                    {{ f }}
                                {% endfor %}
                </div></div></div>
        </body>
    <script>
            $(document).ready(function (){
                $('#modal1').modal()
            })
        </script>
    </html>
    

    this code work:

    <html>
        <head>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
            <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
            {{form.media}}
        </head>
        <body>
             {% for f in  form %}
                  <label for="{{ f.auto_id }}" class="bmd-label-static">{{ f.label }}</label>
                  {{ f }}
             {% endfor %}
        </body>
    </html>
    

    I appreciate if you can help me solve this.

    opened by Esteban108 5
  • Map is not rendering

    Map is not rendering

    When opening change form in admin map is blank. image After changing city it's refreshed and renders correctly, after saving model it works correctly, problem exists only when opening model that wasn't edited through admin (it was imported). Dragging map or changing location field don't help.

    I'm using postgis, and from location_field.models.spatial import LocationField Tested in django 2.2 and 1.10, with django-location-field==2.1.0

    opened by Alexander3 5
  • Not compatible with Django 2.1

    Not compatible with Django 2.1

    I did a basic install and added a PlainLocationField to my model, and now the admin crashes with:

    TypeError: render() got an unexpected keyword argument 'renderer'
    

    It seems on the Django side it is calling:

    widget.render(
                name=self.html_initial_name if only_initial else self.html_name,
                value=self.value(),
                attrs=attrs,
                renderer=self.form.renderer,
            )
    

    But the LocationWidget doesn't accept renderer as a keyword argument.

    opened by carlmjohnson 5
  • Allow blank value for LocationField

    Allow blank value for LocationField

    Environment details

    Python version: 2.7.3 Django version: 1.5.1 Django Location Field version: 84718c64e039c4ca2974b62e220b60b6db74cf12 (latest master checkout)

    Problem

    Currently the form explodes (both on validation and on rendering of the the field value) if you set field blank attribute to True, leave the value empty and save the model.

    return func(*args, **kwargs)
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 989, in add_view
        if form.is_valid():
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 126, in is_valid
        return self.is_bound and not bool(self.errors)
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 117, in _get_errors
        self.full_clean()
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 272, in full_clean
        self._clean_fields()
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 287, in _clean_fields
        value = field.clean(value)
      File "/home/vagrant/.virtualenvs/foo/src/location-field/location_field/forms.py", line 32, in clean
        lat, lng = value.split(',')
    ValueError: need more than 1 value to unpack
    
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/template/base.py", line 830, in render
        bit = self.render_node(node, context)
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/template/debug.py", line 74, in render_node
        return node.render(context)
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/template/debug.py", line 87, in render
        output = force_text(output)
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/utils/encoding.py", line 99, in force_text
        s = s.__unicode__()
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 411, in __str__
        return self.as_widget()
      File "/home/vagrant/.virtualenvs/foo/local/lib/python2.7/site-packages/django/forms/forms.py", line 458, in as_widget
        return widget.render(name, self.value(), attrs=attrs)
      File "/home/vagrant/.virtualenvs/foo/src/location-field/location_field/widgets.py", line 14, in render
        lat, lng = value.split(',')
    ValueError: need more than 1 value to unpack
    

    This pull request fixes this and allows a blank value.

    bug 
    opened by Kami 5
  • Mapbox doesn't work as map provider

    Mapbox doesn't work as map provider

    Mapbox doesn't work as map provider since they deprecated classic styles: https://blog.mapbox.com/deprecating-studio-classic-styles-d8892ac38cb4 When I try to load map at the django admin panel, the map doesn't render correctly. Response to the request is: {"message":"Classic styles are no longer supported; see https://blog.mapbox.com/deprecating-studio-classic-styles-d8892ac38cb4 for more information"}

    opened by parkhomchukp 0
  • How to update map marker with current location on the map

    How to update map marker with current location on the map

    Good day,

    We are using the library with this configuration

    LOCATION_FIELD = {
        "map.provider": "openstreetmap",
        "search.provider": "nominatim",
    }
    

    The model is using a PlainLocationField.

    We need to allow the users to use their current location in the map. For this, we implemented this little script

      function getLocation() {
        if ("geolocation" in navigator) {
          navigator.geolocation.getCurrentPosition(showPosition, error);
        } else {
          $("#location-message").show()
        }
      }
      function showPosition(position) {
        $("#id_location").val(position.coords.latitude + "," + position.coords.longitude)
      }
      function error(err) {
        $("#location-message").show()
      }
    

    it is working fine, the latitude and longitude is automatically updated; however, the marker is not. How may we force the marker to move to the new coordinates?

    We tried editing the coordinates directly and it is not working either; it seems that the marker updates the coordinates field but it does not work in the other way.

    Thank you,

    opened by jlariza 0
  • LocationField throws AttributeError because value is always None

    LocationField throws AttributeError because value is always None

    Hello there. I have a strange behaviour with the LocationField in my forms.py. I guess i do something wrong, but have no idea what it is (maybe the problem is that i use crispy-forms?)

    I have a Spatial LocationField in my model and added it also to my Create-Form.

    forms.py

    from location_field.forms.spatial import LocationField
    
    class SomeCreateForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['location'].initial = "2.0,2.0"
    
            self.helper = FormHelper()
            self.helper.form_tag = False
            self.helper.layout = Layout(
               ...
                LocationField("location"),
                ...
                Submit("create", "Create", css_class="some_class"),
            )
    
        class Meta:
            model = Place
            fields = (..., 'location', ...)
    

    Problem:

    When LocationField.clean() is called, the value is always None, which leads to a AttributeError. The initial-value gets propagated to self.initial in my case.

    class LocationField(PlainLocationField):
        def clean(self, value):
            try:
                lat, lng = value.split(',')
                return Point(float(lng), float(lat))
            except ValueError:
                return None
    

    So as a workaround i created a costum MyLocationField() where i add the initial value directly into the .clean() function. I am looking forward to any kind of help or advice here. Thank you!

    opened by daMichaelB 0
Owner
Caio Ariede
Caio Ariede
This is a Django app that uses numerous Google APIs such as reCAPTURE, maps and waypoints

Django project that uses Googles APIs to auto populate fields, display maps and routes for multiple waypoints

Bobby Stearman 57 Dec 3, 2022
A better and faster multiple selection widget with suggestions

django-searchable-select A better and faster multiple selection widget with suggestions for Django This project is looking for maintainers! Please ope

Andrew Dunai 105 Oct 22, 2022
Alt1-compatible widget host for RuneScape 3

RuneKit Alt1-compatible toolbox for RuneScape 3, for Linux and macOS. Compatibility macOS installation guide Running This project use Poetry as packag

Manatsawin Hanmongkolchai 75 Nov 28, 2022
Displaying objects on maps in the Django views and administration site.

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

Vitaly Bogomolov 31 Dec 28, 2022
A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.

Django Countries A Django application that provides country choices for use with forms, flag icons static files, and a country field for models. Insta

Chris Beaven 1.2k Jan 7, 2023
A django model and form field for normalised phone numbers using python-phonenumbers

django-phonenumber-field A Django library which interfaces with python-phonenumbers to validate, pretty print and convert phone numbers. python-phonen

Stefan Foulis 1.3k Dec 31, 2022
A Django application that provides country choices for use with forms, flag icons static files, and a country field for models.

Django Countries A Django application that provides country choices for use with forms, flag icons static files, and a country field for models. Insta

Chris Beaven 1.2k Dec 31, 2022
A django model and form field for normalised phone numbers using python-phonenumbers

django-phonenumber-field A Django library which interfaces with python-phonenumbers to validate, pretty print and convert phone numbers. python-phonen

Stefan Foulis 1.3k Dec 31, 2022
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 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 3, 2023
Custom Django field for using enumerations of named constants

django-enumfield Provides an enumeration Django model field (using IntegerField) with reusable enums and transition validation. Installation Currently

5 Monkeys 195 Dec 20, 2022
A pickled object field for Django

django-picklefield About django-picklefield provides an implementation of a pickled object field. Such fields can contain any picklable objects. The i

Gintautas Miliauskas 167 Oct 18, 2022
A pickled object field for Django

django-picklefield About django-picklefield provides an implementation of a pickled object field. Such fields can contain any picklable objects. The i

Gintautas Miliauskas 167 Oct 18, 2022
A django integration for huey task queue that supports multi queue management

django-huey This package is an extension of huey contrib djhuey package that allows users to manage multiple queues. Installation Using pip package ma

GAIA Software 32 Nov 26, 2022
Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project

Django URL Shortener Django URL Shortener is a Django app to to include URL Shortening feature in your Django Project Install this package to your Dja

Rishav Sinha 4 Nov 18, 2021
Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.

django-widget-tweaks Tweak the form field rendering in templates, not in python-level form definitions. Altering CSS classes and HTML attributes is su

Jazzband 1.8k Jan 2, 2023
Resolve form field arguments dynamically when a form is instantiated

django-forms-dynamic Resolve form field arguments dynamically when a form is instantiated, not when it's declared. Tested against Django 2.2, 3.2 and

DabApps 108 Jan 3, 2023
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
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

Yunbo Shi 8 Oct 28, 2022