django user group code example
Example 1: django user group check
from django.contrib.auth.models import User, Group
group = Group(name="Author")
group.save()
user = User.objects.get(username="Johndoe")
user.groups.add(group)
if user.groups.filter(name=group):
else:
Example 2: 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)
...
else:
...
Example 3: 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 4: 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)
Example 5: import login required
from django.contrib.auth.decorators import login_required