首页 > 解决方案 > 基于 Django 类的视图,传递参数

问题描述

我在 django rest 中有以下基于类的视图,

class UserRoom(views.APIView):
    def add_user_to_persistent_room(self, request):
        try:
            user = User.objects.get(id=int(request.data['user_id']))
            club = Club.objects.get(id=int(request.data['club_id']))
            location = Location.objects.get(id=int(request.data['location_id']))
            name = location.city + '-' + club.name
            room, created = PersistentRoom.objects.get_or_create(name=name,
                                                                 defaults={'club': club, 'location': location})
            room.users.add(user)
            room.save()
            return Response(PersistentRoomSerializer(room).data, status=status.HTTP_201_CREATED)
        except User.DoesNotExist:
            return Response("{Error: Either User or Club does not exist}", status=status.HTTP_404_NOT_FOUND)


    def find_all_rooms_for_user(self, request, **kwargs):
        try:
            user = User.objects.get(id=int(kwargs.get('user_id')))
            persistent_rooms = user.persistentroom_set.all()
            floating_rooms = user.floatingroom_set.all()
            rooms = [PersistentRoomSerializer(persistent_room).data for persistent_room in persistent_rooms]
            for floating_room in floating_rooms:
                rooms.append(FloatingRoomSerializer(floating_room).data)
            return Response(rooms, status=status.HTTP_200_OK)
        except User.DoesNotExist:
            return Response("{Error: User does not exist}", status=status.HTTP_404_NOT_FOUND)

这是我的 urls.py

urlpatterns = [
    url(r'^rooms/persistent/(?P<user_id>[\w.-]+)/(?P<club_id>[\w.-]+)/(?P<location_id>[\w.-]+)/$',
        UserRoom.add_user_to_persistent_room(),
        name='add_user_to_persistent_room'),
    url(r'^rooms/all/(?P<user_id>[\w.-]+)/$', UserRoom.find_all_rooms_for_user(), name='find_all_rooms')
]

当我运行它时,我收到以下错误,

TypeError: add_user_to_persistent_room() missing 2 required positional arguments: 'self' and 'request'

我清楚地理解了这个错误的原因,我的问题是如何在 urls.py 中传递请求对象?

标签: djangodjango-rest-frameworkdjango-class-based-views

解决方案


我认为你使用Class Based Views了错误的方法。您的方法必须命名为getor post。例如:

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from django.contrib.auth.models import User

class ListUsers(APIView):
    """
    View to list all users in the system.

    * Requires token authentication.
    * Only admin users are able to access this view.
    """
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = (permissions.IsAdminUser,)

    def get(self, request, format=None):
        """
        Return a list of all users.
        """
        usernames = [user.username for user in User.objects.all()]
        return Response(usernames)

更多信息在这里: http: //www.django-rest-framework.org/api-guide/views/#class-based-views


推荐阅读