Search code examples
pythondjangodjango-viewsargskeyword-argument

args and kwargs in django views


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?


Solution

  • 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()