Home > Back-end >  in Django, I use sweetalert2
in Django, I use sweetalert2

Time:11-10

I have used sweetalert2 to pop up messages, it works great when page return render but when I

used return redirect not works there is something I need to add it.

any helps Thanks

I want a sweetalert2 to pop up when the user submit forms

in Django views

        messages.success(request, 'yes')
        return render(request, 'app/home.html')

Not pop up

       messages.success(request, 'yes')
       return redirect('app:home')

in html page

  {% for message in messages %}
  <script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  {% if message.tags == 'success' %}
  <script>
  Swal.fire(
  'good',
  '{{message}}',
  'success'
  )
  </script>
  {% endif %}
 {% endfor %}

CodePudding user response:

Try this package....

Install this package it provides sweetalert2 functionality with Django

pip install sweetify

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    'sweetify',
]

Html Code (base.py)

{% load static %}

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        {% block title %}
                                      
        {% endblock title %}
    </title>
</head>
<body>
  
  {% block body %}
   
  {% endblock body %}
  <script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/11.6.5/sweetalert2.all.min.js"></script>
  

</body>
</html>


{% load sweetify %}
{% sweetify %}

view.py

import sweetify
def HomeView(request):
    if request.method == 'POST':
      no = request.POST.get('demono')
      Demo(name=no).save()
      sweetify.success(request, 'Cheers to new toast')
      return redirect('/')
    
    context = {
      'h':'Hello world with django',
      
    }
    return render(request,'index.html',context)

Output

enter image description here

  • Related