Issue
I'm building a web app where user can create markers on a leaflet map. Marker's details are saved in a backend with Django. My goal is to redirect the user to a detail page to fill marker's detail after clicking on the map. Here the js code to redirect to url create with an Ajax post.It's run when user click on the leaflet map.
map.on("click", function (e) {
window.location.href = {% url 'create' %};
$.ajax({
url: {% url 'create' %},
data: { markers: markers_dict},
type: "POST"
}).done(function (response) {
console.log(response);
});
}
but I'm struggling in the views.py because this redirect and AJAX post create two request one GET and another POST:
def create_marker(request):
if request.method == "POST":
r = request.POST.get("markers")
print(r)
return JsonResponse({"response":"succeed"})
else:
return JsonResponse({"response":"failed"})
and the urls.py :
url_patterns = [
path("create/",views.create_marker,name="create"),
]
It always returns the failed response even if it prints r
in the console. How can I send these frontend data to the create url while redirect to this url and create a django from with these data ?
Solution
You are exiting the current page before making the ajax call. Move the redirection into ajax call’s done block. Something like this:
map.on("click", function (e) {
$.ajax({
url: {% url 'create' %},
data: { markers: markers_dict},
type: "POST"
}).done(function (response) {
window.location.href = “{% url 'create' %}/” + response.id;
});
}
You will need one more url in your urls.py for editing the marker object in backend. Try the CBV DetailView.
So first you post to this view with your map data. Once successful, redirect the user to the edit view of the created data.
- User clicks on map You create the minimal object in backend
- You get the ID of the created object on success
- Redirect the user to the form/edit view of that object
- User fills out the remaining items
- User clicks on save
Answered By - Amrit Bera
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.