Django URL模式多个参数(无pk) [英] Django url pattern multiple Parameters (without pk)

查看:683
本文介绍了Django URL模式多个参数(无pk)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Django框架的新手,有一件事困扰着我.

I'm new to the Django Framework and one thing bothers me.

我想要一个简单的休息电话:

I want a simple Rest Call:

www.abc.com/users/1/cantonments/1/

如果我在网址格式中使用"pk",则一切都可以直接使用(pk,pk1,pk2 ....). 但是我有一些权限功能,希望用户和州以"upk"和"cpk"形式使用kwargs中的参数.因此,如果我将 pk 更改为 upk ,一切都会中断.该网址以某种方式需要一个pk.

If i use 'pk' in the url pattern everything works out of the box (pk, pk1, pk2....). But i have some permission functionality which expects the parameters in kwargs in the form 'upk' and 'cpk' for user and cantonment. So if i change pk to upk everything breaks. Somehow the url needs ONE pk.

这有效:

url(r'^users/(?P<pk>[0-9]+)/cantonments/(?P<cpk>[0-9]+)/$',
views.CantonmentDetail.as_view()),

这不是:

url(r'^users/(?P<upk>[0-9]+)/cantonments/(?P<cpk>[0-9]+)/$',
views.CantonmentDetail.as_view()),

是否可以使用不需要pk一项的网址格式?

P.S.错误:

Expected view CantonmentDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.

我的观点很简单:

# Authenticated User can show Cantonment Detail
class CantonmentDetail(generics.RetrieveAPIView):
    serializer_class = serializers.CantonmentSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return Cantonment.objects.filter(pk=self.kwargs['cpk'])

我将get_queryset更改为获取对象,并且它可以工作.

I changed get_queryset to get object and it works.

def get_object(self):
    queryset = self.filter_queryset(self.get_queryset())
    obj = queryset.get(pk=self.kwargs['cpk'])
    return obj

Edit3: 使用

lookup_url_kwarg = "cpk"

课堂上的

也可以.

in the class works as well.

推荐答案

您是否使用变量的新名称更改了视图? 如果您有这样的网址:

Did you changed your view with the new names of the variables? If you have url like this:

url(r'^users/(?P<upk>[0-9]+)/cantonments/(?P<cpk>[0-9]+)/$',
views.CantonmentDetail.as_view()),

您应该像这样更新您的视图:

You shouls update your view like this:

def view_name(request, upk=None, cpk=None):
    ...

这篇关于Django URL模式多个参数(无pk)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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