我在调度程序中有两个 url 指向相同的 View
path('posts/top/', posts, name='top'),
path('posts/new/', posts, name='new'),
我希望 View 开始如下:
def posts(request, ordering):
...
我想,通过
top
和 new
作为参数,它应该是这样的:path('posts/<ordering:top>/', posts, name='top'),
path('posts/<ordering:new>/', posts, name='new'),
但它给了我:
django.core.exceptions.ImproperlyConfigured: URL route 'posts/<ordering:top>/' uses invalid converter 'ordering'.
所以,作为一种解决方法,我使用它,但它看起来有点脏:
path('posts/top/', posts, name='top', kwargs={'order': 'top'}),
path('posts/new/', posts, name='new', kwargs={'order': 'top'}),
正确的做法是什么?
最佳答案
您误解了路径转换器的工作方式。第一个元素是类型,这里是 str
,第二个是调用 View 时使用的参数名称。在这一点上,您不限制允许的值本身。所以你的路径是:
path('posts/<str:ordering>/', posts, name='posts')
当你反转时,你会传入相关参数:
{% url 'posts' ordering='top' %}
如果你真的想确保人们只能传递这两个值,你可以在 View 中以编程方式检查它,或者你可以使用
re_path
在您的路径中使用正则表达式:re_path(r'^posts/(?P<ordering>top|new)/$', posts, name='posts')
关于Django 将已知的确切字符串作为 url 参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51420143/