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?
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.
*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.
Django has two types of views; function-based views (FBVs), and class-based views (CBVs).
**kwargs allows you to handle named arguments that you have not defined in advance. In a function call, keyword arguments must follow positional arguments.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With