Django. Restrict each user to only vote once -
i have situation , happy either 1 of 2 solutions, depending on more feasible/possible. have page displays event. event's name may not correct, , users have option suggest corrections. corrections stored in own table foreign key relationship event. once suggestion has been made, users can vote or down on suggestion. need restrict each logged in user's maximum vote 1. don't have slightest idea how this.
my ideal solution: there many 5 suggestions displayed. each logged in user can vote on each of these 5 suggestions. once on each.
my less ideal, still acceptable solution: there many 5 suggestions displayed. logged in user allowed vote or down on 1 of 5 suggestions.
i'm not sure more practical. i'll provide models event , suggested name. please let me know if there's else need see. in advance!
class event(models.model): def __unicode__(self): return unicode(self.id) id = models.bigintegerfield(blank = 'true', primary_key='true') version = models.integerfield(default = 0) views = models.integerfield(default = 0) created = models.datetimefield(editable = false) modified = models.datetimefield() trained = models.booleanfield(default = false) type = models.smallintegerfield(default = 0) def save(self, *args, **kwargs): if not self.id: self.created = datetime.datetime.today() self.modified = datetime.datetime.today() super(event, self).save(*args, **kwargs) class suggestedname(models.model): def __unicode__(self): return unicode(self.name) name = models.charfield(max_length=200, blank = 'true', null = 'true') votes = models.integerfield(default = 0) event = models.foreignkey(event)
class vote(models.model): class meta: unique_together = (('userprofile','suggestedname'),) userprofile = models.foreignkey(userprofile) suggestedname = models.foreignkey(suggestedname) event = models.foreignkey(event)
as comments suggest, should have model user
(which, in example, i'm assuming have).
what can model? need do!
suppose have view allows user vote. you'd want override post()
(or is_valid()
, depends) method check if user can vote or not:
def post(self, request, *args, **kwargs): # - retrieve user_profile # - retrieve suggestedname voted # - query votes see if combination of user_profile + suggestedname exists vote, created = vote.objects.get_or_create( userprofile=userprofile, suggestedname=suggestedname, event=event ) # get_or_create return tuple # created true if method created vote # false if there vote user , name # want use value 'created' # decide wether vote valid or not if not created: return httpresponse('you voted this, cheater') else: return httpresponse('awesome, voting!')
furthermore, if want allow 1 vote per user, pass get_or_created
retrieved user value.
hope these guidelines out bit :)
Comments
Post a Comment