Login

Simple login script from a nub

Author:
alandelevie
Posted:
December 13, 2008
Language:
Python
Version:
1.0
Score:
-1 (after 1 ratings)

The utility of a login script is self-evident. As I learned about Django's built-in user authentication features, I whipped up this script and figured that I'd post it here. I am by no means an expert and would appreciate any constructive criticism. However, per the rules of this site, this is working code and not work in progress. Thanks Also: I wrote a blog post explaining the script for those who are interested: http://bit.ly/bwIL

 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
53
54
55
56
57
#models.py
class LoginForm(forms.Form):
	username = forms.CharField(max_length=100)
	password = forms.CharField(widget=forms.PasswordInput(render_value=False),max_length=100)

#views.py
from django.contrib.auth import authenticate, login
from django.shortcuts import render_to_response
def login(request):
	def errorHandle(error):
		form = LoginForm()
		return render_to_response('login.html', {
				'error' : error,
				'form' : form,
		})
	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('courses/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('login.html', {
			'form': form,
		})

#login.html
{% if error %}
<p>{{ error }}</p>
{% endif %}

<form action="." method="POST">
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

#logged_in.html
<h1>Welcome, {{ username }}</h1>

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

alandelevie (on December 22, 2008):

Thanks! I will take a look at that.

#

Please login first before commenting.