Home > Mobile >  Toast with Django CreateView message How to show
Toast with Django CreateView message How to show

Time:08-31

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

CodePudding user response:

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");
    });
});

CodePudding user response:

Did you follow the documentation here and there :

In your template, use something like:

{% if messages %}
<ul >
    {% for message in messages %}
    <li{% if message.tags %} {% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

Then you can check in your console if you don't have any Javascript errors for your code. I've never used Swal library.

  • Related