szaman
szaman

Reputation: 6756

urls with object

I have element in my urls.py

url(r'^name/(?P<some_id>.+)/$', Class(), name='name'),

Is it possible somehow to receive some_id in class?

Upvotes: 0

Views: 130

Answers (2)

Reiner Gerecke
Reiner Gerecke

Reputation: 12214

When you pass a class instance as view, its __call__ method will be executed. The parameters passed are the same as in function-based views (except the self as first argument). Text that you capture in your regex will be passed as string to the function/method. (Capturing text in urls)

class A(object):

    def __call__(self, request, some_id):
        # stuff

If you don't already know this, Django will use class-based views (besides the function-based) as of version 1.3. http://docs.djangoproject.com/en/dev/ref/class-based-views/

Upvotes: 1

Ski
Ski

Reputation: 14487

You can do this with decorator.

def accepts_some_object(f):
    def new_f(request, some_object_id, *args, **kwargs):
        some_object = get_object_or_404(...)
        return f(request, *args, **kwargs, some_object=some_object)
    return new_f

@accepts_some_object
def some_view(request, some_object)

Useful if you have many views which accept some_object.

Upvotes: 1

Related Questions