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)
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 %}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With