Я новичок в Django, мне было интересно, как кодировать запрос PUT и метод Delete в моем проекте REST API Django.
Я пытался следовать многим учебникам, но ни один из них не работал с моим видом кода..
Код, который я пробовал, выглядит следующим образом
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)
def delete(self, request, pk):
snippet = self.get_object(pk)
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
Но метод получения сообщений не разрешен
Ниже приведен мой Models.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
Ниже приведены мои serializers.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__'
Следующий код содержит мои Views.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)
Следующий код содержит urls.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)