[Fixed]-Args and kwargs in django views

16👍

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

6👍

*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;

5👍

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

👤César

Leave a comment