Django 将变量传递给模板

Roo*_* DJ 12 html django django-templates django-views

嗨,谢谢你的帮助,我编码很差。

指出:我正在做一个 Django 项目,将数据表单数据库传递给前端;但现在我什至无法将 Django 的任何视图传递到模板中,我怀疑我传递了错误的变量类型;请对您的想法发表评论。

这是我在views.py上的代码:

from django.shortcuts import render

def index (requset):
    return render(requset,'myapp/index.html') # link to be able open frountend

def testdex(requset):
    text = "hello world"
    context ={'mytext' : text }
    return render(requset,'myapp/inculdes.html', context)
Run Code Online (Sandbox Code Playgroud)

所以我的变量将被传递到扩展到索引页的 inculdes

这是我在 inculdes.html 中的代码:

{% exntends "myapp/index.html" %}

{% block includes %}
{{ mytext }}
{% endblock includes %}
Run Code Online (Sandbox Code Playgroud)

这是我在 index.html 上的代码:

<body>
{% block includes %} {% endblock includes %}    
</body>
Run Code Online (Sandbox Code Playgroud)

再次感谢您给我时间来帮助我,如果可以给我写一些代码,我将不胜感激,因为尝试整周解决这个问题

Aja*_*mar 20

你可以试试这样的

视图.py

from django.template.response import TemplateResponse

def testdex(requset, template_name="myapp/inculdes.html"):
    args = {}
    text = "hello world"
    args['mytext'] = text
    return TemplateResponse(request, template_name, args)
Run Code Online (Sandbox Code Playgroud)

inculdes.html

{% extends "myapp/index.html" %}
{% block includes %}
{{ mytext }}
{% endblock includes %}
Run Code Online (Sandbox Code Playgroud)

并确保您在settings.py 中为模板设置了路径


mah*_*f_i 11

当您这样做时,{% block content %}{% endblock content %}您是在告诉 Django 您希望能够覆盖此部分。请注意,内容一词可以是任何反映您要覆盖的内容的内容。

当你这样做时,{{ variable }}你是在告诉 Django 你想要传递一个上下文。在这个例子中,我想传递的变量被称为 Title 作为键和 Portfolio 作为值。Context 是你在views.py 中传递的字典,如下所示:

def portfolio_home(request):
    return render(request, 'portfolio/work.html', {'title': 'Portfolio'})
Run Code Online (Sandbox Code Playgroud)

假设我想将上下文(或变量)传递到我的基本模板中。在这个例子中,我想在我的基本模板的头部部分的标题标签中传递标题。

base.html的 html 文件中,你需要有这样的东西:

<!DOCTYPE html>
<html lang="en">

{% load staticfiles %}

    <head>
        <title>{{ title }}</title>
        ...........
    </head>
</html>
Run Code Online (Sandbox Code Playgroud)

在我的项目和其他应用程序的 urls.py 中,我想将标题传递给它,我应该创建这样的视图:

def portfolio_home(request):
    return render(request, 'portfolio/work.html', {'title': 'Portfolio'})
Run Code Online (Sandbox Code Playgroud)