gpt4 book ai didi

angular - 在看似有效的 Django Rest Framework 上获取错误请求 Post 请求在 Serializer 数据中请求 FK

转载 作者:行者123 更新时间:2023-12-04 03:01:11 25 4
gpt4 key购买 nike

我正在创建一个新的 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)

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

但这并没有改变什么

编辑:

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

感谢您的帮助。

最佳答案

再次回答我自己的问题

它在我的 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);
});

关于angular - 在看似有效的 Django Rest Framework 上获取错误请求 Post 请求在 Serializer 数据中请求 FK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49082128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com