【问题标题】:How to send parameter in AJAX (rest-api) using django?如何使用 django 在 AJAX (rest-api) 中发送参数?
【发布时间】:2013-12-13 20:59:54
【问题描述】:

我在 django 中使用了 rest-api, 而且我没有成功通过 ajax 发送“GET”参数:

在 django 的 rest-api 应用程序中,我在 urls.py 中有:

urlpatterns = patterns('',
    url(r'^titles/(?P<author_id>\d+)/$', login_required(views.TitlesViewSet.as_view()) ),
)

在views.py中我写道:

class TitlesViewSetViewSet(ListCreateAPIView):
     serializer_class = TitleSerializer

     def get_queryset(self):
         aouther_id = self.request.GET.get('aouther_id', None)
         return Title.objects.filter(auther = auther_id)

当代码插入到上面的 get_queryset 时,它无法识别任何 GET 参数,并且 aouther_id 设置为 None。

有人知道我应该怎么做吗?

【问题讨论】:

    标签: django-rest-framework


    【解决方案1】:

    首先,您在 url 中有一个拼写错误,您使用的是 author_id,并且您正在尝试获取 aouther_id 密钥。其次,您试图从查询参数中获取值,但实际上并没有使用它们。第三,您正在使用命名的 url 参数,这些参数存储在基于类的视图的 kwargs 属性中。

    您可以通过以下方式访问它们:

    class TitlesViewSetViewSet(ListCreateAPIView):
        serializer_class = TitleSerializer
    
        def get_queryset(self):
            # try printing self.kwargs here, to see the contents
            return Title.objects.filter(author_id=self.kwargs.get('author_id'))
    

    【讨论】:

      【解决方案2】:

      您应该将 auther_id 设置的一行替换为:

      auther_id=self.kwargs['auther_id']
      

      更新: 我现在看到 jbub 的答案......谢谢老兄!我才发现...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 2016-08-07
        • 2014-07-14
        • 2016-06-06
        • 1970-01-01
        • 2019-07-17
        相关资源
        最近更新 更多