开发者

How to return a objects details only when a condition is met (request.user is listed in a linked M2M field)

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},)
        开发者_JAVA百科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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