python - 如何使用 Django 将 View 变量传递给模板

标签 python django django-templates django-views

检查了几个类似的线程后,我仍然无法让它工作。我想将一个简单的变量从 views.py 传递到我的 index.html 模板。但模板显示变量“liga1”,因为它在前端,并且变量的值未传递。

这些是我的文件:

views.py

import requests
from django.shortcuts import render
import json

# Render different pages


def render_landing_page(request, template="index.html"):
    liga = ['1. Bundesliga', 'Premier League', 'La liga']
    return render(request, template, {'liga': liga})

index.html(仅一个片段):

    <!-- Sidebar -->

    <div id="sidebar">
      <header>
        <a href="#">Dasocc</a>
      </header>
      <ul class="nav">
        <li class="countries"><img src="{% static "images/germany.png" %}" alt="germany">{{ liga }}

urls.py//项目目录

from dasocc_app import views
from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^$', views.render_landing_page, name='landing_page'),
    url(r'^$', views.liga, name='liga'),
    url(r'^dasocc-app/', include('dasocc_app.urls')),
    url(r'admin/', admin.site.urls),
]

urls.py//应用目录

from django.conf.urls import url
from dasocc_app import views

urlpatterns = [
    #Where home is some random view from your dassocc-app
    url(r'^$', views.liga, name='liga')
    ]

index.html 模板中的 {{ liga }} 变量前端没有 html 输出:

enter image description here

相关项目结构:

enter image description here

最佳答案

出于某种原因,您已将模板添加到 urls.py 中。尽管您没有告诉我们您要访问哪个 URL,但从输出中可以清楚地看出您正在直接访问模板地址,而不是访问 liga View 提供的 URL。

从您的网址中删除模板并添加指向liga的网址。

关于python - 如何使用 Django 将 View 变量传递给模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58146117/

相关文章:

python - 如何添加默认路径以在其中查找 python 脚本文件?

Django REST Framework : how to make Id field required upon POST, 即非只读字段?

python - 切换到 django-pytest 后,我​​还能使用 `manage.py test` 吗?

python - Django 1.9 : Add a custom button to run a python script on clicking in admin site of a app/model

django-templates - Django 的 Twig

python - Django+ Bootstrap : concatentating bootstrap_alert

python - 应用引擎 : sub folder in templates

python - csv中的字符串替换

python - 计算组分离后的列平均值

python - 如何获取 Django 模型字段对象的值