0

I am building a web application using Django. The page shows a large leaflet map, in which users can select one out of several layers. I want users to be able to select a layer, click on the map and add a note to that location and that layer.

I've created a model form, which holds the note itself. This works fine, and saves to my database. However, I need to also include the currently selected layer and mouse-click-location, which is readily available as a JS variable. How do I pass this on in Django?

My views.py holds the following:

if request.method == 'POST':
        form = MapNoteForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = MapNoteForm()

And forms.py:

class MapNoteForm(forms.ModelForm):
    note = forms.CharField()

    class Meta:
        model = MapNote
        fields = ('note',)

Finally, the relevant section of the template:

  map.on('click', function (e) {
      var MapNote = L.popup();
      var content = '<form method="post"> {% csrf_token %} {{form}} <br> <button type="submit"> Save</button>'
      MapNote.setContent(content);
      MapNote.setLatLng(e.latlng); //calculated based on the e.layertype
      MapNote.openOn(map);
      })

I'm kind of looking to reverse the workings of the Django-view, trying to pass something from the template to Django, instead of vice versa. What would be the best approach here?

1 Answer 1

1

You can use the ajax form submission to submit the data to the form
Click here to see the document

Sign up to request clarification or add additional context in comments.

1 Comment

Interesting approach, will check if I can get it to work using AJAX.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.