首页 > 解决方案 > 在 Django 中提交表单后显示 javascript 样式警报

问题描述

我正在 Django 中创建一个简单的应用程序。我在页面上有一个表单,提交表单后,我想将用户重定向到一个新页面并显示这样的 JavaScript 警报。我该怎么做呢?我的代码在下面。


这是存储表单数据并重定向到新页面的功能,新页面上只有简单的html。

def donate(request):
    if request.method == "POST":
        title = request.POST['donationtitle']
        phonenumber = request.POST['phonenumber']
        category = request.POST['category']
        quantity = request.POST['quantity']
        location = request.POST['location']
        description = request.POST['description']
        # New part. Update donor's stats.
        UserDetail.objects.filter(user=request.user).update(donations=F('donations') + 1)
        UserDetail.objects.filter(user=request.user).update(points=F('points') + (quantity * 2))
        return render(request, 'dashboard.html', )
    return render(request,'donate.html') 

我做了很多研究,但我找不到解决问题的合乎逻辑的方法。过去的问题要求我使用 Django 消息,这是我不想使用的。感谢所有提供帮助的人!

标签: javascriptdjango

解决方案


在您的模板中,dashboard.html它似乎是,确保您加载 jquery,然后这将显示一个警报;

向您的页面添加一些上下文以告知模板已提交表单;

return render(request, 'dashboard.html', {'form_submitted': True})

然后您可以检查表单是否已提交

{% if form_submitted %}
<script>
  $(document).ready(function(){
    alert('Donor stats updated!');
  });
</script>
{% endif %}

就个人而言,我会用 djagno 的消息来做这件事——更好的用户体验


推荐阅读