代码之家  ›  专栏  ›  技术社区  ›  Charles Haro

django tastypie简单GET给出400个错误

  •  0
  • Charles Haro  · 技术社区  · 10 年前

    我使用的是python2.7、django1.6和apache2。我已启用跨域访问。我尝试过使用和不使用crsf令牌。我不知道我做错了什么。

    参观: url/to/site/contacts/api/v1/adresponses/1 工作正常,所以很美味。我可以看到广告回复。

    请有人帮忙。几天来,我一直在努力让美味派工作。

    这是我的api.py

    class UserResource(ModelResource):
        class Meta:
                queryset = User.objects.all()
                resource_name = 'user'
                fields=['username', 'id']
                allowed_methods = ['get']
                authorization = Authorization()
                authentication = Authentication()
    
     class AdResponsesResource(ModelResource):
        users = fields.ManyToManyField('contacts.api.UserResource', 'users',
                        related_name='adresponse')
        class Meta:
                queryset = AdResponses.objects.all()
                resource_name = 'adresponses'
                authorization = Authorization()
                authentication = Authentication()
    

    这是我的ajax调用

    $(function (){
        $.ajax({
            url: 'url/to/site/contacts/api/v1/adresponses/1',
            type: 'GET',
            accepts: 'application/json',
            dataType: 'json'
        });
    

    所以我不完全确定为什么我最初发布的js不起作用,但我看到了这个例子 http://django-tastypie.readthedocs.org/en/latest/cookbook.html 它的工作如预期。也许是因为我没有成功的功能?

    $.ajax({
        url: '../../api/v1/user/',
        contentType: 'application/json',
        type: 'GET', 
        success: function(data, textStatus, jqXHR) {
             // Your processing of the data here.
             console.log(data);
             }
        });
    
    2 回复  |  直到 10 年前
        1
  •  1
  •   Arctelix    10 年前

    我需要查看为api设置的url,以便为您提供更多帮助,但对于初学者来说,您提供的原始url是:

    url: 'url/to/site/contacts/api/v1/adresponses/1',
    

    和你回答中的那个

    url: '../../api/v1/user/',
    

    不要调用相同的资源,这会使诊断更加困难。

    然而,第一个url是绝对路径,第二个是相对路径,这可能会导致您的 ALLOWED_HOSTS 可能产生400错误的设置。

    所以试试这个:

     $.ajax({
        url: '../../api/v1/adresponses/1',
        contentType: 'application/json',
        type: 'GET', 
        success: function(data, textStatus, jqXHR) {
             console.log(data);
             }
        });
    

    是的,如果没有成功功能,您将看不到任何结果:

    success: function(data, textStatus, jqXHR) {
        console.log(data);
    }
    

    console.log是使您在控制台中看到结果的内容。

    您的原始代码不提供:

    contentType: 'application/json',
    

    您有:

    accepts: 'application/json',
    
        2
  •  0
  •   jpizarrom    10 年前

    我认为问题是在url末尾使用“/”是强制性的。 您应该尝试使用url:'url/to/site/contacts/api/v1/adresponses/1/',

    当您访问url/to/site/contacts/api/v1/adresponses/1时,它会重定向到url/to/site/contacts/api/v1/andresponses/1/,具体取决于您的tastypie配置