【问题标题】:django-tastypie simple GET gives 400 errordjango-tastypie 简单的 GET 给出 400 错误
【发布时间】:2014-03-10 22:19:03
【问题描述】:

我正在使用 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);
         }
    });

【问题讨论】:

    标签: python django python-2.7 tastypie http-status-code-400


    【解决方案1】:

    我需要查看您为 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',
    

    【讨论】:

    • 我知道如果没有成功我会看到结果,但我的问题是它是否导致了 400 错误。根据您的回答,我猜不是,错误是由“接受”部分引起的。感谢您的回复! :D
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-08-05
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 2015-06-23
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多