开发者

Django: how to use bare classes in urls.py urlpatterns?

开发者 https://www.devze.com 2022-12-13 08:15 出处:网络
I\'ve seen somewhere a urls.py construct like this: from project.f import SomeClass urlpatterns = patterns(\'\',

I've seen somewhere a urls.py construct like this:

from project.f import SomeClass

urlpatterns = patterns('',
   (r'^url/$', SomeClass()),
)

Nowhere in http://docs.djangoproject.com/en/dev/topics/http/urls/ I can find out what this means, normally an entry is like this:

   (r'^url/(?P<some_id>\d+)/$', 'project.views.some_view'),

Can someone explain me how putting just SomeClass() in there works?

The SomeClass() construct works if it is parameter-less, but I wanted to have parameters in there, so I made something like this:

   (r'^url/(?P<some_id>\d+)/$', SomeClass()),

and modified SomeClass which was:

class SomeClass(OtherClass):

    def items(self):
        return MyItems.objects.all()

to:

class SomeClass(OtherClass):

    def items(self, some_id):
        return MyItems.objects.filter(pk=some_id)

Now when visiting /url/ I get:

TypeError at /url/12/

items() takes exactly 2 arguments (1 given)

so it looks like the arguments are not passed. If I tried putting in urls.py:

   (r'^url/(?P<some_id>\d+)/$', SomeClass(some_id)),

I get:

NameError at /url/12/

name 'some_id' is not defined

How to make corre开发者_开发百科ct urlpatterns in this setup?


All the urlconf cares about is that the value for the view is a callable. Callables can be class instances, as long as the class defines a __call__ method. It's this method that needs to accept the parameters from the url - you haven't explained what your 'items' method is, but it's presumably being called from __call__.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号