creación de vistas genericas para app ecommerce

Se utilizan viewsets del framework.
registro de vistas genericas en router del urls.py del sitio.
This commit is contained in:
devfzn 2023-03-30 15:49:52 -03:00
parent e3b750bd83
commit 0cfc0e5991
Signed by: devfzn
GPG Key ID: E070ECF4A754FDB1
3 changed files with 83 additions and 4 deletions

View File

@ -499,7 +499,7 @@ X-Frame-Options: DENY
}
```
## Ecommerce Model
### Ecommerce Model
Esta app hace uso obligatorio del token de autentificación. Solo usuarios
autentificados pueden acceder a este endpoint.
@ -518,3 +518,22 @@ Registro de app en el panel de [administración](./backend/ecommerce/admin.py).
Migraciones `./manage.py makemigrations` y `./manage.py migrate`.
### Ecommerce Views y URLs
Creación de [views](./backend/ecommerce/views.py) de la app, se utiliza
`IsAuthenticated` del framework.
Se agrega conjunto de vistas genericas de la app en [urls.py](./backend/drf_course/urls.py)
del sitio, registrandolas en el `router`.
```py
...
from ecommerce import views as ecommerce_views
...
router = routers.DefaultRouter()
router.register(r'item', ecommerce_views.ItemViewSet, basename='item')
router.register(r'order', ecommerce_views.OrderViewSet, basename='order')
...
```

View File

@ -1,10 +1,13 @@
from django.contrib import admin
from django.urls import path
from core import views as core_views
from ecommerce import views as ecommerce_views
from rest_framework import routers
from rest_framework.authtoken.views import obtain_auth_token
router = routers.DefaultRouter()
router.register(r'item', ecommerce_views.ItemViewSet, basename='item')
router.register(r'order', ecommerce_views.OrderViewSet, basename='order')
urlpatterns = router.urls

View File

@ -1,3 +1,60 @@
from django.shortcuts import render
from json import JSONDecodeError
from django.http import JsonResponse
from .serializers import ItemSerializer, OrderSerializer
from .models import Item , Order
from rest_framework.parsers import JSONParser
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.mixins import (
ListModelMixin,
UpdateModelMixin,
RetrieveModelMixin
)
# Create your views here.
class ItemViewSet(
ListModelMixin,
RetrieveModelMixin,
viewsets.GenericViewSet
):
"""
Conjunto de vistas simples para listar o recibir items.
"""
permission_classes = (IsAuthenticated,)
queryset = Item.objects.all()
serializer_class = ItemSerializer
class OrderViewSet(
ListModelMixin,
RetrieveModelMixin,
UpdateModelMixin,
viewsets.GenericViewSet
):
"""
Conjunto de vistas simples para listar, recibir y crear pedidos.
"""
permission_classes = (IsAuthenticated,)
serializer_class = OrderSerializer
def get_queryset(self):
"""
Retorna lista con todas las ordenes del usuario autentificado.
"""
user = self.request.user
return Order.objects.filter(user = user)
def create(self, request):
try:
data = JSONParser().parse(request)
serializer = OrderSerializer(data=data)
if serializer.is_valid(raise_exception=True):
item = Item.objects.get(pk = data["item"])
order = item.place_order(request.user, data["quantity"])
return Response(OrderSerializer(order).data)
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
except JSONDecodeError:
return JsonResponse({"result": "error","message": "Json decoding error"},
status= 400)