3/12/2016 - 11:17 AM

Custom user implementation in Django with Django Rest Framework

Custom user implementation in Django with Django Rest Framework


AUTH_USER_MODEL = 'accounts.User'
from django.contrib.auth.models import Group
from rest_framework import serializers
from hello.models import User

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        print "UserSerializer"
        model = User
        fields = ('id','password', 'email','is_active')
        write_only_fields = ('password',)
        read_only_fields = ('id','is_active')
    def create(self, validated_data):
        print "create user"
        user = User.objects.create(


        return user

class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ('url', 'name')

from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager

class CustomUserManager(BaseUserManager):

    def _create_user(self, email, password,is_superuser, **extra_fields):
        Creates and saves a User with the given email and password.
        now = timezone.now()
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email,
                          is_staff=is_staff, is_active=True,
                          is_superuser=is_superuser, last_login=now,
                          date_joined=now, **extra_fields)
        return user

    def create_user(self, email, password=None, **extra_fields):
        return self._create_user(email, password, False, False,

    def create_superuser(self, email, password, **extra_fields):
        return self._create_user(email, password, True, True,

# Create your models here.
class User(AbstractBaseUser):
        email = models.EmailField(('email address'), max_length=254, unique=True)
        is_active = models.BooleanField(('active'), default=True,
        help_text=('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
        USERNAME_FIELD = 'email'
        REQUIRED_FIELDS = []

        objects = CustomUserManager()