我正在尝试在我的django项目中实现模板标记,而且我是一个关键错误。我认为这与在load_menu.py下的模板标记中获取上下文有关。
Exception Type: KeyError
Exception Value:'request'
Error during template rendering
In template C:\Users\Eric Franzen\PycharmProjects\MySite\templates\app\TikSys\tiksys_home.html, error at line 0
request
1 {% extends 'app/TikSys/tiksysbase.html' %}
2 {% block content %}
3 <div class="body-container">
4 {% include "app/TikSys/sidenavbar.html" %}
5 <div class="col-md-10 ">
6 <div class="jumbotron">
7 <h1>Welcome to TikSys!</h1>
8 <p>Please Sign In</p>
9 </div>
10 </div>
回溯
...
File "C:\Users\Eric Franzen\PycharmProjects\MySite\Site\views.py", line 43, in tiksys_home
return render(request, 'app/TikSys/tiksys_home.html', {})
...
File "C:\Users\Eric Franzen\PycharmProjects\MySite\Site\templatetags\load_menu.py", line 10, in menu
request = context['request']
网站/ templatetags / load_menu.py
from django import template
from Site.models import *
register = template.Library()
@register.inclusion_tag('app/TikSys/sidenavbar.html', takes_context=True)
def menu(context):
request = context['request']
um = UserMunicipal.objects.filter(userID=request.user).values('municipalID')
m = Municipal.objects.filter(id=um)
return {'menus': m}
应用/ TikSys / sidenavbar.html
<div class="col-md-2 NavBar">
{% load load_menu %}
{% menu %}
{% for item in menus %}
<ul class="nav nav-pills nav-stacked">
<li>{{ item.name }} </li>
</ul>
{% endfor %}
</div>
views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.template import Context, loader
from django.views.generic import TemplateView
from Site.forms import UserForm, UserProfileForm
from django.http import *
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth import get_user_model
from .models import Notification, UserMunicipal, Municipal
@login_required(login_url='/login/')
def tiksys_home(request):
return render(request, 'app/TikSys/tiksys_home.html', {})
答案 0 :(得分:1)
您正在加载标记,在呈现标记的同一模板中。这就是为什么没有上下文了。
标记呈现app/TikSys/sidenavbar.html
的模板应该只有:
<div class="col-md-2 NavBar">
{% for item in menus %}
<ul class="nav nav-pills nav-stacked">
<li>{{ item.name }} </li>
</ul>
{% endfor %}
</div>
在主模板(您需要菜单的位置)中,添加 - 在顶部{% load load_menu %}
,然后添加您想要菜单的位置,添加{% menu %}
,如下所示:
{% load load_menu %}
{% extends 'app/TikSys/tiksysbase.html' %}
{% block content %}
<div class="body-container">
{% menu %}
<div class="col-md-10 ">
<div class="jumbotron">
<h1>Welcome to TikSys!</h1>
<p>Please Sign In</p>
</div>
</div>