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

问题描述:

随着我的

settings.py

urls.py

文件,我创建了一个

context_processors.py

文件。这是我的context_processors.py文件:

file in the same directory. This is my context_processors.py file:

from django.contrib.auth.forms import AuthenticationForm

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

这是我的views.py:

and this is my 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在/说:

Now, when I run this and go to The URL which calls the main_page view, it gives me a TypeError at / saying:

'function' object is not iterable

,追溯导致:

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

任何想法为什么?我正在使用上下文处理器吗?

any idea why? Am I using the context processor correctly?

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

The Django Docs say that the AuthenticationForm is just that, it is a Form, so I believe that you would need to call it in this way:

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}))