Django RestAPI服务器无法从iOS应用程序发布到它

2024-04-20 15:41:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个简单的restapi服务器。在

一切正常。我有一个模型,一个串行器等等。当我浏览到localhost:8000/foobars/时,我可以获取并发布foobars,而且{}也可以正常工作。(来自Browser works的帖子)

我有两个模型:Geopoint和FooBar。在

地质点:

class Geopoint(models.Model):
    latitude = models.FloatField()
    longitude = models.FloatField()

FooBar酒吧:

^{pr2}$

序列化程序:

class GeopointSerializer(serializers.ModelSerializer):

    class Meta:
        model = Geopoint
        fields = ('id', 'latitude', 'longitude')

class FooBarSerializer(serializers.ModelSerializer):

    geo_location = GeopointSerializer(required=True)

    class Meta:
        model = FooBar
        fields = ('id', 'geo_location', 'geo_fence', 'registered', 'last_login')

在视图.py看起来像这样:

"""
    GEOPOINT
"""
class GeopointList(generics.ListCreateAPIView):
    queryset = Geopoint.objects.all()
    serializer_class = GeopointSerializer

class GeopointDetail(generics.RetrieveUpdateAPIView):
    queryset = Geopoint.objects.all()
    serializer_class = GeopointSerializer


"""
    FOOBAR
"""
class FooBarList(generics.ListCreateAPIView):
    queryset = FooBar.objects.all()
    serializer_class = FooBarSerializer

class FooBarDetail(generics.RetrieveUpdateAPIView):
    queryset = FooBar.objects.all()
    serializer_class = FooBarSerializer

在网址.py公司名称:

urlpatterns = [
    url(r'^geopoints/$', views.GeopointList.as_view()),
    url(r'^geopoints/(?P<pk>[0-9]+)/$', views.GeopointDetail.as_view()),

    url(r'^foobars/$', views.FooBarList.as_view()),
    url(r'^foobars/(?P<pk>[0-9]+)/$', views.FooBarDetail.as_view()),
]

所以,当我尝试使用AFNetworking在iOS中发布一个新的地理点时,这段代码是有效的!在

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{
                                 @"latitude": @"50.1205530",
                                 @"longitude": @"8.6444050"
                                 };
    [manager POST:@"http://127.0.0.1:8000/geopoints/"
       parameters:parameters
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

尝试发布一个新的FooBar,我得到一个错误:

NSDictionary *parameters = @{
                                     @"geo_location": @{
                                         @"latitude": @"50.1205530",
                                         @"longitude": @"8.6444050"
                                         },
                                     @"geo_fence": @"Frankfurt",
                                 };
    [manager POST:@"http://127.0.0.1:8000/foobars/"
       parameters:parameters
          success:^(AFHTTPRequestOperation *operation, id responseObject) {
              NSLog(@"JSON: %@", responseObject);
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSLog(@"Error: %@", error);
              NSLog(@"Error: %@", error.localizedDescription);
          }];

错误日志:

Error: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo=0x7cd17260 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7ce70b00> { URL: http://127.0.0.1:8000/foobars/ } { status code: 400, headers {
    Allow = "GET, POST, HEAD, OPTIONS";
    "Content-Type" = "application/json";
    Date = "Wed, 03 Dec 2014 13:21:45 GMT";
    Server = "WSGIServer/0.1 Python/2.7.8";
    Vary = "Accept, Cookie";
    "X-Frame-Options" = SAMEORIGIN;
} }, NSErrorFailingURLKey=http://127.0.0.1:8000/foobars/, NSLocalizedDescription=Request failed: bad request (400), com.alamofire.serialization.response.error.data=<7b226765 6f5f6c6f 63617469 6f6e223a 205b2244 69657365 73204665 6c642069 7374207a 77696e67 656e6420 6572666f 72646572 6c696368 2e225d7d>}

Django服务器日志:[03/Dec/2014 14:21:45] "POST /foobars/ HTTP/1.1" 400 60

我做错什么了?我想是序列化程序的问题,但我不确定。在

