问题
Along with my
settings.py
and
urls.py
file, I created a
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,}
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))
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
and the traceback leads to this:
return render(request, 'main_page.html', variables, context_instance=RequestContext(request, processors = loginFormCustom))
any idea why? Am I using the context processor correctly?
回答1:
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}))
来源:https://stackoverflow.com/questions/21150834/django-how-to-create-and-use-context-processors-the-variables-which-the-cont