Episode 21 of 32
Login Form
Create the login form and template — use Django AuthenticationForm to render username and password fields for user login.
Login Form
Django provides AuthenticationForm for login — it handles username and password fields with built-in validation.
The Login View (GET)
# accounts/views.py
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
def login_view(request):
form = AuthenticationForm()
return render(request, 'accounts/login.html', {
'form': form
})
The Login Template
<!-- templates/accounts/login.html -->
{% extends 'base_layout.html' %}
{% block content %}
<h2>Log In</h2>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Log In</button>
</form>
<p>Don't have an account? <a href="{% url 'accounts:signup' %}">Sign up</a></p>
{% endblock %}
AuthenticationForm vs UserCreationForm
| Form | Fields | Purpose |
|---|---|---|
UserCreationForm | Username, Password, Confirm Password | Registration |
AuthenticationForm | Username, Password | Login |
Key Takeaways
AuthenticationFormprovides username and password fields for login- The template structure is identical to signup — form, csrf_token, submit button
- Link the signup page from login and vice versa for good UX
- The actual login logic (authenticating the user) comes in the next episode