编辑:现在我在试这个:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSDictionary *newGeopoint = @{
                                 @"latitude": @"51.1205530",
                                 @"longitude": @"9.6444050"
                                 };
    [manager POST:@"http://127.0.0.1:8000/geopoints/"
       parameters:newGeopoint
          success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject)
    {
        NSDictionary *newFooBar = @{
                                    @"geo_location":responseObject,
                                    @"geo_fence": @"SOMEWHERE"
                                    };
        [manager POST:@"http://127.0.0.1:8000/foobars/"
           parameters:newFooBar
              success:^(AFHTTPRequestOperation *operation, id responseObject) {
                  NSLog(@"responseObject %@", responseObject);
              } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  NSLog(@"NewFooBarERROR: %@", error);
              }];

    }
          failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              NSLog(@"newGeopointERROR: %@", error);
    }];

但我得到了同样的错误信息:/

2014-12-04 09:47:23.828 ShoutPreView[1853:276181] NewFooBarERROR: Error Domain=com.alamofire.error.serialization.response Code=-1011 "Request failed: bad request (400)" UserInfo=0x79f90610 {com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7b08d360> { URL: http://127.0.0.1:8000/foobars/ } { status code: 400, headers {
    Allow = "GET, POST, HEAD, OPTIONS";
    "Content-Type" = "application/json";
    Date = "Thu, 04 Dec 2014 08:47:23 GMT";
    Server = "WSGIServer/0.1 Python/2.7.8";
    Vary = "Accept, Cookie";
    "X-Frame-Options" = SAMEORIGIN;
} }, NSErrorFailingURLKey=http://127.0.0.1:8000/foobars/, NSLocalizedDescription=Request failed: bad request (400), com.alamofire.serialization.response.error.data=<7b226765 6f5f6c6f 63617469 6f6e223a 205b2244 69657365 73204665 6c642069 7374207a 77696e67 656e6420 6572666f 72646572 6c696368 2e225d7d>}

使用DJANGO REST FRAMEWORK 3.0进行编辑: 我已经将django rest框架更新到3.0。 在我的网站API视图中,FooBar中现在有两个字段(一个用于long。其他用于横向) 当我试图通过Website/APIView发布时,我得到了一个错误:

IntegrityError at /foobars/
NOT NULL constraint failed: restServer_foobar.geo_location_id

我删除了我的数据库并创建了一个新的数据库。相同的错误:/

序列化程序:

class GeopointSerializer(serializers.ModelSerializer):

    class Meta:
        model = Geopoint
        fields = ('id', 'latitude', 'longitude')

class FooBarSerializer(serializers.ModelSerializer):

    geo_location = GeopointSerializer(required=True)

    class Meta:
        model = FooBar
        fields = ('id', 'geo_location', 'geo_fence', 'registered', 'last_login')

    def create(self, validated_data):
        geo_location_data = validated_data.pop('geo_location')
        foobar = FooBar.objects.create(**validated_data)
        Geopoint.objects.create(FooBar=foobar, **geo_location_data)
        return foobar

已解决 更新到django-restframework-3.0之后,AFNetworking出现了一个问题。在

这是我的目标C代码。在

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    NSDictionary *foobarparams = @ {@"geo_location" :@{
                                                       @"latitude":@997,
                                                       @"longitude":@997
                                                       }, @"geo_fence" :@"Frankfurt" };


    [manager POST:@"http://127.0.0.1:8000/foobars/" parameters:foobarparams
          success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        NSLog(@"JSON: %@", responseObject);
    }
          failure:
     ^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
     }];

Tags: idhttpmanagerlocationerrorpostoperationclass
1条回答
网友
1楼 · 发布于 2024-04-20 15:41:19

您的模型FooBar有一个ForeignKey字段,您在FooBarSerializer中添加了一个serializer字段,但这不足以创建一个新的FooBar+一个新的Geopoint。在

Django Rest Framework(2.4.x)目前不支持带有可写嵌套序列化程序的ModelSerializer子类(就像您试图实现的那样)。这是一项正在进行的任务,请参见http://www.django-rest-framework.org/topics/3.0-announcement/#writable-nested-serialization

我的建议是:

编辑:

用键值(即整数)更改请求@“geo_location”:responseObject。可能是的响应对象.pk在

相关问题 更多 >