通过引发异常将用户从您的视图中弹出
django-tigger的Python项目详细描述
通过引发异常将用户从您的视图中弹出
简介
您可能已经习惯了这种工作流程:
fromdjango.httpimportHttp404fromdjango.views.genericimportTemplateViewclassMyView(TemplateView):defget_context(self,**kwargs):# do some stuffraiseHttp404
…但是如果你不只是用404轰炸机,不是很好吗? 是否可以将用户跳出到重定向并附加友好消息?那是 江哥跳虎干什么!
fromdjango.core.urlresolversimportreversefromdjango.views.genericimportTemplateViewfromtigger.exceptionsimportBounceclassMyView(TemplateView):defget_context(self,**kwargs):# do some stuffraiseBounce(reverse("some-url"),message="The wonderful thing about tiggers...",level="SUCCESS")
上面的代码将把用户跳转到some-url解析为和的任何内容 使用django消息传递框架在屏幕上转储消息。
安装
- 使用pip:pip install django-tigger。
- 将django_tigger.middleware.BouncingMiddleware添加到MIDDLEWARE 在你的django设置中列出。注意,您不需要将此添加到 INSTALLED_APPS因为此包没有任何模型、迁移或 任何需要的东西。
使用
基本上,只要你想摆脱目前的程序 相反,重定向用户,调用Bounce()并传入几个参数:
- url:唯一需要的参数是,在这里您将跳转您的用户 到。
- message:如果提供,这将向用户的会话附加一条消息 使用django消息传递框架
- level:消息的级别。必须是DEBUG,INFO之一, SUCCESS,WARNING,ERROR。默认值是INFO。
支架
我已经在Python3和Django1.11中使用过这个,但是我看不出它为什么不 在Python2.7和Django1.10中工作。比那还老,你会有 麻烦。比那还新,你应该没事的。
这不是特别复杂的代码;-)
树脂
The wonderful thing about tiggers Is tiggers are wonderful things Their tops are made out of rubber Their bottoms are made out of springs They're bouncy, trouncy, flouncy, pouncy fun, fun, fun, fun, fun But the most wonderful thing about tiggers is I'm the only one I'm the only one. -- Winnie the Pooh and Tigger Too!, 1974