django user groups code example

Example 1: django user group check

from django.contrib.auth.models import User, Group

group = Group(name="Author")
group.save() # Create a sample group.
user = User.objects.get(username="Johndoe") # get Some User.
user.groups.add(group) # Add User 'Johndoe' to a Group.

# check if user belongs to certain group.
if user.groups.filter(name=group):
  # do your stuff and give user access.
else:
  # redirect him

Example 2: django admin password reset

python manage.py changepassword <user_name>

Example 3: how to logout in django

from django.contrib.auth import logout

def logout_view(request):
    logout(request)
    # Redirect to a success page.

Example 4: django add user to group

from django.contrib.auth.models import Group, User
 
g = Group.objects.get(name='My Group Name')
users = User.objects.all()
for u in users:
    g.user_set.add(u)

Example 5: how to get user id django

if request.user.is_authenticated:
    # Do something for authenticated users.
else:
    # Do something for anonymous users.

Example 6: django add user to group

from django.contrib.auth.models import Group, User
tonystark=User.objects.get(id=pk)
hulk=Group.objects.get(name='groupname')
hulk.user_set.add(tonystark)