Search code examples
django-templatesdjango-viewsdjango-usersdjango-permissions

Add users to a group by emails through a view (allow comma separation for mulitple)


I would like to be able to add users in Django to a user-created group through a view and a template form. Creating the groups is easy, I just am having trouble creating a way to add bulk users (like this email1@email.com, email2@email.com, email203920492@email.com etc) to the group. If the user exists in the system, they are sent a message to join, if they don't exist, they get a message inviting them to join the website and the group.


Solution

  • If I understand what you're asking...

    If you have a list of the emails, then simply loop through the list of emails and get the user assigned to each email:

    for email in emails:
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            # A user doesn't exist with that email address, so send the invitation email
    
        # The user exists, so send them an email with a link to a view that lets them join    the group
    

    In your view, you would add the current logged in user to the group when they visit the link, with something like:

    request.user.groups.add(group)