0

我正在尝试使用 Django Rest Framework 通过 AJAX 请求发布数据,但我不断收到此错误:

POST /api/uservenue/ HTTP/1.1" 400 37
{"venue":["This field is required."]}

但是,我正在发布该字段的数据,但无法弄清楚我做错了什么。

AJAX 调用:

const addVenueToList = function(listId, venueName) {
  console.log(venueName);
  console.log(listId);

  $.ajax({
    type: "POST",
    url: '/api/uservenue/',
    dataType: 'json',
    data: {
      csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value,
      'venue': JSON.stringify(venueName),
      'list': parseInt(listId)
    },
    success: function(data) {
      console.log('User added: ' + data)
    },
  });
}

这是我的序列化程序:

class UserVenueSerializer(serializers.ModelSerializer):
    venue = mapCafesSerializer()
    
    class Meta:
        model = UserVenue
        fields = ['id', 'list', 'venue']

以下是相关模型:

class UserVenue(models.Model):
    venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT)
    list = models.ForeignKey(UserList, on_delete=models.PROTECT)

    class Meta:
        unique_together = ['list','venue']

[...]

class mapCafes(models.Model): 
    id = models.BigAutoField(primary_key=True)
    cafe_name = models.CharField(max_length=200)
    cafe_address = models.CharField(max_length=200)
    cafe_long = models.FloatField()
    cafe_lat = models.FloatField()
    geolocation = models.PointField(geography=True, blank=True, null=True)
    venue_type = models.CharField(max_length=200)
    source = models.CharField(max_length=200)
    description = models.CharField(max_length=1000)

    class Meta:
        managed = False
        db_table = 'a_cafes'
4

1 回答 1

0

尝试

class UserVenueSerializer(serializers.ModelSerializer):
    venue = serializers.CharField(write_only=True)
    
    class Meta:
        model = UserVenue
        fields = ['id', 'list', 'venue']

    def create(self, validated_data):
       """Overrides the create method to create the UserVenue instance"""

        validated_data["venue"] = mapCafes.objects.get(cafe_name=validated_data.get("venue")
        return UserVenue.objects.create(**validated_data)
于 2021-03-23T14:06:09.310 回答