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

View File

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