Registro de usuario en Django Rest Framework

Mi solución de registro de usuarios a través de una API rest. No he encontrado ejemplos completos en ninguna parte, y este código bien pudiera no ser óptimo.
[code language=»python»]
#serializers.py
class UserViewSet(viewsets.ModelViewSet):
"""
A viewset that provides the standard actions
"""
queryset = User.objects.all()
serializer_class = UserSerializer
permission_classes = (AllowAny, )

def create(self, request, *args, **kwargs):
"""
http POST 127.0.0.1:8000/users/ By default asks for permission.
:param request:
:return:
"""
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
user = serializer.create(validated_data=request.data)
#serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
[/code]

[code language=»python»]
#views.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
"""
Returns all the Avatars id related to one user. Must set the related_name from the many part.
"""
avatars = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
model = User
fields = (‘id’, ‘email’, ‘avatars’, ‘account_type’, ‘password’, ‘username’)

def create(self, validated_data):
"""
We’ve to override the create serializer method in order to call to our custom create_user
http://www.django-rest-framework.org/api-guide/serializers/#saving-instances
:param validated_data: Incoming POST data
:return: A created user instance
"""
account_type = AccountType.objects.get(pk=validated_data[‘account_type’])
email = validated_data[‘email’]
password = validated_data[‘password’]
username = validated_data[‘email’]
return User.objects.create_user(username=username, account_type=account_type, email=email, password=password) # Alternative: User.objects.create(**validated_data)
[/code]

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.