Reputation: 3667
I feel like a heel asking this because I'm sure the answer is simple. Nevertheless I've spent hours researching and testing possible solutions and I have been left hairless.
In the project harmony I have written my own login page and it resides in an app called users.
I have another app called your_harmony. To proceed beyond the your_harmony page, users need to login.
your_harmony.html
{% if user.is_authenticated %}
<h1>{{ self.sub_title|richtext }}</h1>
You are logged in as: {{ user.username }}  
<a href="/users/logout">Click here to logout</a>
...
{% else %}
You must login to access this page. <a href="/users/login">Click here to login</a>
{% endif %}
harmony.urls
urlpatterns = [
...
url(r'your-harmony/', include('your_harmony.urls')),
url(r'^users/', include('users.urls')),
...
your_harmony.urls
urlpatterns = [
path('', views.your_harmony, name='your_harmony')
]
The url /users/login uses users/views.py to display the login form
views.py
RETURN_FROM_LOGIN_URL = 'your-harmony'
RETURN_FROM_LOGIN_URL = 'your_harmony/your_harmony.html'
def login_view(request):
form_context = {'login_form': LoginForm,}
url = "users/login.html"
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
url = RETURN_FROM_LOGIN_URL
else:
messages.error(request, 'Your account is not enabled!')
context = {}
else:
messages.error(request, 'Your username or password was not recognized!')
context = form_context
else:
context = form_context
return render(request, url, context)
if I return to 'your-harmony' get the error
TemplateDoesNotExist at /users/login/
your-harmony
If I return to 'your_harmony/your_harmony.html' I get the page but no context.
How should I sort this?
Upvotes: 0
Views: 445
Reputation: 3667
Following @gasman's advice, I have revisited the Django Tutorials. As Tutorial Part 4 states:
you should always return an HttpResponseRedirect after successfully dealing with POST data. This tip isn’t specific to Django; it’s good Web development practice in general
So I have changed the code to include this return and replaced the template path with a URL conf.
views.py
RETURN_FROM_LOGIN_URL = 'your_harmony'
def login_view(request):
form_context = {'login_form': LoginForm,}
url = "users/login.html"
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(reverse(RETURN_FROM_LOGIN_URL))
else:
messages.error(request, 'Your account is not enabled!')
context = {}
else:
messages.error(request, 'Your username or password was not recognized!')
context = form_context
else:
context = form_context
return render(request, url, context)
Learned a lot and worth the effort
Upvotes: 1