如何将变量从Django视图传递到模板

时间:2019-07-10 07:50:36

标签: python django

我想将一个变量从views.py传递给home.html。 我尽力了,对django还是陌生的。

它不会给出任何错误,但也不会显示该变量。 我可能在url.py或settings.py

中犯了错误

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'project1'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'project1.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'project1.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

urls.py

from django.contrib import admin
from django.urls import path, include
from django.views.generic.base import TemplateView
from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='home.html'), name='home'),
]

views.py

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

def index(request):
    name = "kiran"
    key = 123
    context = {
        'name': name,
        'key': key,
    }
    return render(request, 'templates/home.html', context)

home.html

<h>hello</h>
<h3>{{key}}</h3>

页面虽然显示问候,但没有显示{{key}} 这只是尝试尝试是否有效,但不适用于我。

3 个答案:

答案 0 :(得分:1)

您以错误的方式传递了templates,并且使基于类的视图与基于函数的视图相混淆。

  

urls.py

from project1.views import index

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index, name='home'),
]

,然后在视图中只需通过'home.html'

  

views.py

from django.shortcuts import render

def index(request):
    name = "kiran"
    key = 123
    context = {
        'name': name,
        'key': key,
    }
    return render(request, 'home.html', context)

现在应该可以正常工作了。

答案 1 :(得分:0)

替换

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', TemplateView.as_view(template_name='home.html'), name='home'),
]

使用

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.index, name='home'),
]

您的代码大部分是正确的,但是URL并未调用您的视图函数(在您的情况下为index)。它使用带有home.html模板的基于类的视图。

答案 2 :(得分:0)

问题可能出在您导入的方式上 尝试导入诸如from project1 import views之类的视图,然后将此path('', TemplateView.as_view(template_name='home.html'), name='home')更改为path('', views.index, name='home')