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?
好吧,我已经尝试了很长一段时间。我不能将args和kwargs传递到django应用程序中的视图吗?我是否必须独立定义每个关键字参数?
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?
有什么原因吗?
2 个解决方案
#1
7
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()
因此,如果locals()是关键字参数,则传入** locals()。我个人不会使用像本地人那样隐含的东西()
#2
3
The problem is that locals()
returns a dictionary. If you want to use **kwargs
you will need to unpack locals
:
问题是locals()返回一个字典。如果你想使用** kwargs,你需要解压当地人:
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,locals())时,你实际上是将字典作为参数传递:
response = someview(request, {'a': 1, 'b': 2, ..})
But when you use **locals()
you are using it like this:
但是当你使用** locals()时,你正在使用它:
response = someview(request, a=1, b=2, ..})
You might want to take a look at Unpacking Argument Lists
您可能需要查看解压缩参数列表
#1
7
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()
因此,如果locals()是关键字参数,则传入** locals()。我个人不会使用像本地人那样隐含的东西()
#2
3
The problem is that locals()
returns a dictionary. If you want to use **kwargs
you will need to unpack locals
:
问题是locals()返回一个字典。如果你想使用** kwargs,你需要解压当地人:
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,locals())时,你实际上是将字典作为参数传递:
response = someview(request, {'a': 1, 'b': 2, ..})
But when you use **locals()
you are using it like this:
但是当你使用** locals()时,你正在使用它:
response = someview(request, a=1, b=2, ..})
You might want to take a look at Unpacking Argument Lists
您可能需要查看解压缩参数列表