如何使用命名空间调用Django Rest Framework URL? [英] How do I call a Django Rest Framework URL using namespacing?

查看:123
本文介绍了如何使用命名空间调用Django Rest Framework URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的urls.py:

I have a urls.py that looks like this:

router = SimpleRouter()
router.register(r'meetings', MeetingViewSet, 'meetings-list')

urlpatterns = patterns('clubs.views',
    url(r'^(?P<pk>\d+)/', include(router.urls)),
    url(r'^amazon/$', AmazonView.as_view(), name="amazon"),)

我想使用reverse引用'meetings-list'网址,如下所示:

I want to reference the 'meetings-list' url using reverse, as in:

url = reverse('meetings-list')

但是当我尝试这个时,我会得到NoReverseMatch: Reverse for 'MeetingViewSet' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

but when I try this I get NoReverseMatch: Reverse for 'MeetingViewSet' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

是否可以使用Django Rest Framework做到这一点?

Is there a way to do this using Django Rest Framework?

推荐答案

向路由器注册视图时,可以将base_name作为第三个参数传递.此基本名称用于生成单独的URL名称,它们分别作为[base_name]-list[base_name]-detail生成.

When registering views with the router, you can pass the base_name in as the third argument. This base name is used to generate the individual url names, which are generated as [base_name]-list and [base_name]-detail.

在您的情况下,您正在将视图集注册为

In your case, you are registering your viewset as

router.register(r'meetings', MeetingViewSet, 'meetings-list')

所以base_namemeetings-list,视图名称是meetings-list-listmeetings-list-detail.听起来您正在寻找meetings-listmeetings-detail,它们需要base_namemeetings.

So the base_name is meetings-list, and the view names are meetings-list-list and meetings-list-detail. It sounds like you are looking for meetings-list and meetings-detail, which would require a base_name of meetings.

router.register(r'meetings', MeetingViewSet, 'meetings')

您还使用了现在不建议使用的patterns语法来定义url,但实际上并没有使用正确的url调用.我建议只替换patterns并用标准的Python列表/元组([]())包装您的网址列表.

You are also using the now-deprecated patterns syntax for defining urls, but you are not actually using the right url calls that work with it. I would recommend just replacing the patterns and wrapping your list of urls with a standard Python list/tuple ([] or ()).

这应该可以解决您的问题,并且对reverse的呼叫应该可以为您解决.

This should fix your issue, and the call to reverse should resolve for you.

这篇关于如何使用命名空间调用Django Rest Framework URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