在似乎有效的Django Rest Framework Post请求中获取错误请求,要求在Serializer数据中使用FK

问题描述 投票:2回答:1

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

我有以下型号

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."

它说城市对象是必需的。但我不是在串行器中要求它。我不确定我做错了什么。

编辑:我尝试了这篇文章中推荐的修复:Django REST Framework : "This field is required." with required=False and unique_together

将城市对象传递给序列化程序

  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)

city passsed into serializer above

但它没有改变任何东西

编辑:

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

谢谢您的帮助。

angular post django-rest-framework deserialization bad-request
1个回答
4
投票

再次回答我自己的问题

它在我的AJAX中

我在json中包含一个邻域,但不包括城市。为了满足这种选择,我必须填充这个领域

addneighborhood(){
     const payload = {
       city: this.selectedcityname,
       neighborhood: this.addneighborhoodform.form.value.addneighborhoodinput
     };
     this.suitsettingsservice.addneighborhood(payload)
       .subscribe(
         (req: any)=>{
             this.selectedcityneighborhoods.push(req);
         });
© www.soinside.com 2019 - 2024. All rights reserved.