簡體   English   中英

我需要對 views.py 中的函數做什么?

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

我正在開發一個 API,我需要創建一個函數,在不到 10 分鍾的時間內不允許使用相同的帖子格式,但是如果用戶使用“GET”請求,我只是想在終端中打印一些內容方法,但它不起作用。

網址.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"),
       
]

視圖.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

我仍然看到數據,但是當我使用 get 方法時它沒有返回任何消息或打印任何內容。 先感謝您!!

您傳遞給函數的第一個參數是self ,將其刪除。 否則, Request對象將在該變量中而不是request ,它與您在if語句中一起工作。

另外,用api_view裝飾函數:https : api_view

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM