以下 url 定义应该传递 results/
是否存在于 url 中:
url(r'^(?P<question_id>[0-9]+)/(?P<results>(results/)?)shorten/$', views.shorten, name='shorten')
目前它传递 results/
或 None
这对于一个简单的来说已经足够了:
if results:
pass
但如果有 True
和 False
会更优雅。这是怎么做到的?
最佳答案
您可以有两个 URL 模式并在 kwargs 中传递 results
:
url(r'^(?P<question_id>[0-9]+)/results/shorten/$', views.shorten, {'results': True}, name='shorten'),
url(r'^(?P<question_id>[0-9]+)/shorten/$', views.shorten, {'results': False}, name='shorten'),
如果您不想这样做,那么目前没有一种简单的方法可以将 results
字符串转换为 bool 值。您可以编写一个中间件或装饰器,但那样做就太过分了。
关于python - 在 url 调度中存储 bool 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43708788/