在看似有效的 Django Rest Framework Post 上获取错误请求,请求在序列化程序数据中请求 FK

Getting Bad Request on seemily valid Django Rest Framework Post request asking for FK in Serializer data

我正在创建一个新的 SearchNeighborhood 对象并将其连接到 POST 请求中已经创建的 SearchCity 对象。

我有以下型号

class SearchCity(models.Model):
    city = models.CharField(max_length=200)

class SearchNeighborhood(models.Model):
    city = models.ForeignKey(SearchCity, on_delete=models.CASCADE)
    neighborhood = models.CharField(max_length=200)

我的相关序列化程序是:

class SearchNeighborhoodSerializer(serializers.ModelSerializer):
    class Meta:
        model = SearchNeighborhood
        fields = ('pk', 'neighborhood')

我的观点和相关方法是:

class CityNeighborhoodsListCreate(APIView):
 def post(self, request, *args, **kwargs):
        citypk = kwargs.get('citypk', None)
        city=get_object_or_404(SearchCity,pk=citypk)
        serialized = SearchNeighborhoodSerializer(data=request.data)
        if serialized.is_valid(raise_exception=True):
            validatedData = serialized.validated_data
            neighborhood = validatedData.get('neighborhood')
            neighborhoodobject = SearchNeighborhood(neighborhood= neighborhood, city = city)
            neighborhoodobject.save()
            createdneighborhood = SearchNeighborhoodSerializer(neighborhoodobject)
            return Response({
                'neighborhood': createdneighborhood.data
            })

我正在使用 Angular 4

我的AJAX请求是:

addneighborhood(){
     const payload = {
       neighborhood: this.addneighborhoodform.form.value.addneighborhoodinput
     };
     this.suitsettingsservice.addneighborhood(payload)
       .subscribe(
         (req: any)=>{
             this.selectedcityneighborhoods.push(req);
         });

我得到的错误是:

HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "http://127.0.0.1:8000/api/suitsadmin/settings/neighborhoodbycity", ok: false, …}
error:city :  "This field is required."

说需要城市对象。但我没有在序列化程序中要求它。我不确定我做错了什么。

编辑:我尝试了此 post 中推荐的修复:

将城市对象传递到序列化程序中

  def post(self, request, *args, **kwargs):
        citypk = kwargs.get('citypk', None)
        city=get_object_or_404(SearchCity,pk=citypk)
        serialized = SearchNeighborhoodSerializer(city,data=request.data)

城市传递到上面的序列化器

但它没有改变任何东西

编辑:

我试图将序列化程序城市字段设置为只读。但这也没有帮助

感谢您的帮助。

再次回答我自己的问题

它在我的 AJAX

我在 json 中包含了一个街区字段,但没有包含一个城市。为了满足 serailizer 我必须填充这个字段

addneighborhood(){
     const payload = {
       city: this.selectedcityname,
       neighborhood: this.addneighborhoodform.form.value.addneighborhoodinput
     };
     this.suitsettingsservice.addneighborhood(payload)
       .subscribe(
         (req: any)=>{
             this.selectedcityneighborhoods.push(req);
         });