In my django app I am taking form input.Once that form is validated I am displaying a success message with help of Django Message Framework .
Current State
I am able to display a success message in the template after submission of form when I redirect it to same url(The url of the form itself)
My views.py
if form.is_valid():
form_data = form.save()
messages.success(request, 'Submited Successfully')
return redirect('form-url')
What I want
Once the form is submitted I want to display a success message on the same page( form-url
) and then I want to redirect to a new url list-of-submitted-forms
.
For that I did something like this to my views.py
if form.is_valid():
form_data = form.save()
messages.success(request, 'Submited Successfully')
return redirect('list-of-submitted-forms')
The problem I am facing
I am redirecting to a new url.But without getting success message on the form-url
page.Also again when I go to form-url
page(By clicking a button which redirects to that url) the message of 'Submited Successfully'
is shown
My HTML/JS
<script>
{% if messages %}
{% for message in messages %}
{% if message.tags == "success" %}
swal({text:"{{ message }}",icon: "success",timer: "4000",buttons: false})
{% endif %}
{% endfor %}
{% endif %}
I have faced the same issue, this is what I have done
Instead of redirect to another page from controller, firstly add the query parameters ?redirect='/newpage'. And redirect to the same previous page.
The from the JavaScript catch this query parameters and after few seconds delay run widow.location ='/newpage'
There are many ways to do what you want to do, I'm showing you a way to do it with a JsonResponse
.
views
from django.http import JsonRespon
from django.core.urlresolvers import reverse
if form.is_valid():
form_data = form.save()
response = {'msg':'Submited Successfully',
'url':reverse('list-of-submitted-forms'),
'created':True}
return JsonResponse(response)
js
$("#your_form").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:"URL",
type:'POST',
data:formData,
processData: false,
contentType: false,
success: function(data){
if(data.created){
alert(data.msg); // handle the message , till the user click ok, and redirect to data.url
window.location.href = data.url;
}
else{
$("your_form").html($("your_form",data));
}
},
error:function(){
alert("error");
}
});
return false;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.