views:

8

answers:

1

I have the following model

class Team(models.Model):
    name = models.CharField(max_length=100)
    members = models.ManyToManyField(User, related_name="members", blank=True, null=True)

And the following view

def team_details(request, team_id):
    # Look up the Team (and raise a 404 if it is not found)
    team =  get_object_or_404(Team, pk=team_id)

    # check to see if user is authenticated
    if request.user.is_authenticated():

        # check to see if the authenticated user is listed in members
        if team.members == request.user: # This condition always returns False
            return render_to_response('teams/team_detail.html', {'team': team},)
        else:
            # User is in members list, redirect to join team page
            return redirect('/join')
    else:
        # User isn't authenticated, redirect them to login page
        return redirect('/login')

The objective of this view is to list the details of a team only if the current authenticated user is a member of the team.

Firstly, is there a better way to do this?

Secondly, I've tried team.members == request.user but this did not work, it always returns False. What would be the correct syntax for the condition of this IF?

Any advice on how to achieve this would be greatly appreciated.

+2  A: 

team.members returns a Manager - ie something you then do queries on. So you can do team.members.get(user=request.user) and catch the User.DoesNotExist exception if the user isn't found.

It's always worth exploring this sort of thing in the Python shell - if you had imported Team and done a query to get an instance, you could have just typed team.members and seen what it returned, which would have told you why your initial try wouldn't have worked.

Daniel Roseman
Thanks Daniel - that's great advice. And yes, I should have tried this in the shell first. I keep forgetting the shell is really powerful.
Jamie Woods