I am creating a new SearchNeighborhood
object and connecting it to a already create SearchCity
object in a POST
request.
I have the following models
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)
my relevant serializer is:
class SearchNeighborhoodSerializer(serializers.ModelSerializer):
class Meta:
model = SearchNeighborhood
fields = ('pk', 'neighborhood')
my view and relevant method is:
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
})
I am using Angular 4
my AJAX
request is:
addneighborhood(){
const payload = {
neighborhood: this.addneighborhoodform.form.value.addneighborhoodinput
};
this.suitsettingsservice.addneighborhood(payload)
.subscribe(
(req: any)=>{
this.selectedcityneighborhoods.push(req);
});
the error I am getting is:
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."
It is saying the city object is required. but I am not asking for it in the serializer. I am not sure what I am doing wrong.
edit: I attempted the fix recommended in this post: Django REST Framework : "This field is required." with required=False and unique_together
of passing the city object into the serializer
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)
but it didnt change anything
edit:
I attempted to set the serializers city field to read only. But that also didnt help
Thank you for your help.
Answering my own question again
its in my AJAX
I include a neighborhood field in the json but not a city. to satisfy the serailizer I must populate this field
addneighborhood(){
const payload = {
city: this.selectedcityname,
neighborhood: this.addneighborhoodform.form.value.addneighborhoodinput
};
this.suitsettingsservice.addneighborhood(payload)
.subscribe(
(req: any)=>{
this.selectedcityneighborhoods.push(req);
});