Django post post form submission

I have a page with a POST form that has an action set for some url.
Suppose this page URL is /form_url/ : ..

The view in /submit_url/ takes care of the form data. After that, I want to return the same form page with a successful message. In a view that takes over the POST form, I use HttpResponseRedirect to "clear" the form data from the browser. But in this way, I cannot display the message on the form page unless I do something like:

 return HttpResponseRedirect("/form_url/?success=1") 

and then check this option in the template. I don’t like this, because if the user refreshes the page, he will still see a success message.

I noticed that in the django admin site, deleting / adding objects uses a redirect after sending a POST and still displays a success message. How?

I have already briefly seen the django messaging application, but I want to know how it works in the first place.

+11
post django forms message
source share
5 answers

The django django.contrib.messages uses django.contrib.messages , you use it like this:

In your opinion:

 from django.contrib import messages def my_view(request): ... if form.is_valid(): .... messages.success(request, 'Form submission successful') 

And in your templates:

 {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} 
+14
source share

Django's message structure stores messages in a session or cookie (this depends on the storage backend ).

+5
source share

You do not need to redirect to clear form data. All you have to do is re-create the form:

 def your_view(request): form = YourForm(request.POST or None) success = False if request.method == 'POST': if form.is_valid(): form.save() form = YourForm() success = True return render(request, 'your_template.html', {'form': form}) 

If the user refreshes the page, they will initiate a GET request, and success will be False . In either case, the form will be unbound in the GET or in the successful POST.

If you use the message structure , you still need to add a conditional expression to the template to display messages if they exist or not.

+2
source share
 from django.contrib.messages.views import SuccessMessageMixin from django.views.generic.edit import CreateView from myapp.models import Author class AuthorCreate(SuccessMessageMixin, CreateView): model = Author success_url = '/success/' success_message = "%(name)s was created successfully" 

https://docs.djangoproject.com/en/1.11/ref/contrib/messages/

+1
source share

messages.success (request, your account has been created! Now you can log in)

0
source share

All Articles