tags:

views:

68

answers:

1

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 correct urlpatterns in this setup?

+3  A: 

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__.

Daniel Roseman
+1 for all the urlconf cares about is that the value for the view is a callable. I was about to post the same thing.
mikej
very interesting - I'm not sure this will ever come in handy, but I'm glad to know it :)
Jiaaro