Learning Django by Example(4): First user authenticated

In the last post, we succeeded to update the database, in this post we would add more functionalities to the view of normal users.

In r23, I re-organize the file directory in the repository, media is added to the repository for your convenience.

Though Gelman is designed for personal use, the multi-user functionality is added just in case you want to share you collection with family members and friends later.The built-in authentication is quite neat, if you deploy Gelman into an enterprise environment, you may consider this. Now, just follow the documentation, and add the very first reader to Gelman by running python manage.py shell:

>>> from django.contrib.auth.models import User
>>> u = User.objects.create_user('python', '', 'spam')
>>> u.save()

Now, let’s build the gateway for the user to login. Copy the basic login form in the doc to templates/login.html, The default success login action is to redirect to user’s profile, we may override it to the index first:

add the URL mapping in urls.py:

(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html', }),
(r'^accounts/logout/$', 'gelman.library.views.logout_view', ),

For logout action, just logout the user and redirect the user to the front page, in library/views.py:

def logout_view(request):
    return HttpResponseRedirect('/library')

We would greet the users in the top-left corner of the page just as Wordpress’s dashboard does. Add the following code snippet to base_generic.html:

{% if user.is_authenticated %}
    Howdy, {{ user.username }} [<a href="/accounts/logout">Logout</a>, <a href="/accounts/profile">My Profile</a>]
{% else %}
    [<a href="/accounts/login">Login</a> or <a href="/accounts/register">Register</a>]
{% endif %}

as the following(left: logged-in user, right: logged-out user):

Login and Logout demo
Login and Logout demo

Check out r25 for the implementation details.