Django RESTful框架中的POST,PUT,DELETE不起作用

时间:2019-01-06 06:53:01

标签: django django-rest-framework request

我想使用POST发布到我的Django服务器,以便添加员工项目。

views.py

class EmployeeList(generics.ListAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer


class EmployeeDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

models.py

class Employee(models.Model):
    firstname=models.CharField(max_length=10)
    lastname=models.CharField(max_length=10)
    emp_id=models.IntegerField()

    def __str__(self):
        return self.firstname;

serializer.py

class EmployeeSerializer(serializers.ModelSerializer):

    class Meta:
        model=Employee
        # fields={'firstname','lastname'}
        fields='__all__'

我的POST请求:

{
    "id": 8,
    "firstname": "zxcvb",
    "lastname": "bnmmm",
    "emp_id": 3
}

我得到的错误:

{
    "detail": "Method \"POST\" not allowed."
}

即使使用了generics.RetrieveUpdateDestroyAPIView,我也无法发布,放置或删除。

PS:我是Django REST框架的新手。

1 个答案:

答案 0 :(得分:1)

要提供post方法处理程序,您需要一个带有create()操作(CreateAPIViewListCreateAPIView)的视图。检查有关concrete view classes的文档。

将您的EmployeeList视图更改为从ListCreateAPIView继承,以添加读写端点来代表员工集合

class EmployeeList(generics.ListCreateAPIView):
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

现在,只需照常向URL conf注册视图

urlpatterns = [
    path('employees/', EmployeeList, name='employee-list'),
    path('employees/<int:pk>/', EmployeeDetail, name='employee-detail'),
]

具体视图类将在混合文件中定义的方法(例如ListModelMixinCreateModelMixinRetrieveModelMixin等映射到HTTP方法)。默认情况下,这些操作(请参见here)映射到以下HTTP方法

  • list-get
  • create-post
  • retrieve-get
  • update-put
  • partial_update-patch
  • destroy-delete