Git Product home page Git Product logo

django-location-field's Introduction

logo

django-location-field

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

Documentation: https://django-location-field.readthedocs.io/en/latest/
License: MIT

Status

PyPI! PyPI - Downloads! Build 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, 2.2, 3.2
  • Python 2.7, 3.9, 3.10, 3.11

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

django-location-field's People

Contributors

1vank1n avatar angvp avatar arcticlinux avatar caioariede avatar camilonova avatar czpython avatar earthboundkid avatar fpoulain avatar fruitschen avatar hirunatan avatar jamim avatar jeromelebleu avatar kami avatar leibowitz avatar litchfield avatar mariocesar avatar marteinn avatar michaelhjulskov avatar mixser avatar mpauly avatar parkhomchukp avatar predatell avatar shayh avatar sylvainblot avatar tadeo avatar thejoeejoee avatar undernewmanagement avatar uniphil avatar voodmania avatar wolfskaempf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-location-field's Issues

Question about rendering the form

Hello. First of all, thank you, this is a great module and it works fine in the admin area. Although I am not sure how should I render the location selection form in my template, could anyone help me with that ? I am still a begginer.

Generate coordinates on save / import

Hello there.

So I'm importing locations with django-import-export, which have a city, state and country. I use them as based_fields.

When I import them the location field is empty, though. No coordinates were computed. They only get computed if I manually enter the data again in the admin form.

Is there a way to let the coordinates compute on import? Also, how do I render the Google Maps widget in a view/html, so I can show the location on the map to visitors?

EDIT1: It seems to be enough to touch (as in: change value and change it back) one of the based_fields in the admin form for every other based_field to be considered for the computing of the coordinates. Am I assuming correctly that the computation of the coordinates is based on the javascript portion of this package?

EDIT2: I'm implementing a geocoding-step on save of a model now through the geocoder package. Trying to figure out right now how to use "def clean_???" to update the plain location fields coordinates on save.

Allow based_fields to given as field names, instead of field references

What I mean is based_fields=[city, zipcode] vs based_fields=['city', 'zipcode'].

If I can enter my based fields this way, and django location field looks them up on the model, that would allow me to make use of fields defined in parent models. With the current implementation I have to define every field I want to base the location on on the current model.

not migrate

Hello, i have a problem, at moment to make the migrations i got the next error

ValueError: Cannot successfully create field 'location' for model 'property': 'module' object has no attribute 'PlainLocationField'.

i am using version 1.6
django 1.6

some idea about these error

Save the zoom level from the map widget

Thinking from the standpoint of the end-user, I would expect the preview map to represent what my users will see on the website. However, only the latlong is saved in the LocationField, not the zoom level. I think it'd be nice to have access to the zoom level the user selected in their preview window as this will make it more like a WYSIWYG experience.

Never display in view: TemplateDoesNotExist when i render the view with location-field

My model
`class Station(models.Model):
"""Station service."""

OPEN = 1
CLOSE = 0
STATUTLIST = (
    (OPEN, _("Ouverte")),
    (CLOSE, _("Fermée")),
)
nom_station = models.CharField(
    _('Nom de la station'), max_length=30)
statut_station = models.CharField(
    _('Ouverte ou fermée'),
    max_length=1,
    choices=STATUTLIST, default=OPEN)
city = models.ForeignKey(City, verbose_name=_('Ville'))
location = PlainLocationField(
    based_fields=['city'], zoom=7)
photo_station = models.ImageField(
    _("Photo"),
    upload_to=utils.photo_file_path,
    storage=utils.photo_storage,
    null=True,
    blank=True,
)
telephone = PhoneNumberField(_('Numero de téléphone'), null=True)`

My view
`def add_station_view(request, station_id=None):
"""Ajout et modification d'une station."""
template_name = "backend/main/add_station.html"
args = {}
args.update(csrf(request))

args['meta_keyword'] = args['home_title'] = _('Station')
args['meta_description'] = _('Création d\'une nouvelle station.')

if station_id is not None:
    args['cobject'] = get_object_or_404(
        sitemodels.Station, id=station_id)
    args['meta_description'] = _(
        'Editer %s' % (args['cobject'].get_nom_station()))
    form = siteforms.StationForm(
        request=request,
        instance=args['cobject']
    )

if request.method == 'POST':
    if 'cobject' in args and form.has_changed():
        form = siteforms.StationForm(
            request.POST,
            request=request,
            instance=args['cobject'])
        args['updated'] = True
    else:
        new_station = sitemodels.Station()
        form = siteforms.StationForm(
            request.POST,
            request=request,
            instance=new_station)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.save()
        if 'updated' in args:
            messages.success(request, STDUMSG)
        else:
            obj.cree_parking()
            obj.cree_catalogue()
            messages.success(
                request, _('Nouvelle station ajoutée'))
        if 'save_and_add_another' in request.POST:
            return HttpResponseRedirect(
                reverse(
                    'ppsmsite:addstation',
                    current_app=request.resolver_match.namespace,
                )
            )
        return HttpResponseRedirect(
            reverse(
                'ppsmsite:liststatio',
                current_app=request.resolver_match.namespace,
            )
        )
else:
    if 'cobject' not in args:
        form = siteforms.StationForm(request=request)
args['form'] = form
return render_to_response(
    template_name,
    args,
    context_instance=RequestContext(request)
)`

