我在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中传递请求对象?
答案 0 :(得分:1)
我认为你以错误的方式使用了Class Based Views
。您的方法必须命名为get
或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