Simple login script from a nub

 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. Remember me for login by iElectric 4 years, 2 months ago
  2. Login + logout script from a nub by alandelevie 5 years, 3 months ago
  3. Decorator for authenticating token based API calls by jpulgarin 3 years, 3 months ago
  4. Clear session data on login and logout by jb0t 6 years ago
  5. Using the built-in slugify filter outside a template by jcroft 7 years, 1 month ago

Comments

alandelevie (on December 22, 2008):

Thanks! I will take a look at that.

#

(Forgotten your password?)