Reputation: 37
I'm new to django and made a simple app the would let the users to make six picks of a list of names to vote for the top six. The problem that I'm having is that any user when logged in they can see everyone else's votes! How can I have the logged user(no the admin) to only see their votes and not everyone's? I have been reading on here and it looks like it can be done with querysets? but want' able to get the idea deployed.
I have two classes in my model.py:
class CandidateName(models.Model):
canidate_name = models.CharField(max_length=15)
def __str__(self):
return self.canidate_name;
class Vote(models.Model):
first_pick = models.ForeignKey(CandidateName, related_name= 'first')
second_pick = models.ForeignKey(CandidateName, related_name='second')
third_pick = models.ForeignKey(CandidateName, related_name='third')
fourth_pick = models.ForeignKey(CandidateName, related_name='fourth')
fifith_pick = models.ForeignKey(CandidateName, related_name='fifth')
sixth_pick = models.ForeignKey(CandidateName, related_name='sixth')
Upvotes: 1
Views: 2098
Reputation: 167
You can do something like adding a User field to your Vote class.
from django.contrib.auth.models import User
class Vote(models.Model):
user = models.ForeignKey(User)
first_pick = models.ForeignKey(CandidateName, related_name= 'first')
second_pick = models.ForeignKey(CandidateName, related_name='second')
third_pick = models.ForeignKey(CandidateName, related_name='third')
fourth_pick = models.ForeignKey(CandidateName, related_name='fourth')
fifith_pick = models.ForeignKey(CandidateName, related_name='fifth')
sixth_pick = models.ForeignKey(CandidateName, related_name='sixth')
Then in your views.py retrieve the Votes associated with the currently logged in user and pass those to your template.
if request.user.is_authenticated():
votes_by_user = Vote.objects.filter(user=request.user)
Upvotes: 6