如何限制用户对自己的模型进行投票
我正在使用 django-voting 作为我的两个模型的投票应用程序。 这两个模型都有“作者”字段。
如何在不修改 django-voting 应用程序的情况下限制用户对将此特定用户设置为作者的模型进行投票?
我首先想到的是 Django 中间件,但我不明白它的“proces_view”函数。 如果您认为中间件是正确的方法,请举例说明如何做到这一点。
I am using django-voting as a voting application for two of my models. Those both models have fields "author".
How can I restrict a user from voting on a model that has this particular user set as it's author without modifying django-voting app?
Django middleware is the first thing that comes to my mind, but I don't understand it's "proces_view" function. If you think middleware is the right way could you please give an example of how to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 settings.py 中的任何位置添加此代码:
我没有运行此代码,也许它不正确,但我希望想法很清楚
Add this code anywhere in your settings.py:
I didn't run this code, maybe it's incorrect, but I hope idea is clear
为什么不通过另一个视图将请求重新路由到该特定 URI,而不是中间件黑客呢? 然后您可以执行您喜欢的任何逻辑,并随后在适当的情况下调用原始视图。
Rather than a middleware hack, why not reroute requests to that particular URI through another view? Then you can performs whatever logic you like, and subsequently call the original view if appropriate.
另一个想法是使用 post_save 信号,
如下所示:这样
做的好处与重写
VoteManager.record_vote
相比,它与投票模块的耦合不太紧密,如果他们进行更改,则不太可能破坏您的代码编辑:如 Glader 的回答所示,您需要确保您投票的所有对象都具有“用户”属性。
Another idea is to use the post_save signal
like so:
The benefit of doing this vs overriding
VoteManager.record_vote
is that it's less tightly coupled to the voting module, and if they make changes it's less likely to break your codeedit: as in Glader's answer, you need to make sure that all the objects you're voting on have a 'user' attribute.