开发者

problems rendering a template when using a decorator in Django

开发者 https://www.devze.com 2023-01-18 13:53 出处:网络
I have this URL in my project: url(r\'^alerts/inbox/$\', \'inbox\', {\'template_name\': \'inbox.xhtml\' }, name = \'inbox\'),

I have this URL in my project:

url(r'^alerts/inbox/$', 'inbox', {'template_name': 'inbox.xhtml' }, name = 'inbox'),

The inbox view is exactly this:

@login_required()
@ownsBid
def inbox(request, template_name):
    return render_to_response(template_name, context_instance=RequestContext(request))

My ownsBid decorator is:

def ownsBid(fn):
    def _check(request, *args, **kwargs):
        return fn(request, kwargs)

    re开发者_C百科turn _check

When I use:

fn(request, kwargs) 

I get a TemplateDoesNotExist at /alerts/inbox/. If I do instead:

fn(request, kwargs['template_name'])

It renders the template without problems. I don't have a clue why this happens. But if I have to pass a specific parameter to the view, it totally breaks DRY principle of decorators.


Can you try fn(request, **kwargs) instead? Here is a quick illustration:

>>> def foo(template_name):
 print template_name

>>> d = dict(template_name =  'foo/bar.html')
>>> foo(d)
{'template_name': 'foo/bar.html'}
>>> foo(**d)
foo/bar.html
>>> 

So what is happening here? In the first case (foo(d)) you are passing a dictionary as-is to the function. Naturally the value of template_name is then the dictionary object.

In the second case (foo(**d)) you are expanding unpacking the dictionary and passing the keys and values as keyword arguments. The template_name key will become a keyword argument and foo/bar.html will be its value.

0

精彩评论

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