我需要帮助,因为Django对我来说真的不管用

2024-04-23 21:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我对正在进行的学校项目有意见。当我运行代码并转到我创建的“随机页面”链接时,什么都没有发生。经过一段时间的尝试,我认为问题在于,{{}中的任何东西似乎都找不到。views.py:

from django.shortcuts import render
from django.http import HttpResponse
from . import util
import random

def index(request):
    return render(request, "encyclopedia/index.html", {
        "entries": util.list_entries()
    })
    random_page = random.choice(entries)
def CSS(request):
    return render(request, "encyclopedia/css_tem.html", {
        "article_css": "css is slug and cat"
    })
def Python(request):
    return render(request, "encyclopedia/python_tem.html", {
        "article_python": "python says repost if scav"
    })
def HTML(request):
    return render(request, "encyclopedia/HTML_tem.html", {
        "article_HTML": "game theory: scavs are future humans"
    })
def Git(request):
    return render(request, "encyclopedia/Git_tem.html", {
        "article_Git": "github is git"
    })
def Django(request):
    return render(request, "encyclopedia/Django_tem.html", {
        "article_Django": "this is a framework"
    })

layout.html:

<!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>
        <div class="row">
            <div class="sidebar col-lg-2 col-md-3">
                <h2>Wiki</h2>
                <form>
                    <input class="search" type="text" name="q" placeholder="Search Encyclopedia">
                </form>
                <div>
                    <a href="{% url 'index' %}">Home</a>
                </div>
                <div>
                    Create New Page
                </div>
                <div>
                    <a href = "http://127.0.0.1:8000/{{random_page}}">Random Page</a>
                </div>
                {% block nav %}
                {% endblock %}
            </div>
            <div class="main col-lg-10 col-md-9">
                {% block body %}
                {% endblock %}
            </div>
        </div>

    </body>
</html>

Tags: importdivreturnrequestdefhtmlarticlecol
1条回答
网友
1楼 · 发布于 2024-04-23 21:24:03

您的index()方法return会在选择random_page之前停止,因此代码永远不会运行。文件名与代码不匹配,但实际上需要将随机页面名传递到索引页面的上下文中

视图:

def index(request):
    random_page = random.choice(entries)
    return render(request, "encyclopedia/index.html", {
        "entries": util.list_entries(),
        "random_page": random_page,
    })

“百科全书/index.html”

[...]
 <div>
   <a href = "http://127.0.0.1:8000/{{random_page}}">Random Page</a>
 </div>
[...]

相关问题 更多 >