Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 604
Sidd Avatar asked Dec 20 '12 17:12

Sidd


People also ask

How do you use args in Django?

In Python, *args is used to pass an arbitrary number of arguments to a function. It's worth mentioning that the single asterisk( * ) is the most important element, the word arg is just a naming convention we can name it anything it will work as long as we have a ( * ) before it.

What does * args and * Kwargs mean?

*args specifies the number of non-keyworded arguments that can be passed and the operations that can be performed on the function in Python whereas **kwargs is a variable number of keyworded arguments that can be passed to a function that can perform dictionary operations.

Which are the two basic categories of views in Django?

Django has two types of views; function-based views (FBVs), and class-based views (CBVs).

What is Kwargs Django?

**kwargs allows you to handle named arguments that you have not defined in advance. In a function call, keyword arguments must follow positional arguments.


1 Answers

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

like image 164
Hedde van der Heide Avatar answered Sep 28 '22 02:09

Hedde van der Heide