django display message after POST form submit

我的未来我决定 提交于 2019-12-02 20:42:58
damio

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

In your view:

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 %}

Django messages framework stores the messages in the session or cookie (it depends on the storage backend).

You don't need to do a redirect to clear the form data. All you need to do is re-instantiate 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're going to initiate a GET request, and success will be False. Either way, the form will be unbound on a GET, or on a successful POST.

If you leverage the messages framework, you'll still need to add a conditional in the template to display the messages if they exist or not.

Asif
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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!