CreateModelMixin TypeError: __init__() takes 1 positional argument but 2 were given

CreateModelMixin TypeError: __init__() takes 1 positional argument but 2 were given

我正在尝试将新行插入 2 列 table,其中一列引用经过身份验证的用户(模型通过 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)

因为您正在使用 class-based views--[Django Doc], you should've call as_view()--[Django Doc]

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

更新 1

改变你的观点如下,

<b>from rest_framework.response import Response</b>


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

    <b>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)</b>

我认为您 url 配置有误,请这样做:

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'}))