My form:
`class StationForm(forms.ModelForm):
"""Docstring for StationsForm."""

def __init__(self, *args, **kwargs):
    """Form Init."""
    self.request = kwargs.pop('request', None)
    super(StationForm, self).__init__(*args, **kwargs)

class Meta:
    """Docstring for StationForm meta."""

    model = sitemodels.Station
    fields = [
        'telephone',
        'photo_station', 'location', 'city', 'nom_station']`

When i exclude field in form my view work, but when i try to render it with location field it show me this error:
TemplateDoesNotExist at /station/ajouter/

backend/main/add_station.html

Request Method: GET
Request URL: http://localhost:8000/station/ajouter/
Django Version: 1.8.7
Exception Type: TemplateDoesNotExist
Exception Value:

backend/main/add_station.html

Exception Location: C:\Python34\lib\site-packages\django\template\loader.py in render_to_string, line 137
Python Executable: C:\Python34\python.exe
Python Version: 3.4.4
Python Path:

['C:\Users\CRESUS\Documents\projet\ppsm',
'C:\Python34\lib\site-packages\django_datetime_widget-0.9.3-py3.4.egg',
'C:\WINDOWS\SYSTEM32\python34.zip',
'C:\Python34\DLLs',
'C:\Python34\lib',
'C:\Python34',
'C:\Python34\lib\site-packages']

Server time: jeu, 7 Avr 2016 02:28:29 +0100

Template-loader postmortem

Django tried loading these templates, in this order:

Using loader django.template.loaders.filesystem.Loader:
    C:\Users\CRESUS\Documents\projet\ppsm\templates\backend\main\add_station.html (File exists)
Using loader django.template.loaders.app_directories.Loader:
    C:\Python34\lib\site-packages\suit\templates\backend\main\add_station.html (File does not exist)
    C:\Python34\lib\site-packages\django\contrib\admin\templates\backend\main\add_station.html (File does not exist)
    C:\Python34\lib\site-packages\django\contrib\auth\templates\backend\main\add_station.html (File does not exist)
    C:\Python34\lib\site-packages\django\contrib\gis\templates\backend\main\add_station.html (File does not exist)
    C:\Python34\lib\site-packages\ckeditor\templates\backend\main\add_station.html (File does not exist)
    C:\Python34\lib\site-packages\ckeditor_uploader\templates\backend\main\add_station.html (File does not exist)
    C:\Python34\lib\site-packages\leaflet\templates\backend\main\add_station.html (File does not exist)
    C:\Python34\lib\site-packages\geoposition\templates\backend\main\add_station.html (File does not exist)

Please help if i forget to do something

Lat and lng are swapped in the admin widget

Hello,

when displaying the location in the admin. The lat and long are swapped. I double crosschecked this.

x in my case is 48.11 and y is 11.23 but displayed is 11.23, 48.11

Kind regards

Maps doesn't render, all other fields as NaN

Hi,
I'm trying to use django-location-field in a custom view (and not in the admin), and the map is acting super-weird.

When I load the page
image

After I type something in the address box
image

And the most weird part: It's working just fine in the admin panel

media folder not installed with package

This might be extremely stupid question, but when I install this package, media folder isn't present. Any idea why that happens?

Moreover, wouldn't be better to rename media to static so collectstatic can pick it up automatically?

Location Widget showing latitude and longitude inverse values

I already had a lot of locations point on my database. When I added the LocationWidget to my admin.py I verified that the class is exchanging values from the Latitude and Longitude from my items.

This is a snippet from widgets.py that I installed by using "pip install". From line 34 to line 49.

if value is not None:
            try:
                if isinstance(value, six.string_types):
                    lat, lng = value.split(',')
                else:
                    lat = value.x # Notice that this is actually the longitude in the Point class from GEOS
                    lng = value.y # And this one is the latitude

                value = '%s,%s' % (
                    float(lat),
                    float(lng),
                )
            except ValueError:
                value = ''
        else:
            value = ''

