简体   繁体   中英

Django How to only show user's own posts when logged in?

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')

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM