Django - how to create and use context processors / the variables which the context processors return

白昼怎懂夜的黑 提交于 2019-12-25 04:26:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!