简体   繁体   English

关键字参数

[英]Keyword arguments

I am trying different types of views for practice and I am getting following error message in Django 1.5:- 我正在尝试不同类型的视图进行练习,并且在Django 1.5中收到以下错误消息:-

context = super(HelloTemplate, self).get_context_data(**kwargs)
NameError: global name 'kwargs' is not defined.

My urls.py for project: 我的项目的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()),
    )

My Views.py: - 我的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

Because the parameter in get_context_data is named kwarg and you're referring to it by kwargs (in plural). 因为get_context_data的参数名为kwarg ,所以您使用kwargs (以复数形式)引用它。

I suggest you to use kwargs in plural since is more standard :) 我建议您使用kwargs复数形式,因为它比较标准 :)

Replace : 更换:

def get_context_data(self, **kwarg):
    context = super(HelloTemplate, self).get_context_data(**kwargs)
    context['name'] = 'Mudassar'
    return context

With : 与:

def get_context_data(self, **kwargs):
    context = super(HelloTemplate, self).get_context_data(**kwargs)
    context['name'] = 'Mudassar'
    return context

:) :P :):P

You have to use same variable you are passing. 您必须使用要传递的相同变量。

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

If you want to use kwargs then pass kwargs if you want to use kwarg then pass same in super. 如果要使用kwargs则传递kwargs如果要使用kwarg则在super中传递相同的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM