在看似有效的 Django Rest Framework Post 请求上获取错误请求,要求在序列化程序数据中请求 FK
Posted
技术标签:
【中文标题】在看似有效的 Django Rest Framework Post 请求上获取错误请求,要求在序列化程序数据中请求 FK【英文标题】:Getting Bad Request on seemily valid Django Rest Framework Post request asking for FK in Serializer data 【发布时间】:2018-08-11 10:27:41 【问题描述】:我正在创建一个新的 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."
这是说城市对象是必需的。但我不是在序列化程序中要求它。我不确定我做错了什么。
编辑:我尝试了这篇文章中推荐的修复: 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 传入上面的序列化器
但它并没有改变任何东西
编辑:
我试图将序列化程序的城市字段设置为只读。但这也没有帮助
感谢您的帮助。
【问题讨论】:
【参考方案1】:再次回答我自己的问题
它在我的 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);
);
【讨论】:
是的,谢谢!我的 api 应用程序遇到了同样的问题 - django 序列化程序有一个“用户名”输入,反应它是“用户名”以上是关于在看似有效的 Django Rest Framework Post 请求上获取错误请求,要求在序列化程序数据中请求 FK的主要内容,如果未能解决你的问题,请参考以下文章
注册后 Django Rest Framework 无法登录
将 django-rest-framework 中的超链接添加到 ModelViewSet