Answers for "django user group"

3

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
Posted by: Guest on October-13-2020
1

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)
Posted by: Guest on May-03-2020
5

user login validation django

from django.contrib.auth import authenticate, login

def my_view(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(request, username=username, password=password)
    if user is not None:
        login(request, user)
        # Redirect to a success page.
        ...
    else:
        # Return an 'invalid login' error message.
        ...
Posted by: Guest on June-12-2020
0

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)
Posted by: Guest on January-28-2021

Python Answers by Framework

Browse Popular Code Answers by Language