我现在正在使用路由器创建url,我想为我的api创建url,但是问题是,我遇到了错误
createuser()缺少1个必需的位置参数:'request'缺少1个必需的位置参数:'request'
我在UserAuthAPIView类内的所有方法都遇到相同的错误,我已经阅读了stackoverflow上的解决方案,但在我的情况下它们无法正常工作。
我在UserAuthAPIView类中有很多方法,我想为所有这些方法创建URL。
例如
127.0.0.1:8000/api
127.0.0.1:8000/api/createuser
127.0.0.1:8000/api/login
127.0.0.1:8000/api/<pk>/viewuser
urls.py
from django.conf.urls import url
from UserAPI.api import views
from UserAPI.api.views import UserAuthAPIView
urlpatterns = [
url(r'^$', UserAuthAPIView.as_view({'get': 'list'}), name='user-list'),
url(r'createuser/$', views.UserAuthAPIView.createuser, name='user-create'),
#url(r'userlogin/$', views.UserAuthAPIView.userlogin, name='user-login'),
]
views.py
class UserAuthAPIView(ModelViewSet):
queryset = UserModel.objects.all()
serializer_class = ListViewSerializer
def get_object(self, queryset=None):
return self.request.user
@action(methods=['post'], detail=False, permission_classes=[AllowAny], serializer_class=UserSerializer)
def createuser(self, request, *args, **kwargs):
data = request.data
serializer = UserSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response({ "status" : "user created successfully"}, status=HTTP_201_CREATED)
答案 0 :(得分:3)
路由器在视图集上执行一些操作,尤其是添加从http动词到相关函数的映射。
您需要执行类似的操作:
urlpatterns = [
url(r'^$', UserAuthAPIView.as_view({'get': 'list'}), name='user-list'),
url(r'createuser/$', views.UserAuthAPIView.as_view({'post': 'createuser'}), name='user-create'),
]
答案 1 :(得分:2)
您以错误的方式在URL中调用了Viewset。您需要这样做:
urlpatterns = [
url(r'createuser/$', UserAuthAPIView.as_view({'post':'createuser'}),
]
或
{{1}}