I want to put a login form everywhere in my webpage so I added a context_processor and I included it in base.html file. The problem now is I cannot see the form.
Here is my context_processors.py:
def global_login_form(request):
if request.method == 'POST':
formLogin = LoginForm(data=request.POST)
if formLogin.is_valid():
from django.contrib.auth import login
login(request, formLogin.get_user())
...
else:
formLogin = LoginForm()
return {'formLogin': formLogin}
And here are the diferents htmls I tried in base.html trying to invoke the form:
<form action="/myapp/login/" method="post">
{% csrf_token %}
{{global_login_form}}
</form>
<form action="/myapp/login/" method="post">
{% csrf_token %}
{{global_login_form.as_p}}
</form>
<form action="/myapp/login/" method="post">
{% csrf_token %}
{{request.formLogin}}
</form>
first time I load the page, the context_process returns {'formLogin': formLogin} (cause formLogin is LoginForm()) but I cannot see the form while inspecting the html. It is not there... but I can see the csrf_token so I think I'm not invoking the context properly.
Just it case (maybe the order is incorrect), here is settings.py:
TEMPLATE_CONTEXT_PROCESSORS = (
"myapp.context_processors.global_login_form",
"django.core.context_processors.request",
"django.contrib.auth.context_processors.auth",
)
Any ideas?
I believe OP has incorrectly assumed that the template context variable is going to match the function name of the context processor.
OP's context processor global_login_form() injects formLogin to the template context. Therefore, in the templates the form should be referenced as, for example, {{ formLogin.as_p }}.
you must have the form variable in every views, or you should implement a templatetag instead. example:
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags
from django import template
from django.contrib.auth.forms import AuthenticationForm
register = template.Library()
@register.inclusion_tag('registration/login.html', takes_context=True)
def login(context):
"""
the login form
{% load login %}{% login %}
"""
request = context.get('request', None)
if not request:
return
if request.user.is_authenticated():
return dict(formLogin=AuthenticationForm())
return dict(user=request.user)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With