Sidd
Sidd

Reputation: 1208

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?

Upvotes: 16

Views: 27008

Answers (3)

Rishi Chhabra
Rishi Chhabra

Reputation: 101

*args and **kwargs are used to pass a variable number of arguments to a function. Single asterisk is used for non-keyworded arguments and double for keyworded argument.

For example:

    def any_funtion(*args, **kwargs):
         //some code

    any_function(1,arg1="hey",arg2="bro")

In this, the first one is a simple (non-keyworded) argument and the other two are keyworded arguments;

Upvotes: 6

Hedde van der Heide
Hedde van der Heide

Reputation: 22439

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

Upvotes: 16

César
César

Reputation: 10119

The problem is that locals() returns a dictionary. If you want to use **kwargs you will need to unpack locals:

response = someview(request,**locals())

When you use it like response = someview(request,locals()) you are in fact passing a dictionary as an argument:

response = someview(request, {'a': 1, 'b': 2, ..})

But when you use **locals() you are using it like this:

response = someview(request, a=1, b=2, ..})

You might want to take a look at Unpacking Argument Lists

Upvotes: 5

Related Questions