Am I doing something wrong? Or is this a bug?

Error adding when you don't have default attribute on the LocationField in the model

Hi,

I've found a bug that makes the rest of the js fails, when you don't specify a default point in the model and you're in the add form on the admin it will crash all the js.

For example I have a model like this:

class Region(models.Model):
    name = models.CharField()

class TestLocation(models.Model):
    region = models.ForeignKey(Region)
    coordinates = LocationField(based_fields=[region], zoom=7, blank=True,
                                null=True)
    test = models.CharField()

When I go to: http://localhost:8000/admin/myapp/testlocation/add/ crashes.

I made a patch I will be uploading it in few minutes with the proper pull request,

Map does not render

Hi,

for me the map will not render at all. In the form view the allocated space is visible, but no map tiles appear. There is no related error on the console. I believe I'm just missing a load or a template tag, but I cannot find out which.

Help! :)

About Example on first page, form.js path

Hi,

On the frontpage example you use ... location = LocationField(based_fields=[city], zoom=7, default=Point(1, 1))... but you do not import from django.contrib.gis.geos.Point

And is there a way to change media/form.js path? I want to have it inside my static folder path...

ValueError: too many values to unpack

 File "/var/www/virtualenvs/backoffice/src/django-location-field/location_field/forms/spatial.py", line 11, in clean
    lat, lng = value.split(',')
ValueError: too many values to unpack

Seems to be that sometimes the coordinate have an extra comma and is not working .. so the proper fix is to do a try / except instead an if validating if value.

Rendering widget in custom form

I am trying to render PlainLocationFIeld in my form the following way:

class PhotoForm(forms.Form):
    # ...
    geo_query = forms.CharField()
    location = PlainLocationField(based_fields=[geo_query], zoom=10)
    # ...

And this results in following error:

AttributeError at /admin/base/photo/907/
'CharField' object has no attribute 'name'

The only way I managed to solve this problem is by setting 'name' attribute to CharfField so my form looks like this:

class PhotoForm(forms.ModelForm):
    # ...
    geo_query = forms.CharField()
    geo_query.name = 'geo_query'
    location = PlainLocationField(based_fields=[geo_query], zoom=10)
    # ...

But I'm not happy with this dirty solution. I don't have deep understanding of how Django creates forms for models and I guess I'm missing something really important. Is there better way to make PlainLocationWidget work with custom form?
I am using Django 1.7 and python 2.7.

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.

No module named app.py

Documentation: Stable is v. 1.6.1
Documentation: States that django-location-field supports Django 1.7 to 1.9 but forces download of Django 1.8.15 during pip install.
Documentation: states that location_field.apps.DefaultConfig should be included in INSTALLED_APPS but module apps.py does not exist in the PyPi install version.
This installed version has documentation issues. Wrong version uploaded to PyPi?

pyinstaller shows : No module named apps when run then executable file.

Hi,
Using : linux red hat, django : 1.10, pyinstaller : 3.2, python : 2.7.5
I created a basic django project and tried to make it executable using PyInstaller 3.2,
the project runs fine when given : python manage.py runserver.
when i used pyinstaller : has one traceback : Attribute error: settings object has no attribute ' template_context_processors', how ever the outfile is created in dist dir, when i run the executable file it shows : ImportError: No module named apps. i tried to copy the apps dir from django to project , still same error, checked the apps dir has init file, did all the hidden-import commands, did try hooks,
please suggest if there is something wrong. or should i switch to some other freezing app.
thanks in advance

ValueError: need more than 1 value to unpack

I am getting the following instances when I don't fill the location field in an admin form-

  File ".../lib/python2.7/site-packages/location_field/widgets.py", line 16, in render
    lat, lng = value.split(',')
ValueError: need more than 1 value to unpack

There can be instances (like if the location field is left empty in an admin interface) that value is an empty string instead of None.
To handle the empty string case in addition to None string, it would be better to replace like-
https://github.com/caioariede/django-location-field/blob/master/location_field/widgets.py#L23

with if value:

Change README.md

Change

from location_field.models import PlainLocationField

to

from location_field.models.plain import PlainLocationField

in README.md

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?

Version 1.6.1 supports Django 1.9?

It seems to work fine for me, so I'd recommend updating setup.py to allow using Django 1.9. However, I can't seem to run tox or tests with version 1.6.1, so I can't confirm this.

Still impossible to use with non-spatial database without heavy effort

Hi, I really like this project. However, when I tried to use it just to allow location selection on the map without any GIS linking, I ran into problems.

Since the PlainLocationField is in the same module like the regular LocationField, when importing it without having the spatial database and libraries set up, it fails with import error:

ImportError: cannot import name GEOSException

