开发者

urls with object

开发者 https://www.devze.com 2023-02-10 10:37 出处:网络
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开发者_如何学编程?When you pass a class instance as v

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开发者_如何学编程?


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/


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.

0

精彩评论

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