简体   繁体   中英

django rest framework same route, different

i'm using django rest framework to build an api, here is my problem

url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveView.as_view(), name='profiles-detail'),
url(r'^profiles/(?P<pk>[0-9]*)', ProfileUpdateView.as_view(), name='profiles-update'),

    class ProfileRetrieveView(RetrieveAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

class ProfileUpdateView(UpdateAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated, )

When i query the api with the link /profile/2 and the method patch, i receive 405, method not allowed, only the get method is allowed, how can i solve that without haven to transform my two view classes into on class with a GenericView Base class and Retrive + update Mixins.

urls.py

url(r'^profiles/(?P<pk>[0-9]*)', ProfileRetrieveUpdateView.as_view(), name='profiles-detail-update'),

views.py

from rest_framework.generics import RetrieveUpdateAPIView

class ProfileRetrieveUpdateView(RetrieveUpdateAPIView):

    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

    def get_permissions(self):
        if self.request.method == "GET":
            return []
        else:
            return [IsAuthenticated()]

You should condense this into a single endpoint. You can have a single class handle all the listing, update, get, etc for this. Try...something like this:

from rest_framework import mixins, viewsets
class ProfileUpdateView(viewset.ModelViewSet,
                        mixins.ListModelMixin,
                        mixins.UpdateModelMixin):

    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated, )

    get_queryset(self):
          return Profile.objects.all()

If you're using pure models, use the built in model stuff, and check out the mixins. It will save you TONS of generic code writing. It has some magic that knows how to route the request to the matching http method.

http://www.django-rest-framework.org/api-guide/generic-views/#mixins

Django rest framework provides generic view you don't require Mixins. You can directly use RetrieveUpdateAPIView . Provides request methods get to retrieve data, put update data and patch for partial update.

from rest_framework.generics import RetrieveUpdateAPIView

class ProfileUpdateView(RetrieveUpdateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    permission_classes = (IsAuthenticated, )

Reference: http://www.django-rest-framework.org/api-guide/generic-views/#retrieveupdateapiview

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