Skip to main content
 首页 » 编程设计

python之关键字参数

2025年05月04日16findumars

我正在尝试不同类型的 View 进行练习,但在 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()), 
    ) 

我的观点.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 

请您参考如下方法:

因为 get_context_data 中的参数名为 kwarg 并且您通过 kwargs(复数形式)引用它。

我建议你使用复数形式的 kwargs 因为 is more standard :)