args and kwargs in django views

Sidd picture Sidd · Dec 20, 2012 · Viewed 17.9k times · Source

Okay, I've tried searching for this for quite some time. Can I not pass args and kwargs to a view in a django app? Do I necessarily have to define each keyword argument independently?

For example,

#views.py
def someview(request, *args, **kwargs):
...

And while calling the view,

response = someview(request,locals())

I can't seem to be able to do that. Instead, I have to do:

#views.py
def someview(request, somekey = None):
...

Any reasons why?

Answer

Hedde van der Heide picture Hedde van der Heide · Dec 20, 2012

If it's keyword arguments you want to pass into your view, the proper syntax is:

def view(request, *args, **kwargs):
    pass

my_kwargs = dict(
    hello='world',
    star='wars'
)

response = view(request, **my_kwargs)

thus, if locals() are keyword arguments, you pass in **locals(). I personally wouldn't use something implicit like locals()