If you just want to have a homepage with static content that handles logins, the Django built-in auth application can handle this with very little effort. You just need to bind a URL to django.contrib.auth.views.login
and probably one to django.contrib.auth.views.logout
, write a login template and a post-logout template, then set a couple of setting variables.
The full setup is documented here:
https://docs.djangoproject.com/en/dev/topics/auth/default/#module-django.contrib.auth.views
Here are the relevant bits from a working project of mine:
urls.py
# HomeView is a simple TemplateView that displays post-login options
urlpatterns = patterns('',
...
url(r'^myapp/$', HomeView.as_view(template_name='home.html'), name='home'),
url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='login'),
url(r'^accounts/logout/$', 'django.contrib.auth.views.logout', name='logout'),
...
)
settings.py
from django.core.urlresolvers import reverse_lazy
...
LOGIN_URL = reverse_lazy('login')
LOGIN_REDIRECT_URL = reverse_lazy('home')
login.html
{% extends "base.html" %}
{% block head %}
<title>Login</title>
{% endblock %}
{% block body %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action="{% url 'django.contrib.auth.views.login' %}">
{% csrf_token %}
<table>
<tr>
<td>{{ form.username.label_tag }}</td>
<td>{{ form.username }}</td>
</tr>
<tr>
<td>{{ form.password.label_tag }}</td>
<td>{{ form.password }}</td>
</tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
logged_out.html
{% extends "base.html" %}
{% block head %}
<title>Logged out</title>
{% endblock %}
{% block body %}
<p>You have been logged out. You may <a href="{% url 'login' %}">log back in</a>.</p>
{% endblock %}
I'm not showing my base.html
template but I trust the pattern is obvious. If you want more than a bare login form there's no reason your login.html
template couldn't be fancier. The names are default values, as documented for the views, but you could use other choices if you wanted to.
That's all you need for the basic behavior. If you wrap your views with the login_required
decorator as described in the docs, it will redirect to your login page any time a non-authenticated user tries to access one of your views. Or, if you're using class-based views, use @method_decorator(login_required)
as documented here. Two more snippets from my project:
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
class HomeView(TemplateView):
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(HomeView, self).dispatch(*args, **kwargs)
@login_required
def report_for_group(request, group_id):
...
The docs include discussions of some more complicated setups, should you need them.