login page uses django forms

This commit is contained in:
iou1name 2018-08-12 01:43:47 -04:00
parent c79cb36f23
commit 7fb52374f9
3 changed files with 29 additions and 14 deletions

12
login/forms.py Normal file
View File

@ -0,0 +1,12 @@
#!/usr/bin/env python3
"""
Form(s) for the login page.
"""
from django import forms
class LoginForm(forms.Form):
"""
The main login form.
"""
username = forms.CharField(label="Username", max_length=20)
password = forms.CharField(label="Password", widget=forms.PasswordInput)

View File

@ -4,8 +4,7 @@
<h1>Login</h1>
<form method="post" action="{{ url('login:index') }}">
{{ csrf_input }}
<input type="text" placeholder="Username" name="username" maxlength="20" required/><br />
<input type="password" placeholder="Password" name="password" maxlength="1024" required/><br />
{{ form.as_p() }}
<input type="submit" value="Log in" name="submit"/>
</form>
{% endblock %}

View File

@ -6,20 +6,24 @@ from django.contrib import messages
from django.shortcuts import redirect, render
from django.contrib.auth import authenticate, login
from .forms import LoginForm
def index(request):
"""
The login page.
"""
if request.method == "GET":
context = {}
return render(request, 'login/index.html', context)
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
form = LoginForm()
return render(request, 'login/index.html', {'form': form})
form = LoginForm(request.POST)
if form.is_valid():
user = authenticate(
request,
username=form.cleaned_data.get('username'),
password=form.cleaned_data.get('password'))
if user is not None:
login(request, user)
messages.success(request, "Logged in")
return redirect('homepage:index')
else:
messages.error(request, "Invalid credentials")
return redirect('login:index')
return render(request, 'login/index.html', {'form': form})