16

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?

Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100
Sidd
  • 1,168
  • 2
  • 10
  • 27

3 Answers3

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

Hedde van der Heide
  • 21,841
  • 13
  • 71
  • 100
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;

Rishi Chhabra
  • 101
  • 1
  • 3
  • Hey Rishi! Could you use code formatting in your answer to make it more readable? Just put three ` symbols and three ` symbols after your code! :) – Luca Schimweg May 19 '20 at 12:18
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
  • 9,939
  • 6
  • 53
  • 74