Skip to main content
 首页 » 编程设计

python之如何从 HttpResponseRedirect django 发送警报消息

2024年11月01日32Terrylee

我在 Bootstrap 模式中有一个表单。 当用户提交此表单时,它会向 url(/submitform) 发送一个发布请求, /submitform 的 View 对数据做了一些事情(重新排列) 并对另一个网址执行“requests.post”。 现在取决于第二个帖子请求的成功或失败。我想在 HttpResponseRedirect url 上显示警报。

代码如下:

payload= {"createRequest": 
                  { "users": request.POST["newuser"], 
                    "email": request.POST["newemail"] 
                    } 
                  } 
headers =  {'content-type' : 'application/json'} 
r = requests.post('http://localhost:8000/api/v1.0/newuser', 
                          data=json.dumps(payload), 
                          headers=headers, verify=False) 
 
return HttpResponseRedirect("/dashboard/all_users", {"alert":r.content}) 

并且在 all_users 的 View 中,它检查警报是否存在(因为 all_users 已从警报不属于它的其他几个地方调用),如果警报存在,它将它从其 render_to_respons 发送到 html。

我无法更改 all_users url 格式,它已在很多地方使用。 如果需要更多说明,请告诉我。

我尝试过的事情:

return HttpResponseRedirect(reverse("/dashboard/all_users"), kwargs={"alert":r.content}) 

错误:

Reverse for '/dashboard/all_users' with arguments '()' and keyword arguments '{}' not found.

请您参考如下方法:

在您的模板中,您可以:

<script type="text/javascript"> 
 $(function(){ 
   {% if alert %} 
      //whatever conditions and js code 
      alert('{{alert}}'); 
   {% endif %} 
 }); 
</script> 

在 View 中,使用 redirect而不是 HttpResponseRedirect

return redirect(reverse("/dashboard/all_users"), {"alert":r.content})