在Django rest fram中放置和删除请求

2021-02-25 20:53:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Django新手,我想知道如何在Django restapi项目中编写PUT request和Delete方法。在

我尝试过很多教程,但是没有一个使用我的代码。在

我试过的代码是这样的

def put(self, request, pk): snippet = self.get_object(pk) serializer = UserSerializers(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

^{pr2}$

但不允许获取消息方法

以下是我的模型.py在

from django.db import models class Users(models.Model): user_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) profile_name = models.CharField(max_length=30) profile_picture = models.CharField(max_length=1000) phone = models.CharField(max_length=15) email = models.EmailField() password = models.CharField(max_length=25, default='') def __str__(self): return self.name

以下是我的序列化程序.py在

from rest_framework import serializers from .models import Users from .models import UserPost class UserSerializers(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' class UserDetailSerializer(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' class UserPostSerializers(serializers.ModelSerializer): class Meta: model = UserPost fields = '__all__'

以下代码包含视图.py在

from django.http import Http404 from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import status from .models import Users from .models import UserPost from .serializers import UserSerializers, UserPostSerializers class UsersList(APIView): def get(self, request): User_details = Users.objects.all() serializer = UserSerializers(User_details, many=True) return Response(serializer.data) def post(self, request): serializer = UserSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class UserDetail(APIView): def get_object(self, pk): try: return Users.objects.get(pk=pk) except Users.DoesNotExist: raise Http404 def get(self, request, pk): snippet = self.get_object(pk) serializer = UserSerializers(snippet) return Response(serializer.data) class UserViewSet(viewsets.ModelViewSet): queryset = Users.objects.all() serializer_class = UserSerializer @action(methods=['put'], detail=False) def filter_by_something(self, request): something = request.data.get('that_something') queryset = Users.objects.filter(something__exact=something) return Response(self.get_serializer(queryset, many=True).data)

以下代码包含网址.py在

from sys import path from django.urls import include from rest_framework.urlpatterns import format_suffix_patterns from app import views from django.conf.urls import url from django.contrib import admin from rest_framework import routers router = routers.DefaultRouter() router.register('user_details', UserDetailViewSet) urlpatterns = [path('api/', include(router.urls)), ...] urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^User_details/', views.UsersList.as_view()), url(r'^User_details/(?P<pk>[0-9]+)/', views.UserDetail.as_view()), url(r'^userpost_details/', views.UsersPostList.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns)

2条回答
网友
1楼 ·

UsersDetail类中定义put&;delete方法。在

class UsersDetail(APIView):
 def put(self, request, pk):
   // code

 def delete(self, request, pk):
   //code

如果上述操作不起作用,则添加http_method_names

^{pr2}$

APIView继承了Django基文件中定义的类Viewdispatch方法将检查http_method_names的有效方法。PUT和{}与其他方法一起列为有效方法。在

参考:django/views/generic/base.py

  class View(object):
    def dispatch(self, request, *args, **kwargs):
        # Try to dispatch to the right method; if a method doesn't exist,
        # defer to the error handler. Also defer to the error handler if the
        # request method isn't on the approved list.
        if request.method.lower() in self.http_method_names:
            handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
        else:
            handler = self.http_method_not_allowed
        return handler(request, *args, **kwargs)

    def http_method_not_allowed(self, request, *args, **kwargs):
        logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
            extra={
                'status_code': 405,
                'request': request
            }
        )
        return http.HttpResponseNotAllowed(self._allowed_methods())
网友
2楼 ·

在网址.py您应该声明一个将视图集映射到DRF的路由器对象:

from rest_framework import routers
router = routers.DefaultRouter()
router.register('user_details', UserDetailViewSet)
urlpatterns = [path('api/', include(router.urls)), ...]

必须在api中声明UserDetailViewSet\视图.py(api是DRF应用程序的目录)

^{pr2}$

然后您将在http:\\ your_website\api\user_details\filter_by_something上发出PUT请求

试试这个。它应该有用的!在

相关问题