Home > database >  Django map widget interface in Django admin
Django map widget interface in Django admin

Time:11-16

I have a model with a location field like so:

from django.contrib.gis.db import models as gis_models

class Facility(models.Model):
    location = gis_models.PointField(srid=4326, verbose_name=_('location'), null=True, blank=True)

I want the user to be able to set a location using a map in django admin. I have added the below code in my django admin:

from django.contrib.gis.db import models as gis_models
from mapwidgets.widgets import GooglePointFieldWidget

@admin.register(Facility)
class FacilityAdmin(admin.ModelAdmin):
    formfield_overrides = {
        gis_models: {'widget': GooglePointFieldWidget},
        }

at the end I have added the following setting to my settings.py:

MAP_WIDGETS = {
    "GooglePointFieldWidget": (
        ("zoom", 12),
        ("mapCenterLocation", [ 50.8157, 9.1846]),
    ),
    "GOOGLE_MAP_API_KEY": env('GOOGLE_MAP_API_KEY')
}

I am using postgis image as my database and the following is my requirements.txt:

asgiref==3.5.2
async-timeout==4.0.2
branca==0.5.0
certifi==2022.9.24
chardet==5.0.0
charset-normalizer==2.1.1
click==8.1.3
colorama==0.4.6
Deprecated==1.2.13
Django==4.1.2
django-crispy-forms==1.14.0
django-environ==0.9.0
django-map-widgets==0.4.0
django-rq==2.5.1
folium==0.13.0
idna==3.4
Jinja2==3.1.2
lml==0.1.0
MarkupSafe==2.1.1
numpy==1.23.4
packaging==21.3
pandas==1.5.1
Pillow==9.2.0
postgis==1.0.4
psycopg2==2.9.4
pyexcel==0.7.0
pyexcel-io==0.6.6
pyparsing==3.0.9
python-dateutil==2.8.2
pytz==2022.5
redis==4.3.4
requests==2.28.1
rq==1.11.1
six==1.16.0
sqlparse==0.4.3
texttable==1.6.4
tzdata==2022.5
urllib3==1.26.12
wrapt==1.14.1

The map appears in django admin, but as it turns out, it doesn't read the settings. Also the styling of the map is just unacceptable. Is there any way it could be fixed? Right now this is what I'm getting in my django admin panel: enter image description here

CodePudding user response:

Apparently, the syntax is wrong. As it says in the document of Django Map Widgets, formfield_overrides should be written like this:

from django.contrib.gis.db import models as gis_models

class FacilityAdmin(admin.ModelAdmin):
    formfield_overrides = {
        gis_models.PointField: {'widget': GooglePointFieldWidget},
        }

*Notice the PointField added to gis_models.

Also remember to enable Maps Javascript Api in google console as it says here.

  • Related