首页 > 解决方案 > 无法在 django 中使用变量

问题描述

我最近开始了我的 django 在线课程,但遇到了一些问题。我无法使用从 index.html 传递到 about.html 的变量。但在 about.html 中没有显示出来。

.py 文件代码:

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

def index(request):
    return render(request , 'index.html')

def about(request):
    t1 = print(request.GET.get('text' , 'default'))
    return render(request , 'about.html' , t1)

index.html 文件代码:

<!DOCTYPE html>
<html>
<head>
    <title>template</title>
</head>
<body>
<h1> hello everyone </h1>
<form action="/about" , method="get">
    <textarea name="text" style="margin: 0px; width: 1245px; height: 171px;"></textarea>

    <input type="submit" name="OK">

</form>
</body>
</html>

about.html 文件代码:

<!DOCTYPE html>
<html>
<head>
    <title>template</title>
</head>
<body>
 <h1>you typed {{t1}}</h1>
</form>
</body>
</html>

标签: django

解决方案


print(..)不返回任何东西您可以将变量传递给上下文,例如:

def about(request):
    return render(
        request ,
        'about.html' ,
        {'t1': request.GET.get('text' , 'default')}
    )

推荐阅读