我对网址http://127.0.0.1:8000/airlines/的POST请求失败
以下是我项目中的模型和相应的序列化器。最初我想创建航空公司信息,然后再添加航班
有人可以告诉我哪里出错了吗
models.py
class AirlineFirm(models.Model):
operator_name = models.CharField(max_length=30)
def __unicode__(self):
return "%s" % (self.operator_name)
class Flight(models.Model):
flight_num = models.CharField(max_length=7, primary_key=True)
src = models.CharField(max_length=20)
dest = models.CharField(max_length=20)
outbound_time = models.DateTimeField()
inbound_time = models.DateTimeField()
num_of_seats = models.IntegerField()
ticketPrice = models.FloatField()
delayed = models.BooleanField()
airlinefirm = models.ForeignKey(AirlineFirm)
serializers.py
class FlightSerializer(serializers.Serializer):
flight_num = serializers.CharField(read_only=True)
src = serializers.CharField()
dest = serializers.CharField()
outbound_time = serializers.DateTimeField()
inbound_time = serializers.DateTimeField()
num_of_seats = serializers.IntegerField()
ticketPrice = serializers.FloatField()
delayed = serializers.BooleanField()
airlinefirm = serializers.RelatedField(read_only='True')
#passengers = models.ManyToManyField(Passenger)
def create(self, validated_data):
return Flight.objects.create(**validated_data)
def update(self, instance, validated_data):
pass
class AirlineSerializer(serializers.ModelSerializer):
flights = FlightSerializer(many=True)
class Meta:
model = AirlineFirm
fields = ('operator_name','flights')
def create(self, validated_data):
flights_data = validated_data.pop('flights')
airlinefirm = AirlineFirm.objects.create(**validated_data)
for flight_data in flights_data:
Flight.objects.create(airlinefirm=airlinefirm, **flight_data)
return airlinefirm
views.py
@api_view(['GET','POST'])
def airline(request, format=None):
if request.method == 'GET':
airlines = AirlineFirm.objects.all()
serializer = AirlineSerializer(airlines, many=True)
return Response(serializer.data)
if request.method == 'POST':
#data = JSONParser().parse(request)
serializer = AirlineSerializer(data=request.data)
#import pdb;pdb.set_trace()
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
import pdb;pdb.set_trace()
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
当我向我的航空公司视图课程发送POST请求http://127.0.0.1:8000/airlines/时,我得到404回复
http请求
import json
import requests
payload = {'operator_name':'AmericanAirlines','flights':[]}
headers = {'Content-type':'application/json'}
r = requests.post('http://127.0.0.1:8000/',data=json.dumps(payload),headers=headers)
以下是错误消息:
AttributeError:尝试在序列化程序flights
上获取字段AirlineSerializer
的值时获得AttributeError。
序列化程序字段可能名称不正确,并且与AirlineFirm
实例上的任何属性或键都不匹配。
原始异常文本是:'AirlineFirm'对象没有属性'flight'。
[18 / Feb / 2016 13:43:58]“POST / airlines / HTTP / 1.1”500 112039
答案 0 :(得分:1)
你需要和你的urls.py中的api端点(如果它不存在),然后在你的请求中指向它,如:
r = requests.post('http://127.0.0.1:8000/airlines',data=json.dumps(payload),headers=headers)