Currently, the only fix is to install GEOS even though you don't need it for anything else. Very simple solution would be to separate the fields into two separate modules. I actually think about forking your repository and fix it. You interested?

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.

Wrong spatial convention

I am not sure about this but I think you might have a wrong convention when storing your Point fields at least in PostGIS.

From the PostGIS documentation: http://postgis.net/docs/ST_Point.html you can see that the first coordinate of a point is the longitude the second is the latitude. Exactly the opposite convention of google maps!

Another mention of this is here: http://workshops.opengeo.org/postgis-intro/geography.html

Therefore I think you should swap the values transmitterd from your google maps javascript.

This issue almost never becomes appearent unless you use your database to do distance lookups with latitudes over 90 degrees. When that happens, the PostGIS api thinks the longitudes are >90 and throws a DatabaseError:Coordinate values are out of range [-180 -90, 180 90] for GEOGRAPHY type.

I would advise you to look for yourself if what I'm writing is true (I just came accross it while debugging this weird database error) and if it is, make the change.

F.

I'd like to work on a patch but unsure of current branch status

We'd like to solve the issue of the map widget not showing in the admin if the fieldset is collapsed. I'm guessing I'll need to store a reference to the map object somewhere so I can trigger a refresh when it becomes visible.

However my question is about the status of the 2.x code. We're currently on the PyPi branch. I'm not sure whether to fork 1.6 or fork master. How close to being stable is the newer code? Is it still being worked on?

template display

how i can use this app in templates that make user ability to pick the location ?

Let based_fields do relationship lookups

This would be blocked by #38, but if that is implemented, could we get the feature to let based_on fields span relationships?

The Django admin can do this, for example, in a ModelAdmin's search_fields attribute. E.g. search_fields = ('related_model__attribute',).

Django 1.9 Support

I am using django-location-field 1.6.1 with Django 1.9. All things work correctly, but there is a problem in admin page. The problem does not appear in Django 1.8.7. Based on my tests, this is a Javascript issue.

I have installed django-location-field based on "Basic usage" part of the documentation:

    city = models.ForeignKey(City)
    location = PlainLocationField(based_fields=[city], zoom=14, default='')

This is the scenario: I set the location in admin and save it. Then when I click on the object to update some fields, I see that location has changed. It has changed to the center of the city specified by city field.

In Django 1.9, a change event on city field is fired at page load (Actually a change event is fired for all fields). And django-location-field's form.js code listens to this event, and populates location based on it. But this shouldn't be done at page load, but when user changes the city field by hand.

For solving the problem, we put these lines in a $(document).ready(function(){...});. I don't know if this a proper solution.

https://github.com/caioariede/django-location-field/blob/master/location_field/static/location_field/js/form.js#L147-L175

Soon reply is appreciated.

Thanks.

Marker icon not showing on map

I installed the current Beta version: 2.0.0b0 via pip and use it with Django 1.9.4.
When editing an item with the new location field, the marker icon isn't loading and i get a 404 response for it.

It tries to load the icon from /static/location_field/images/marker-icon.png but as I checked the image file in the location_field folder I noticed that it's named marker-icon-2x.png.

I tried to rename it to marker-icon.png and the 404 disappears, but the icon isn't showing on the map either.

location field + django suit = triggers suits confirm modified form popup window

if you try to leave admin detail view of a model that has a location field in it, even if you didn't changed anything, suit brings a popup windows with a message "You have unsaved changes." are you sure you want to leave this page?

this happens when location field has lat or lng value that ends with zero(s)
e.g. 45.801820,16.0506820

in widgets.py i have changed lines 25:34 with these to fix this issue.

                if not isinstance(value, six.string_types):
                    lng = value.x
                    lat = value.y
                    value = '%s,%s' % (
                        float(lat),
                        float(lng),
                    )

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:

charettes/django-admin-enhancer#23

jazzband/django-model-utils#183

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

[INSTALLATION ERROR] ImportError: No module named apps

In the README i see:

  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

After this, when i launch ./manage.py migrate I see:

ImportError: No module named apps
And it is right as you can see in the attachment
schermata 2016-03-01 alle 12 27 14

Thank you in advance

set default map.provider

I have set map.provider in "project:setting"

LOCATION_FIELD = {
'map.provider': 'openstreetmap',
}

but still using google maps

and i have error in java script from google maps
"Google Maps API warning: NoApiKeys"

i already provide that into settings:

LOCATION_FIELD = {
'map.provider': 'openstreetmap',
'provider.google.api_key': 'AIzaSyCa8xXtg_48hAqHloKB0WPM2BXRmHoM_co',
}

Please enlightenment me :)
Thanks...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.