我是Django的新手,我想知道如何在Django REST API项目中编写PUT请求和Delete方法的代码。
我尝试遵循许多教程,但是没有一本使用我的代码。
我尝试过的代码如下
In [17]: dailyUsage['hours'] = dailyUsage.apply(calcDuration,axis=1)
In [18]: dailyUsage.drop(['Start','End'],axis=1).head()
Out [18]:
Date User hours
0 2018-01-01 Dan 11
1 2018-01-02 Dan 24
2 2018-01-03 Dan 13
3 2018-03-01 Fred 8
4 2018-03-02 Fred 16
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)
但是不允许获取消息方法
以下是我的Models.py
def delete(self, request, pk):
snippet = self.get_object(pk)
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
以下是我的serializers.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
以下代码包含我的Views.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__'
以下代码包含urls.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)
答案 0 :(得分:0)
在urls.py中,您应该声明一个将ViewSet映射到DRF的路由器对象:
from rest_framework import routers
router = routers.DefaultRouter()
router.register('user_details', UserDetailViewSet)
urlpatterns = [path('api/', include(router.urls)), ...]
UserDetailViewSet必须在api \ views.py中声明(api是DRF应用程序的目录)
from rest_framework.decorators import action
from rest_framework import viewsets
from rest_framework.response import Response
class UserDetailViewSet(viewsets.ModelViewSet):
queryset = UserDetail.objects.all()
serializer_class = UserDetailSerializer
@action(methods=['put'], detail=False)
def filter_by_something(self, request):
something = request.data.get('that_something')
queryset = UserDetail.objects.filter(something__exact=something)
return Response(self.get_serializer(queryset, many=True).data)
然后,您将在http:\\您的网站\ api \ user_details \ filter_by_something上发出PUT请求
尝试类似这样的方法。应该可以!
答案 1 :(得分:0)
在put
类中定义delete
和UsersDetail
方法。
class UsersDetail(APIView):
def put(self, request, pk):
// code
def delete(self, request, pk):
//code
如果以上方法无效,请添加http_method_names
class UsersDetail(APIView):
http_method_names = ['GET', 'PUT', 'DELETE']
类APIView
继承自Django基本文件中定义的类View
。 dispatch
方法将检查http_method_names
的有效方法。 PUT
和DELETE
与其他方法一起被列为有效方法。
参考: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())