Reputation: 862
views
I have a checkbox to check the users in order to add them in a group.Here If the checked user is already in the group then it fails now with this code but I want proceed(if checked users are already in) and add the remaining user to the group and leave the already added user as it is.
It throws this error if the checked users are in the group already
UNIQUE constraint failed: user_registration_user_groups.user_id, user_registration_user_groups.group_id
def assign_users_to_group(request, pk):
group = get_object_or_404(Group, pk=pk)
if request.method == 'POST':
users = request.POST.getlist('users')
for user in users:
if user in group.user_set.all():
pass
group.user_set.add(user)
messages.success(request, 'users added to this group')
return redirect('user_groups:view_group_detail', group.pk)
UPDATE with Nafees Anwar answer
def assign_users_to_group(request, pk):
group = get_object_or_404(Group, pk=pk)
if request.method == 'POST':
users = request.POST.getlist('users')
for user in users:
try:
group.user_set.add(user)
except IntegrityError as e:
if user not in group.user_set.all():
raise e
messages.success(request, '{} user added to this group')
return redirect('user_groups:view_group_detail', group.pk)
Upvotes: 0
Views: 68
Reputation: 2018
def assign_users_to_group(request, pk):
group = get_object_or_404(Group, pk=pk)
if request.method == 'POST':
users = request.POST.getlist('users')
for user in users:
if not user.groups.filter(name=group.name).exists():
group.user_set.add(user)
messages.success(request, 'users added to this group')
return redirect('user_groups:view_group_detail', group.pk)
Upvotes: 3
Reputation: 6608
You can just ignore if it raises error and user exists.
from django.db.utils import IntegrityError
try:
group.user_set.add(user)
except IntegrityError as e:
if user not in group.user_set.all():
raise e
Upvotes: 0