0

As of now, I am storing username, password in User object which I import from "django.contrib.auth.models".

Now, I am also sending 'role' attribute in POST request and it should add 'role' in User as well. I have seen multiple posts, but not able to understand role part. Some posts says, use some Groups, not clear how to use them. I just have to store role attribute in User of django.contrib.auth.models. POST body will be something like this:

{"username":"name22","password":"$pwd1234","password2":"$pwd1234", "role": "Customer" }

Using below code:

serializers.py:

from rest_framework import serializers
from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password

class RegisterSerializer(serializers.ModelSerializer):

username = serializers.CharField(required=True)
password = serializers.CharField(write_only=True, required=True, validators=[validate_password])
password2 = serializers.CharField(write_only=True, required=True)
role_name= serializers.CharField(required=True)


class Meta:
    model = User
    fields = ('username', 'password', 'password2', 'role_name')
    

def validate(self, attrs):
    if attrs['password'] != attrs['password2']:
        raise serializers.ValidationError({"password": "Password fields didn't match."})
        

    return attrs
    
def validate_username(self, value):
    if User.objects.filter(username__iexact=value).exists():
        raise serializers.ValidationError("A user with this username already exists.")
    return value

def create(self, validated_data):
    user = User.objects.create(
        username=validated_data['username']
    )
    role = Role(user=user, role_name='role_name') 
    role.save()

    
    user.set_password(validated_data['password'])
    user.save()

    return user

models.py:

from django.db import models
from django.contrib.auth.models import User


class Role(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    role_name = models.CharField(max_length=50)

    def __str__(self):
        return self.role_name

When I send "role" = "Customer" in POST request, it creates User object and in response Json, returns:

{
    "username": "name27",
}

Why it is not returning "role": "Customer" as well?

0 Answers0