如何在django中将主键从url传递到基于函数的视图?

时间:2017-09-24 03:04:14

标签: django django-rest-framework django-views django-urls

我有一个基于功能的视图:

@api_view(['GET', 'PUT', 'DELETE'])
def hotel_detail(request, pk):
    # Lots of code

我正在使用此网址格式:

url(r'^hotel/(?P<pk>[0-9]+)/$', api.hotel_detail)

但它无效

视图:

@api_view(['GET', 'PUT', 'DELETE'])
def hotel_detail(request, pk):
    # Retrieve, update or delete a Hotel instance.
    try:
        hotel = models.Hotel.objects.get(pk=pk)
    except models.Hotel.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = serializers.HotelSerializer(hotel)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = serializers.HotelSerializer(hotel, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        hotel.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

我没有收到任何错误消息。

1 个答案:

答案 0 :(得分:0)

您好,您可以尝试命名组

urls.py

from django.conf.urls import url
from . import views
urlpatterns = [
         url(r'^hotel/(?P<pk>[0-9]+)/$', api.hotel_detail name="hotel_details"),
]

如果您想了解更多信息,请参阅文档Named groups