Search code examples
djangotoast

Toast with Django CreateView message How to show


I'm new in Django and I'm creating a CRUD. However I want to show a Success message in a Toast for successfully submit, but I don't know how to do it exactly. The view class once is inserted, redirect correctly to List, but no messages showed. This is my view class

class AlmacenesCreateView(SuccessMessageMixin, CreateView):
    model = Almacen
    form_class = AlmacenesForm
    template_name = 'pages/create.html'  
    success_url = reverse_lazy('almacenes')
    success_message = "Bien!!!!"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = "New Almacen"   
        return context

And this is the script for the toast

  $(function () {
    let mensaje ="{{ messages.0 }}";
    const Toast = Swal.mixin({
      toast: true,
      position: 'top-end',
      showConfirmButton: false,
      timer: 3000
    });
    if (mensaje != "") {
      Toast.fire({
            icon: 'success',
            title: mensaje,
          })
    }
});

My doubt is how I can show the success message


Solution

  • You have to loop over messages and then print icon accordingly

    {% for message in messages %}
        <script>
            $(function () {
                let mensaje ="{{ message }}";
                const Toast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000
                });
                if (mensaje != "") {
                    Toast.fire({
                        icon: "{% if message.tags %}{{ message.tags }}{% endif %}",
                        title: mensaje,
                    })
                }
            });
        </script>
    {% endfor %}
    

    You can even consider using things like this

    Swal.fire({
            title: "Thank you?",
            text: "success message here",
            type: "success",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            closeOnConfirm: false
        }, function() {
            swal("Successful!", "success message here", "success");
        });
    });