I've a use-case where I'd to create a custom user model. I'm facing issues when I try to update the email/username fields. Not sure if I'm following the best practices to do the same though, as I'm pretty new to django.
Attached is the code FYI:
Models.py:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, UserManager
class CustomUserManager(UserManager):
def get_by_natural_key(self, username):
case_insensitive_username_field = '{}__iexact'.format(self.model.USERNAME_FIELD)
return self.get(**{case_insensitive_username_field: username})
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
username = models.CharField(max_length=50, unique=True)
name = models.CharField(max_length=100)
password = models.CharField(max_length=100)
is_active = models.BooleanField(default=True)
USERNAME_FIELD = 'username'
EMAIL_FIELD = 'email'
objects = CustomUserManager()
def clean(self):
super().clean()
self.email = self.__class__.objects.normalize_email(self.email)
self.username = self.username.lower()
def save(self, *args, **kwargs):
if self.password:
self.set_password(self.password)
super().save(*args, **kwargs)
from django.contrib.auth import get_user_model
from rest_framework import serializers
User = get_user_model()
class UserRegisterSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['email', 'username', 'name', 'password']
extra_kwargs = {
'password':{'write_only':True,
'style':{'input_type':'password'}
}
}
def update(self, instance, validated_data):
print("Update logic here")
return instance