选择一个带有django的随机页面 [英] select an random page with django

查看:105
本文介绍了选择一个带有django的随机页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Django选择随机页面,但是我不知道如何调用该函数.

I'm trying to select a random page with Django but I don't know how to call the function.

我试图用一个URL来调用它,但是没有用.

I tried to call it with an URL but it didn't work.

views.py:

def random_page(request):
    entries = util.list_entries() # list of wikis
    selected_page = random.choice(entries)
    return render(request, "encyclopedia/layout.html", {
        "random_page": selected_page
    })

urls.py:

from . import views
app_name = "encyclopedia"

urlpatterns = [
    path("", views.index, name="index"),
    path("wiki/<str:page_title>", views.wiki_page, name="wiki_page"),
    path("create", views.add_entry, name="add_entry"),
    path("search", views.search, name="search"),
    path("wiki/edit/<str:page_title>", views.edit_page, name="edit_page")
]

layout.html:

{% load static %}

<!DOCTYPE html>

<html lang="en">
    <head>
        <title>{% block title %}{% endblock %}</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
        <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
    </head> 
    <body>
        <h2>Wiki</h2>
        <form action="{% url 'encyclopedia:search' %}" method="POST">
            {% csrf_token %}
            <input class="search" type="text" name="q" placeholder="Search Encyclopedia">
        </form>
            <a href="{% url 'encyclopedia:index' %}">Home</a>
            <a href="{% url 'encyclopedia:add_entry' %}">Create New Page</a> 
            <a href=wiki/{{ random_page }}>Random Page</a>
        {% block body %}
        {% endblock %}
    </body>
</html>

推荐答案

我以这种方式编写了视图

I wrote the view in this way

def random_page(request):
    entries = util.list_entries()
    selected_page = random.choice(entries)
    return HttpResponseRedirect(reverse('wiki', args=[selected_page]))

这篇关于选择一个带有django的随机页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