【问题标题】:Store boolean variable in url dispatching在 url 调度中存储布尔变量
【发布时间】:2017-09-28 06:13:47
【问题描述】:

以下 url 定义应该传递results/ 是否存在于 url 中:

url(r'^(?P<question_id>[0-9]+)/(?P<results>(results/)?)shorten/$', views.shorten, name='shorten')

目前它通过results/None 这对于一个简单的来说已经足够了:

if results:
    pass

但是拥有TrueFalse 会更优雅。这怎么可能?

【问题讨论】:

    标签: python regex django url


    【解决方案1】:

    您可以有两个 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 字符串转换为布尔值。您可以编写一个中间件或装饰器,但这将是矫枉过正。

    【讨论】:

    • 如果您传入带有TrueFalse 值的results 参数,您实际上可以反转两个具有相同名称的模式。它compares additional arguments to the defaults 并且仅在值匹配时才匹配模式。
    • @knbk 感谢您的解释和代码链接。我已将答案更改为对两种模式使用相同的名称。
    • @knbk 你能举个例子来说明如何反转模式吗?
    • @R3turnz 你只需传入 results kwarg 并使用适当的值:reverse('shorten', kwargs={'question_id': 1, 'results': True}){% url 'shorten' question_id=1 results=True %}
    猜你喜欢
    • 2014-04-26
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 2015-06-26
    相关资源
    最近更新 更多