我使用django-voting作为我的两个模型的投票应用程序。这两个模型都有“作者”字段。
如何在不修改django投票应用程序的情况下限制用户在将此特定用户设置为其作者的模型上投票?
我首先想到的是Django中间件,但我不理解它的"proces_view“功能。如果您认为中间件是正确的方式,请给出一个如何做到这一点的例子。
发布于 2009-06-16 17:08:14
将此代码添加到settings.py中的任何位置:
from voting.managers import VoteManager
def check_user(func):
def wrapper(self, obj, user, vote):
if obj.user != user:
return func(self, obj, user, vote)
else:
return None
# or raise some exception
return wrapper
VoteManager.record_vote = check_user(VoteManager.record_vote)我没有运行这段代码,也许它是不正确的,但我希望我的想法是清晰的
发布于 2009-06-16 14:53:01
为什么不通过另一个视图将请求重新路由到特定的URI,而不是中间件黑客?然后,您可以执行任何您喜欢的逻辑,然后在适当的情况下调用原始视图。
发布于 2009-06-19 14:46:56
另一个想法是使用post_save signal
如下所示:
from django.db.models.signals import post_save
from voting.models import Vote
def check_user(sender, instance, **kwargs):
if instance.user == instance.object.user:
instance.delete()
# do some other stuff to tell the user it didn't work
post_save.connect(check_user, sender=Vote)与覆盖VoteManager.record_vote相比,这样做的好处是它与投票模块的耦合不那么紧密,并且如果他们进行更改,就不太可能破坏您的代码
编辑用户:在格拉德的回答中,你需要确保你要投票的所有对象都有一个‘’属性。
https://stackoverflow.com/questions/1001856
复制相似问题