首页 > 解决方案 > 格式化 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)

使用 display_entry 时 URL 正确显示

下面是一个随机函数,它返回一个条目,但 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)

使用 random_entry() 时 URL 无法正确显示

最后,我的 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_entrywiki/<str:entry>/但这会产生更多问题。

随意评论我的代码,而不必给我答案。

亲切的问候,

一个

标签: pythonhtmldjango

解决方案


如果您希望 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)

推荐阅读