CreateModelMixin TypeError:__init __()接受1个位置参数,但给出了2个

时间:2019-06-13 06:08:35

标签: django django-rest-framework django-rest-viewsets

我正在尝试在2列表中插入新行,其中一列引用经过身份验证的用户(模型通过FK引用用户模型),另一列是通过url传递的变量。

urls.py


url('^(?P<update>-?\d+.?\d+)/$', views.UpdateViewSet)

views.py


class UpdateViewSet(mixins.CreateModelMixin,viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)  
    serializer_class = serializers.UpdateSerializer
    def create(self,request,*args, **kwargs):
        update = self.kwargs['update']
        return self.create(user=self.request.user,update=update)

追踪

 File "\Backend\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "\Backend\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "\Backend\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
TypeError: __init__() takes 1 positional argument but 2 were given
class Update(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    update = models.DecimalField(decimal_places=5,max_digits=6)

2 个答案:

答案 0 :(得分:4)

由于您使用的是class-based views--[Django Doc],因此您应该致电as_view()--[Django Doc]

url('^(?P<update>-?\d+.?\d+)/$', views.UpdateViewSet.as_view({"post":"create"}))

Update-1

如下更改视图,

from rest_framework.response import Response


class UpdateViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = (IsAuthenticated,)
    serializer_class = serializers.UpdateSerializer

    def create(self, request, *args, **kwargs):
        update_instance = Update.objects.create(user=request.user, update=self.kwargs['update'])
        return Response(self.get_serializer(update_instance).data)

答案 1 :(得分:1)

我认为您错误地配置了网址,请这样做:

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'update', views.UpdateViewSet, basename='update')
urlpatterns = router.urls

 url(r'^(?P<update>-?\d+.?\d+)/$', views.UpdateViewSet.as_view(actions={'post': 'create'}))