[Fixed]-Args and kwargs in django views


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

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

my_kwargs = dict(

response = view(request, **my_kwargs)

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


*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


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


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


Leave a comment