简体   繁体   中英

How to authenticate if a user “owns” a model instance

I have the following models:

class UserProfile(models.Model):
    user = models.OneToOneField(User)

class Site(models.Model):
    user = models.ForeignKey(User)
    site_name = models.CharField(max_length=128, blank=False, null=False)

class Team(models.Model):
    site = models.ForeignKey(Site)
    team_member_name = models.CharField(default='name', max_length=128, blank=False, null=False)

I have a view that passes a team_member id via the URL:

Urls.py:

url(r'^team/(?P<team_member_id>\d+)/$', 'team.views.home', name='team_view_team_member')

Views.py:

@login_required
def home(request, team_member_id=None):
    team_member = Team.objects.get(id=team_member_id)

Note that there are many Team instances (ie lots of team members) which have the same Site_id .

How can I test if the request.user has the same site_id as any team_member returned? Is there a simple way to repeat this if I want to use it across multiple views?

Try this:

team_member = Team.objects.get(id=team_member_id)
if team_member.site.id == request.user.site_set.all().first().id:
   print "same site"
else:
   print "different site"

Hope this helps.

# Site for user in request
req_user_site = Site.objects.get(user=request.user)  # Use filter if it will return more than one object

# Site for team member in url
sites = Site.objects.filter(team__pk=team_member_id)

# Then compare
if req_user_site in sites:
    print "have the same"
else:
    print "don't"

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