caioariede / django-location-field Goto Github PK
View Code? Open in Web Editor NEWLocation field and widget for Django. It supports Google Maps, OpenStreetMap and Mapbox
License: MIT License
Location field and widget for Django. It supports Google Maps, OpenStreetMap and Mapbox
License: MIT License
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.
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?
On readme.md you have:
See the example postgis and example sqlite.
However neither of these 2 links are accessible (Im getting 404s)
https://github.com/caioariede/django-location-field/blob/master/example_sqlite
https://github.com/caioariede/django-location-field/blob/master/example_postgis
Thanks
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
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:
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?
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
Hi-
When I use the widget in the Django admin form as an InlineModel, if the extra
is set to 1, the default works fine and the map gets updated with the address. However, when extra
is set to 0 and a new model is added for the InlineModel, the map gets stuck.
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.
Soon reply is appreciated.
Thanks.
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
I found a solution here: oxplot/fysom#1
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.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?
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.
Seems now a google API Key is required to show a map.
https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys
I think you would need to add an extra setting for it.
https://github.com/caioariede/django-location-field#installation
Release version does not contains
location_field/apps.py
location_field/settings.py
that files.
So if I add 'location_field.apps.DefaultConfig'
in settings.INSTALLED_APPS
, raise error like that.
AttributeError: module 'location_field' has no attribute 'DefaultConfig'
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
screenshot - bad point created on autocomplete
(Note: the fields in yellow were the browser autocomplete fields)
I have <form ... autocomplete="off">... but a lot of browsers ignore this anyway.
Thanks for your assistance in advance.
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,
Hello,
I've tried installing using pip install django-location-field
, works properly but when checking the package, both forms
and models
are missing. Maybe an issue with the manifest file ?
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 ;-) )
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.
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.
Please.
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?
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.
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: evansd/whitenoise#96
i configured settings wrong
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?
How to get lat and lng parameters on view?
how i can use this app in templates that make user ability to pick the location ?
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?
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),
)
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.
In the README i see:
pip install django-location-field
location_field.apps.DefaultConfig
to INSTALLED_APPS your settings.py fileAfter 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
Thank you in advance
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.
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
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! :)
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...
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.
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.
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.
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...
Change
from location_field.models import PlainLocationField
to
from location_field.models.plain import PlainLocationField
in README.md
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.