Django - 如何创建和使用上下文处理器/上下文处理器返回的变量 [英] Django - how to create and use context processors / the variables which the context processors return
本文介绍了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}))
这篇关于Django - 如何创建和使用上下文处理器/上下文处理器返回的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文