login user
Date: March 23rd 2016
Last updated: March 23rd 2016
Creating user login follows on from register users.
urls.py
When the user enters /login/ into the webbrowser the login_user method is called.
from django.conf.urls import url
from . import views
app_name = 'surferprofile'
urlpatterns = [
url(r'^login/$', views.login_user, name='login'),
]
views.py
The first thing that happens is the logout of an existing user (if there is one). This method makes a request for login.html. When the html form is submitted the user is redirected to the user index page (currently found at '/').
def login_user(request):
logout(request)
username = password = ''
if request.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('/')
return render_to_response('surferprofile/login.html', context_instance=RequestContext(request))
Update to base.html
This update to base.html is not essential. I have been extending html templates to remove duplication. I include it here to show that things are working as they should. For more information on how to remove duplication in html templates refer to refactor html templates using base.html.
<div class="headermenu">
Welcome, {{ user.username }}
</div>
login.html
<h1>Log in</h1>
<form action="/login/" method="post">
{% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
username:
<input type="text" name="username" value="{{ username }}" /><br />
password:
<input type="password" name="password" value="" /><br />
{% csrf_token %}
<button type="submit">Submit</button>
</form>
http://127.0.0.1:8080/ (via redirect)
Note the Welcome text in the header region (i.e. Welcome, duck). The header was created in base.html and extended for the index page.