Django 将变量传递给模板 [英] Django pass variable into template

查看:31
本文介绍了Django 将变量传递给模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谢谢你的帮助,我编码很差.

Hi thank you for helping, I'm poor in coding.

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

To point: I'm doing a Django project that pass data form data-base to front-end; but right now i can't even pass anything views of Django into templates, I suspect i'm passing the wrong variable types; please do comment on your thought.

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

This is my code on 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)

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

so my variable will be pass into inculdes where extend to index page

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

This my codes on in inculdes.html:

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

{% block includes %}
{{ mytext }}
{% endblock includes %}

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

this my code on index.html:

<body>
{% block includes %} {% endblock includes %}    
</body>

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

Thanks again on giving me your time to help me and appreciate it if could write me some code because try fix this for whole week

推荐答案

你可以试试这样的

views.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)

inculdes.html

{% extends "myapp/index.html" %}
{% block includes %}
{{ mytext }}
{% endblock includes %}

并确保您在 settings.py

And make sure you have set path for templates in settings.py

这篇关于Django 将变量传递给模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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