Based off what I learned making my previous tutorial A simple introduction to Django forms, I made a somewhat more elegant login script which includes the ability to log out (what a novel idea!).
So here it is:
models.py
1 2 3 4 5 | from django import forms class LoginForm(forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(widget=forms.PasswordInput(render_value=False),max_length=100) |
My previous tutorial explains the widget parameter.
views.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | from project.courses.models import LoginForm def check_login(request): def errorHandle(error): form = LoginForm() return render_to_response('pathto/login.html', { 'error' : error, 'form' : form, }) if request.user.is_authenticated(): username = request.user.username return render_to_response('pathto/logged_in.html', { 'username': username, }) else: if request.method == 'POST': # If the form has been submitted... form = LoginForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: # Redirect to a success page. login(request, user) return render_to_response('pathto/logged_in.html', { 'username': username, }) else: # Return a 'disabled account' error message error = u'account disabled' return errorHandle(error) else: # Return an 'invalid login' error message. error = u'invalid login' return errorHandle(error) else: error = u'form is invalid' return errorHandle(error) else: form = LoginForm() # An unbound form return render_to_response('pathto/login.html', { 'form': form, }) def logout_view(request): if request.user.is_authenticated(): logout(request) form = LoginForm() return check_login(request) else: check_login(request) return HttpResponseRedirect('/') |
The errorHandle function takes an error message as an argument and passes that to the login template. If the template is given an error message, it displays that above the login form. Pretty simple, so far? Good.
The logout_view function checks if the user is not logged in. If the user is logged in, it logs it out.
And here are the templates:
login.html
1 2 3 4 5 6 7 8 | {% if error %}
<p><i>{{ error }}</i></p>
{% endif %}
<form action="." method="POST">
{{ form.as_p }}
<input type="submit" value="Submit" />
</form> |
logged_in.html
1 2 | <h1>Welcome, {{ username }}</h1>
<p><a href='/scraper/logout/'>Logout</a></p> |
You can also look at this code at djangosnippets.org.
Comments 1
Awesome, thank you so much for the tutorial!
Posted 12 May 2010 at 10:22 pm ¶Post a Comment