I have a base.html file that makes the template of my site, within that template I use a variable to set a message which I want to show in every view (as an example). That work fine if I can render the view within my views.py. But the login page is “rendered” directly from the urls.py file in the users app, using
views.LoginView.as_view
However I want the message to appear even in the login page.
Below are the minimum files to show the problem (all imports are resolved and it works)
base.html with the {{ message }}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
{% load static %}
</head>
<body>
<div id="message">
<p>{{ message }}</p>
</div>
{% block content %}
{% endblock %}
</body>
</html>
This works fine in my main app of the site where
url.py
urlpatterns = [
path('', views.index, name='index'),
]
views.py here I set message
def index(request):
message=”have a nice day today”
return render(request, 'index.html', {'message': message} )
index.html
{% extends 'base.html' %}
{% block content %}
<div >
<h2>You're welcome</h2>
</div>
{% endblock %}
Now my login page uses the same base.html and looks something like this
login.html
{% extends 'base.html' %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
</form>
{% endblock %}
and my users app urls.py
urlpatterns = [
path('login/', views.LoginView.as_view(template_name="/login.html"), name='login'),
]
Problem is that the message variable isn’t initialized and therefore not shown.
How can I generate the correct LoginView AND set the message variable?
I have tried to make a new class, with only three lines:
views.py
def myloginview(LoginView)
message=”please login”
template_name="/login.html"
and the urls.py
urlpatterns = [
path('login/', views.myloginview, name='login'),
]
as a start (hoping I could set the variable that way) but that gave me an error that no httpResonse or None (*1) was returned.
(*1) sorry forgot the exact error, have set everything back to the original state.
Any ideas? Thanks.