检查了几个类似的线程后,我仍然无法使其正常工作。我想将一个简单变量从views.py
传递到index.html
模板。但是模板会在前端显示变量'liga1',并且不会传递该变量的值。
这些是我的文件:
views.py
import requests
from django.http import HttpResponse
from django.shortcuts import render
def liga(request):
liga1 = ['1. Bundesliga', 'Premier League', 'La liga']
return render(request, 'dasocc_app/templates/index.html', {'liga1': liga1})
index.html(仅摘要):
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/dasocc_project/styles.css">
<link href="https://fonts.googleapis.com/css?family=Muli&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link rel="shortcut icon" href="images/dasoccfavicon.png"/>
<title>DASPO</title>
</head>
<body>
<div id="outerContainer">
<!-- Sidebar -->
<div id="sidebar">
<header>
<a href="#">{{ liga1 }}</a>
</header>
<ul class="nav">
<li class="countries"><img src="/dasocc_project/images/germany.png" alt="germany">{{ liga1 }}
<ul class="subbar">
urls.py
from django.urls import path
from django.urls import include
urlpatterns = [
path('dasocc_app', include("dasocc_project.urls")),
path('templates/', include('dasocc_app.urls', namespace='dasocc_app'))
]
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dasocc_app',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '/dasocc_project/dasocc_app/templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, '/dasocc_project/dasocc_app/static'),
]
和我的项目结构:
以及相应的前端输出:
出于某种原因,您已将模板添加到urls.py。即使您没有告诉我们要访问的URL,从输出中也可以清楚地看到,您正在直接访问模板地址,而不是访问liga视图提供的URL。
从URL中删除模板,并添加指向liga的URL。