python - 格式化 URL 的正确 python/django 方式是什么?
问题描述
各位程序员好,
我正在为 cs50w 课程开发一个网络应用程序,并且我的代码几乎可以正常运行,但是,我注意到当我使用特定功能时,URL 无法正确显示。
下面是一个返回条目并正确显示 URL 的函数:
def display_entry(request, entry):
entrykey = util.get_entry(entry)
markdowner = Markdown()
context = {'entry': markdowner.convert(entrykey)}
context.update({'title':entry})
context.update({'content': entrykey})
return render(request, "encyclopedia/entry.html", context)
下面是一个随机函数,它返回一个条目,但 URL 不是它应该是的......
def random_entry(request):
# retrieves a list of the entries
entries = util.list_entries()
entry = random.choice(entries)
# retrives a the content of a random entry
entrykey = util.get_entry(entry)
# formats the random entry for display and returns the content to page
markdowner = Markdown()
context = {'entry': markdowner.convert(entrykey)}
context.update({'title':entry})
context.update({'content': entrykey})
return render(request, "encyclopedia/entry.html", context)
最后,我的 URL 模式...
urlpatterns = [
path("", views.index, name="index"),
path("create", views.create, name="create"),
path("edit", views.edit_entry, name="edit_entry"),
path("save", views.save_entry, name="save_entry"),
path("search", views.search_entry, name="search_entry"),
path("wiki/<str:entry>/", views.display_entry, name="view_entry"),
path("random_entry", views.random_entry, name="random_entry"),
]
我尝试将其更改为random_entry
,wiki/<str:entry>/
但这会产生更多问题。
随意评论我的代码,而不必给我答案。
亲切的问候,
一个
解决方案
如果您希望 url 更改为随机条目的正确 url,您不想呈现页面。相反,您希望通过返回状态码为 302 的响应将用户重定向到正确的页面。您可以使用redirect
快捷功能很容易地做到这一点:
from django.shortcuts import redirect
def random_entry(request):
entries = util.list_entries()
entry = random.choice(entries)
return redirect('view_entry', entry=entry)
推荐阅读
- db2 - 如何在 DB2 中编写存储过程
- bash - Gnuplot:通过读取列标题从不同目录的 *txt 文件中绘图
- image - Java FX-8。如何使用 fxml 文件配置本地图像的路径
- javascript - 溢出引起的奇怪滚动效果:hidden on body, html
- animation - SVG rect 动画方向从下到上
- mongodb - Nifi putMongo upsert 示例
- visual-studio-code - 从 Visual Studio Code 将 Vue.js 应用程序部署为 Azure 应用程序服务
- android - phonegap 应用程序在 Android 9 Pie 上没有网络连接,但在 Android 8 (Oreo) 上工作
- laravel - alert-dismissible 不关闭 wen 点击关闭按钮 bootstrap laravel
- php - 排除 foreach 计数中的所有 0