From 7fb52374f91fc13d2fdfd5cc32053c62773f1041 Mon Sep 17 00:00:00 2001 From: iou1name Date: Sun, 12 Aug 2018 01:43:47 -0400 Subject: [PATCH] login page uses django forms --- login/forms.py | 12 ++++++++++++ login/jinja2/login/index.html | 3 +-- login/views.py | 28 ++++++++++++++++------------ 3 files changed, 29 insertions(+), 14 deletions(-) create mode 100644 login/forms.py diff --git a/login/forms.py b/login/forms.py new file mode 100644 index 0000000..62d272c --- /dev/null +++ b/login/forms.py @@ -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) diff --git a/login/jinja2/login/index.html b/login/jinja2/login/index.html index 94ba860..e5c3c13 100644 --- a/login/jinja2/login/index.html +++ b/login/jinja2/login/index.html @@ -4,8 +4,7 @@

Login

{{ csrf_input }} -
-
+ {{ form.as_p() }}
{% endblock %} diff --git a/login/views.py b/login/views.py index 3a7e5a9..289a15a 100644 --- a/login/views.py +++ b/login/views.py @@ -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) - 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') + 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') + messages.error(request, "Invalid credentials") + return render(request, 'login/index.html', {'form': form})