我正在为练习尝试不同类型的视图,我在Django 1.5中收到以下错误消息: -
context = super(HelloTemplate, self).get_context_data(**kwargs)
NameError: global name 'kwargs' is not defined.
我的urls.py项目:
urlpatterns = patterns('',
url(r'^hello/$', 'article.views.hello'),
url(r'^hello_template/$', 'article.views.hello_template'),
url(r'^hello_template_simple/$', 'article.views.hello_template_simple'),
url(r'^hello_class_view/$', HelloTemplate.as_view()),
)
我的Views.py: -
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
from django.shortcuts import render_to_response
from django.views.generic.base import TemplateView
def hello(request):
name = 'Mudassar'
html = "<html><body>Hi %s, this seems to worked!</body></html>" % name
return HttpResponse(html)
def hello_template(request):
name = 'Mudassar'
t = get_template('hello.html')
html = t.render(Context({'name': name}))
return HttpResponse(html)
def hello_template_simple(request):
name = 'Mudassar'
return render_to_response('hello.html', {'name':name})
class HelloTemplate(TemplateView):
template_name = 'hello_class.html'
def get_context_data(self, **kwarg):
context = super(HelloTemplate, self).get_context_data(**kwargs)
context['name'] = 'Mudassar'
return context
答案 0 :(得分:4)
因为get_context_data
中的参数名为kwarg
,而您引用kwargs
(复数形式)。
我建议您使用kwargs
复数{{1}}:{/ p>
答案 1 :(得分:2)
替换:
def get_context_data(self, **kwarg):
context = super(HelloTemplate, self).get_context_data(**kwargs)
context['name'] = 'Mudassar'
return context
使用:
def get_context_data(self, **kwargs):
context = super(HelloTemplate, self).get_context_data(**kwargs)
context['name'] = 'Mudassar'
return context
:):P
答案 2 :(得分:0)
您必须使用传递的相同变量。
class HelloTemplate(TemplateView):
template_name = 'hello_class.html'
def get_context_data(self, **kwargs):
context = super(HelloTemplate, self).get_context_data(**kwargs)
context['name'] = 'Mudassar'
return context
如果您想使用kwargs
,请传递kwargs
,如果您想使用kwarg
,请在超级传递相同内容。