You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django项目中Sweetify(SweetAlert2)无法正常工作,求排查方案

问题描述

我已按照sweetify-django的官方文档完成配置,但Sweetify仍无法在我的Django项目中正常运行,求可行的解决思路。以下是我的相关代码实现:

1. home/views.py

from django.shortcuts import redirect
from django.views.generic import FormView
from attendance.models import Graduates
from home.forms import TicketForm
from django.utils import timezone
from django.urls import reverse
import sweetify

class HomeView(FormView):
    template_name = 'home/index.html'
    form_class = TicketForm

    def form_valid(self, form):
        getId = form.cleaned_data['nomor_ticket']      
        
        try:
            graduate = Graduates.objects.get(ticket_id=getId)
            message_success = 'Congratulations'

            graduate.attendance = timezone.now()
            graduate.status = True
            graduate.save()
            sweetify.success(self.request, message_success, text='Cool', persistent='Thanks', timer='3000')
            return redirect('attendance:index', graduate.ticket_id)

        except Graduates.DoesNotExist:
            print('ticket not found')
            return redirect('home:index')

2. templates/base.html

...
<body>
  {% block contents %}{% endblock contents %}
  <script src="https://unpkg.com/flowbite@1.5.3/dist/flowbite.js"></script>
  {% load sweetify %}
  {% sweetify %}
</body>
...

3. core/settings.py

INSTALLED_APPS = [
...
'sweetify'
...
]

SWEETIFY_SWEETALERT_LIBRARY = 'sweetalert2'
解决思路
  • 检查重定向后的模板继承关系:调用sweetify.success后直接重定向到attendance:index页面,只有当该页面模板**继承了包含{% sweetify %}标签的base.html**时,提示才会被渲染。如果目标页面未继承base.html,需在其模板中添加{% load sweetify %}和{% sweetify %}标签。
  • 修正timer参数类型:当前代码中timer='3000'是字符串类型,Sweetify要求该参数为数字,改为timer=3000即可,否则会导致前端JS解析错误。
  • 确认SweetAlert2资源引入:虽然已在settings指定使用sweetalert2,部分版本的sweetify-django需要手动引入资源,可在base.html的{% sweetify %}标签前添加:
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
  • 检查Session功能是否正常:Sweetify通过Django Session存储提示消息,若项目Session配置异常(如SESSION_ENGINE未正确设置),消息无法传递到下一个请求。可在重定向后的视图中打印request.session,查看是否包含sweetify相关键值对。
  • 简化try-except逻辑:Graduates.objects.get()找不到对象时会直接抛出DoesNotExist异常,代码中if graduate:的判断冗余,可直接删除,避免不必要的逻辑分支。

内容的提问来源于stack exchange,提问作者Uletin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 01:10:27