django get user model code example

Example 1: django import user

from django.contrib.auth.models import User

Example 2: django user fields

# Django User Model Fields
username
first_name
last_name
email
password
groups
user_permissions
is_staff
is_active
is_superuser
last_login
date_joined

Example 3: how to get user id django

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

Example 4: import abstractuser

from django.contrib.auth.models import AbstractUser

Example 5: django authenticate with email

from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend

class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            return None
        else:
            if user.check_password(password):
                return user
        return None

Example 6: how to get user id django

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