GeoDjango Leaflet Maps – Creating Forms with Geometry Field and Leaflet Map

djangogeodjangoleaflet

i use geodjango and leaflet and i want to create a django form where including geometry field with map widget (the user must to put in leaflet map) like as django admin page . i try to follow this example

but in html page dont show me the form ,any idea ?

here the code :

urls.py

url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'),

models.py

from djgeojson.fields import PolygonField
from django.db import models

class MushroomSpot(models.Model):
    name = models.CharField(max_length=256)
    geom = PolygonField()

    def __unicode__(self):
    return self.name

forms.py

from django import forms
from leaflet.forms.fields import PolygonField
from mushrooms.models import MushroomSpot


class WeatherStationForm(forms.ModelForm):
    geom = PolygonField()
    class Meta:
        model = MushroomSpot
        fields = ('name', 'geom')

html page :

{% load leaflet_tags %}
<html>
<head>
{% leaflet_js plugins="forms" %}
    {% leaflet_css plugins="forms" %}
</head>
<body>
<h1>Edit {{ object }}</h1>
<form action="POST">
{{ WeatherStationForm }}
<input type="submit"/>
</form>
</body>
</html>

Best Answer

You did not initialize your WeatherStationForm within the view. To do so, you have to inherit from TemplateView and override get_context function:

Example (not tested):

# Normally in views.py

class MapView(TemplateView):
    template_name = 'index.html'

    def get_context(self, **kwargs):
        context = {'weatherstation': WeatherStationForm()}
        return context

Now, WeatherStationForm is initialized and you can access it in your index.html template via {{ weatherstation }}:

{% load leaflet_tags %}
<html>
<head>
{% leaflet_js plugins="forms" %}
    {% leaflet_css plugins="forms" %}
</head>
<body>
<h1>Edit {{ object }}</h1>
<form action="POST">
{{ weatherstation }}
<input type="submit"/>
</form>
</body>
</html>

And finally your urls.py:

from views import MapView

url(r'^$', MapView.as_view(), name='home')

Note: Urls-definition has changed to path()in Django 2.0 - maybe you should update your django version first...