login with AuthenticationForm
Date: April 14th 2016
Last updated: April 14th 2016
As I have progressed along with numerous django tutorials, I realised the original login form I was using was looking pretty old. This is my updated login form.
urls.py
from django.conf.urls import url
from . import views
app_name = 'surferprofile'
urlpatterns = [
#... <-snipped->
url(r'^login/$', views.login_user, name='login'),
#<- snipped ->
]
views.py
from .forms import LoginForm
def login_user(request):
logout(request)
username = password = ''
if request.POST:
# With the AuthenticationForm you MUST ALWAYS ASSIGN
# THE request.POST to a variable e.g. data!!!!!!!!!!
form = LoginForm(data = request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
login(request, user)
return redirect('/{}/'.format(user.surfer.id))
else:
form = LoginForm()
return render(request, 'surferprofile/login.html',{'form': form})
forms.py
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, ButtonHolder, Submit
from django.contrib.auth.forms import AuthenticationForm
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_method = 'post' # this line sets your form's method to post
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-4'
self.helper.field_class = 'col-lg-6'
self.helper.layout = Layout(
'username',
'password',
ButtonHolder(
Submit('login', 'Login', css_class='btn-primary')
)
)
html template
{% load staticfiles %}
{% load crispy_forms_tags %}
<html>
<head>
<link rel="stylesheet" type="text/css" href="{% static 'surferprofile/style.css' %}" />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div id = "formcontainer">
<h1 style="text-align: center;">Login</h1>
<form id='login' role="form" action="" method="post">
{% csrf_token %}
{% crispy form %}
</form>
</div>
</body>