0
0
Djangoframework~30 mins

Login view and template in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Login view and template
📖 Scenario: You are building a simple login page for a website. Users will enter their username and password to access their account.
🎯 Goal: Create a Django view to handle user login and a corresponding HTML template with a form for username and password.
📋 What You'll Learn
Create a Django view function named login_view that uses django.contrib.auth.authenticate and django.contrib.auth.login to log in users.
Create an HTML template named login.html with a form containing username and password input fields and a submit button.
The form should use the POST method and submit to the same URL.
If authentication fails, the view should re-render the template with an error message.
💡 Why This Matters
🌍 Real World
Login pages are essential for websites that require user accounts, such as social media, e-commerce, or online services.
💼 Career
Understanding how to implement user authentication is a key skill for web developers working with Django or similar frameworks.
Progress0 / 4 steps
1
Create the login view function
Create a Django view function called login_view that accepts a request parameter and imports authenticate and login from django.contrib.auth. For now, just return render(request, 'login.html').
Django
Need a hint?

Start by importing authenticate and login from django.contrib.auth. Then define login_view that returns render(request, 'login.html').

2
Add POST check and get username and password
Inside the login_view function, add a check for request.method == 'POST'. If true, get username and password from request.POST using request.POST.get('username') and request.POST.get('password').
Django
Need a hint?

Use request.method == 'POST' to check the form submission. Then get the username and password from request.POST.

3
Authenticate user and login or show error
Still inside the POST check, use authenticate(request, username=username, password=password) to verify credentials. If the user is valid, call login(request, user) and redirect to '/'. Otherwise, set an error variable to 'Invalid username or password' and pass it to the template context.
Django
Need a hint?

Use authenticate to check credentials. If valid, call login and redirect. Otherwise, prepare an error message for the template.

4
Create the login.html template with form and error display
Create an HTML file named login.html with a form that uses method='post'. Include {% csrf_token %} inside the form. Add input fields with name='username' and name='password'. Add a submit button with text 'Login'. Below the form, display the error variable if it exists inside a <p> tag with style='color: red;'.
Django
Need a hint?

Create a form with POST method, include {% csrf_token %}, username and password inputs, and a submit button. Show the error message in red if it exists.