How to make a PATCH request using DJANGO REST framework

前端 未结 6 1909
北恋
北恋 2020-12-13 13:11

I am not very experience with Django REST framework and have been trying out many things but can not make my PATCH request work.

I have a Model serializer. This is

6条回答
  •  暖寄归人
    2020-12-13 13:11

    Another posiblity is to make the request by URL. For example, I have a model like this

          class Author(models.Model):
            FirstName = models.CharField(max_length=70)
            MiddleName = models.CharField(max_length=70)
            LastName = models.CharField(max_length=70)
            Gender = models.CharField(max_length=1, choices = GENDERS)
            user = models.ForeignKey(User, default = 1, on_delete = models.CASCADE, related_name='author_user')
            IsActive = models.BooleanField(default=True)
            class Meta:
              ordering = ['LastName']
    

    And a view like this

          class Author(viewsets.ModelViewSet):
            queryset = Author.objects.all()
            serializer_class = AuthorSerializer
    

    So can enter http://127.0.0.1:8000/author/ to get or post authors. If I want to make a PATCH request you can point to http://127.0.0.1:8000/author/ID_AUTHOR from your client. For example in angular2, you can have something like this

           patchRequest(item: any): Observable {
            return this.http.patch('http://127.0.0.1:8000/author/1', item);
           }
    

    It suppose you have configured your CORS and you have the same model in back and front. Hope it can be usefull.

提交回复
热议问题