Sonu kumar
Sonu kumar

Reputation: 33

Facing Issue to make the UUID as endpoint in Django Rest framework

As I am new to Django I am unable to make the endpoint in API in the rest-framework library how to make the UUID as an EndPoint their

class Cart(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, max_length=30)
    created_at = models.DateTimeField(auto_now_add=True)


class CartItem(models.Model):
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='items')
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveSmallIntegerField(validators=[MinValueValidator(1)])

As For Serialize the data their

class CartSerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(read_only=True)

    class Meta:
        model = Cart
        fields = ['id']

For View

class CartViewSet(CreateModelMixin, GenericViewSet):
    lookup_field = 'pk:'
    queryset = Cart.objects.all()
    serializer_class = CartSerializer

For Routing

from . import views
from pprint import print
from rest_framework_nested import routers



router = routers.DefaultRouter()
router.register('products', views.ProductViewSet,basename='products'),   
router.register('collections', views.CollectionViewSet,basename='collections')
router.register('carts', views.CartViewSet, basename='carts')
pprint(router.urls)

How to Resolve this Error

[01/Jan/2022 14:47:48] "GET /store/carts/ HTTP/1.1" 405 17010
[01/Jan/2022 14:48:04] "POST /store/carts/ HTTP/1.1" 201 16991
[01/Jan/2022 14:48:15] "OPTIONS /store/carts/ HTTP/1.1" 200 17589
Not Found: /store/carts/fc233c62-14dc-4cbe-a488-5add2c083b81
[01/Jan/2022 14:48:37] "GET /store/carts/fc233c62-14dc-4cbe-a488-5add2c083b81 HTTP/1.1" 404 16322`    

Upvotes: 0

Views: 543

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32244

CartViewSet inherits from CreateModelMixin and GenericViewSet so it doesn't implement the retrieve action.

You need to inherit from RetrieveModelMixin if you want to add this action to your viewset

class CartViewSet(CreateModelMixin, RetrieveModelMixin, GenericViewSet):
    ...

Upvotes: 1

Related Questions