django userid code example

Example 1: django request user

def my_view(request):
    if not request.user.is_authenticated:
        return render(request, 'myapp/login_error.html')

Example 2: how to get user id django

def sample_view(request):
    current_user = request.user
    print current_user.id

Example 3: how to set default user group in django

from django.contrib.auth.models import User, Group
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        instance.groups.add(Group.objects.get(name='group_name'))

Example 4: how to get user id django

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