Django - 如何创建和使用上下文处理器/上下文处理器返回的变量

时间:2014-01-15 23:57:59

标签: django django-templates django-views processors

与我一起

settings.py

urls.py

文件,我创建了一个

context_processors.py

文件位于同一目录中。这是我的context_processors.py文件:

from django.contrib.auth.forms import AuthenticationForm

def loginFormCustom(request):
    form = AuthenticationForm()
    return {'loginForm': form,} 

这是我的views.py:

from django.template import RequestContext
from tp.context_processors import loginFormCustom

def main_page(request):

    variables = { 'title': 'This is the title of the page' }
    return render(request, 'main_page.html', variables, context_instance=RequestContext(request, processors = loginFormCustom))

现在,当我运行它并转到调用main_page视图的URL时,它会在/说出一个TypeError:

'function' object is not iterable

并且追溯导致了这个:

return render(request, 'main_page.html', variables, context_instance=RequestContext(request, processors = loginFormCustom))

任何想法为什么?我是否正确使用了上下文处理器?

1 个答案:

答案 0 :(得分:2)

Django Docs说AuthenticationForm就是这样,它是一个Form,所以我相信你需要以这种方式调用它:

from django.template import RequestContext
from django.contrib.auth.forms import AuthenticationForm

def main_page(request):
  if request.method == 'POST':
    form = AuthenticationForm(request.POST)
    # log in user, etc...
  else:
    form = AuthenticationForm()  # Unbound Form

  return render(request, 'main_page.html', context_instance=RequestContext(request, {'form': AuthenticationForm}))