Django 从地址栏获取 URL



我是 django 的乞丐,我被困在让它工作上,实际上我想要的是用户在地址栏中输入 http://website.com/example 然后在 Django 中我想制作一个动态视图,它检查地址,然后将用户重定向到正确的页面,否则会给出错误。

这就是我正在尝试的,但它可能不起作用。

urlpatterns = [
path("", views.index, name="index"),
path("<str:name>", views.example, name="example") ]

然后在views.py中,我想要以下内容:

def example(request, name):
return render(request, "website/<name> here i want for it to insert what the user typed in the address bar", {
"name": util.get_entry(name)  <-- this is a function which checks if there is that name in the database otherwise will return an error.
})

希望我对这个问题很清楚,并感谢您的帮助:)

我不完全确定你想在这里做什么,但我认为你正在尝试传入一个字符串作为参数。在这种情况下,您可以执行以下操作:

def example(request, name):
#perform some logic with the name parameter like querying the database
# results = Post.objects.filter(body__contains=name)
return render(request, "blog/post.html", {"results": results})

然后,您可以在指定的模板中访问"结果":"blog/post.html"。 我希望这有帮助!

最新更新