Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a success message with get_success_url() in Django FormView

I've got FormView that redirect to a previous page if the form was valid. That's works fine but how can I tell a user that the information has been posted? I want him to see a success message in a modal window after redirect.

I've tried to do it through request.session in get_success_url but it doesn't fit to my goals because a user can submit the form multiple times. So how can I return any message with redirect in get_success_url in FormView?

My FormView

class CatPhotoUploadFormView(FormView):
    template_name = 'blank.html'
    form_class = CatPhotoForm

    def get_success_url(self):
        self.request.session['success_message'] = 'Everything is fine'
        return reverse('cat:detail_cat', args=(self.kwargs['pk'],))

    def form_valid(self, form):
        cat = Cat.objects.filter(id__exact=self.kwargs['pk'])
        for each in form.cleaned_data['attachments']:
            print('****', each, '****', type(each))
            Photo.objects.create(photo_path=each, photo_author=self.request.user, photo_cat = cat[0])
        return super(CatPhotoUploadFormView, self).form_valid(form)
like image 597
mailman_73 Avatar asked Dec 10 '22 16:12

mailman_73


2 Answers

Use Django messaging framework for this purpose, change get_success_url with message.

from django.contrib import messages
def get_success_url(self):
    messages.add_message(self.request, messages.INFO, 'form submission success')
    return reverse('cat:detail_cat', args=(self.kwargs['pk'],))

In your template, something like this ( NOTE: remember to pass messages )

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}
like image 127
Renjith Thankachan Avatar answered Dec 28 '22 07:12

Renjith Thankachan


In fact Django has a ready to use mixin, SuccessMessageMixin, which can be use in class based views to achieve the same purpose.

Like so:

from django.contrib.messages.views import SuccessMessageMixin

class CatPhotoUploadFormView(SuccessMessageMixin, FormView):
    template_name = 'blank.html'
    form_class = CatPhotoForm
    success_message = 'Everything is fine'
    ...

Very clean and straightforward.

like image 20
Erick M Avatar answered Dec 28 '22 06:12

Erick M