Suppose I want to register a user (I\'m using the User model located in django.contrib.auth.models). Assume this is my serializers.py:
class UserSerializer(s
Neither of those is perfect. But View A looks promising.
User creation is not simply User.save, but rather you have to call User.create_user method.User.create_user, however, the views contains a logic which should actually be abstracted within the Serializer.save() method.To solve this, you have to change the behavior of Serializer.save() method. Looking at the documentation, Serializer.save(), will call either Serializer.create() or Serializer.update().
In summary, we have to override the Serializer.create() for user creation and use View A.
# File: serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
def create(self, validated_data):
user = User.objects.create_user(
email = validated_data['email'],
username = validated_data['username'],
password = validated_data['password'],
)
return user