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.
Add this code anywhere in your 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)
I didn't run this code, maybe it's incorrect, but I hope idea is clear
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.
Another idea is to use the 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)
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 code
edit: as in Glader's answer, you need to make sure that all the objects you're voting on have a 'user' attribute.