Skip to content

Commit 0c6a62c

Browse files
30 - Login via Django AuthenticationForm
1 parent 710a2f9 commit 0c6a62c

File tree

2 files changed

+14
-22
lines changed

2 files changed

+14
-22
lines changed

accounts/views.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from django.contrib.auth import authenticate, login, logout
2-
from django.contrib.auth.forms import UserCreationForm
2+
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
33
from django.shortcuts import render, redirect
44

55
def register_view(request):
@@ -12,19 +12,19 @@ def register_view(request):
1212

1313
# Create your views here.
1414
def login_view(request):
15+
# future -> ?next=/articles/create/
1516
if request.method == "POST":
16-
username = request.POST.get("username")
17-
password = request.POST.get("password")
18-
# remove this!!!!
19-
# print(username, password)
20-
# remove this!!
21-
user = authenticate(request, username=username, password=password)
22-
if user is None:
23-
context = {"error": "Invalid username or password."}
24-
return render(request, "accounts/login.html", context)
25-
login(request, user)
26-
return redirect('/')
27-
return render(request, "accounts/login.html", {})
17+
form = AuthenticationForm(request, data=request.POST)
18+
if form.is_valid():
19+
user = form.get_user()
20+
login(request, user)
21+
return redirect('/')
22+
else:
23+
form = AuthenticationForm(request)
24+
context = {
25+
"form": form
26+
}
27+
return render(request, "accounts/login.html", context)
2828

2929

3030
def logout_view(request):

templates/accounts/login.html

+1-9
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,7 @@
66
{% if not request.user.is_authenticated %}
77
<div style='margin-top:30px;'>
88
<form method='POST'>{% csrf_token %}
9-
{% if error %}
10-
<p style='color:red'>{{ error }}</p>
11-
{% endif %}
12-
<div>
13-
<input type='text' name='username' placeholder='username' />
14-
</div>
15-
<div>
16-
<input type='password' name='password' placeholder='password' />
17-
</div>
9+
{{ form.as_p }}
1810
<button type='submit'>Login</button>
1911
</form>
2012

0 commit comments

Comments
 (0)