简体   繁体   中英

What do I need to do to a function in views.py works?

I'm working on a API and I need to create a function to don't allow the same post format in less than 10 minutes, but i'm just trying to print something in the terminal if the user use the "GET" request method, but it's not working.

urls.py:

from django.urls import include, path 
from rest_framework import routers 
from . import views 

router = routers.DefaultRouter()

router.register(r'products',views.ProductsViewSet)
router.register(r'product-images',views.ProductImagesViewSet)
#router.register(r'^products/', views.testIt, basename="TestIt")

urlpatterns = [
    path('', include(router.urls)), 
    path('api-auth/', include('rest_framework.urls',
namespace='rest_framework')), 
    path('products/', views.testIt, name = "testIt"),
       
]

views.py:

from rest_framework import viewsets
from .serializers import ProductsSerializers
from .serializers import ProductImagesSerializers
from .models import Products
from .models import ProductImages
from rest_framework import status   
from rest_framework.throttling import UserRateThrottle
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import api_view
from django.http import JsonResponse


class ProductsViewSet(viewsets.ModelViewSet, APIView):
    queryset = Products.objects.all().order_by('id')
    serializer_class = ProductsSerializers   
     
def testIt(self, request, pk=None):
    if request.method == 'GET':

        print('Testando')
    return Response('Teste!', status = status.HTTP_400_NOT_FOUND)
            
   
class ProductImagesViewSet(viewsets.ModelViewSet):
    queryset = ProductImages.objects.all().order_by('id')
    serializer_class = ProductImagesSerializers

I still see the data but it's not returning any message or printing anything when I use the get method. Thank you in advance!!

The first parameter you are passing to the function is self , remove it. Otherwise, the Request object will be in that variable instead of request , which with you are working in the if statement.

Also, decorate the function with api_view :https://www.django-rest-framework.org/api-guide/views/#api_view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM