UserViewSet Django User – Ejemplo completo

http GET 127.0.0.1:8000/users/ ‘Authorization: Token e9e95a81da6f5c3e37ed63ef3c2eb75d0ae1a694’

[code language=»python»]
# serializers.py
class UserSerializer(serializers.ModelSerializer):

""" 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)
class Meta:
model = User
fields = (‘id’, ‘email’, ‘avatars’, ‘account_type’, )

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
"""
user = User.objects.create_user(
email = validated_data[‘email’],
username = validated_data[‘username’],
password = validated_data[‘password’],
)
return user
[/code]

Antes

[code language=»python»]
# urls.py
urlpatterns = [
url(r’^users/$’, views.UserList.as_view()),
url(r’^user/(?P<pk>[0-9]+)/$’, views.UserDetail.as_view()),
]

[code language="python"]
# views.py
class UserList(generics.ListAPIView):
""" Returns a list with all the users data. """
queryset = User.objects.all()
serializer_class = UserSerializer

class UserDetail(generics.RetrieveAPIView):
""" If exists, returns a list with the data of the selected user."""
queryset = User.objects.all()
serializer_class = UserSerializer
[/code]

Deespués

[code language=»python»]
router = DefaultRouter()
router.register(r’users’, UserViewSet, ‘User’)

# Enlazamos con las urls tradicionales
urlpatterns += router.urls
[/code]

[code language=»python»]
class UserViewSet(viewsets.ViewSet):
"""
A simple ViewSet for listing or retrieving users.
"""
# queryset = User.objects.all()
# @detail_route(methods=[‘post’], permission_classes=[AllowAny], url_name=’list’)
def list(self, request):
queryset = User.objects.all()
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)

def retrieve(self, request, pk=None):
queryset = User.objects.all()
user = get_object_or_404(queryset, pk=pk)
serializer = UserSerializer(user)
return Response(serializer.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.