gpt4 book ai didi

python - 如何根据 django 中的模型条目创建 URL

转载 作者:太空宇宙 更新时间:2023-11-04 10:22:51 25 4
gpt4 key购买 nike

我在模型城市中有两个字段sourcedestination

我的应用程序名为 uroute。如果用户输入一些详细信息,例如:source>parisdestination> bruxelles

然后需要像这样生成 url:uroute/paristobruxelles

我试过这样的:

在 urls.py 中

urlpatterns = [
url(r'^(?P<source>+'to'+<destination>[A-Z][a-z]+)/$', views.detail, name='detail'),
]

在 views.py 中

def detail(request, source, destination):
return HttpResponse(source+'to'+'destination')

我不知道如何处理 views.py坦率地说,我对 Django 非常天真。我请求有人指导。提前致谢!

最佳答案

正如 Wtower 在评论中指出的那样,您提出的方法有很多您可能会遇到的边缘情况,例如名称中包含 to 的城市等。

如果您希望保留 URL 的 to 语义,则更可持续的方法可能是使用类似 uroute/paris/to/berlin 的内容。

然后它将允许您以以下 url 模式轻松捕获两个城市:

urlpatterns = [    url(r'^(?P<source>[a-zA-Z]+)/to/(?P<destination>[a-zA-Z]+)/$', views.detail, name='detail'),]def detail(request, source, destination):    """    Do something    """

关于python - 如何根据 django 中的模型条目创建 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31243680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com