一个加入Group(小组)的逻辑问题


在尝试做一个加入Group(小组)的功能,其中想加一个逻辑——如果发现登录后的用户已经是该小组成员,那么就不再新增membership。

用一下try的方法尝试方法,但没有起作用,求帮忙看看哪里有问题?

join function

@login_required()
def join(request, group_id):

'''
When a registered user click join button ,
he would be added in the group as a member,
and his member card will show up in this group
'''
g = get_object_or_404(Group, pk=group_id)
u = request.user

Try to get the user membership of this group

try:
user_membership = g.membership_set.get(user=u)

except:
default_nickname = u.username
new_member = Membership(user=u, nickname=default_nickname, groups=g)
new_member.save()
p = Profile.objects.get(user=request.user)
p.membership.add(new_member)
p.save()
return HttpResponseRedirect(reverse('groups:memberships:detail', args=(g.id, new_member.id)))

else:
return render(request, 'groups/detail.html')

django

恢复正常了吗 9 years, 10 months ago

Your Answer