- Python for Web Development
-
Overview
- Introduction to Flask and Django
- Setting Up a Flask Application
- Django Models and Migrations
- Routing and URL Handling in Django and Flask
- Forms and User Authentication in Django and Flask
- REST API Development with Flask & Django
- Working with Databases (SQLite, PostgreSQL, MySQL)
- Template Engines (Jinja2 for Flask, Django Templates)
- Deployment of Flask & Django Applications on AWS, GCP, and Heroku
- Security Best Practices for Web Apps
Forms and User Authentication in Django and Flask
Forms and authentication are essential in web applications for handling user input and securing access to resources. Django provides built-in support for forms and authentication, while Flask requires additional extensions like Flask-WTF
for form handling and Flask-Login
for authentication.
1. Forms in Django
Creating a Form Using Django Forms
Django provides forms.Form
and forms.ModelForm
for handling form validation.
Example: Creating a Login Form in Django
In forms.py
:
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(max_length=100)
password = forms.CharField(widget=forms.PasswordInput)
Handling the Form in a View
In views.py
:
from django.shortcuts import render
from .forms import LoginForm
def login_view(request):
form = LoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
# Authenticate user (authentication logic here)
return HttpResponse(f"Logged in as {username}")
return render(request, 'login.html', {'form': form})
Rendering the Form in a Template
In login.html
:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
Explanation:
forms.Form
is used to create the form.request.POST or None
ensures form data is processed.form.is_valid()
checks if input is valid.{{ form.as_p }}
renders the form fields in HTML.
2. Forms in Flask
Flask does not have built-in form handling, so we use Flask-WTF
(an extension of WTForms
).
Installing Flask-WTF
Run:
pip install flask-wtf
Creating a Login Form in Flask
In forms.py
:
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
submit = SubmitField('Login')
Handling the Form in Flask
In app.py
:
from flask import Flask, render_template, request
from forms import LoginForm
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
username = form.username.data
password = form.password.data
return f"Logged in as {username}"
return render_template('login.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
Rendering the Form in a Template
In login.html
:
<form method="POST">
{{ form.hidden_tag() }}
<p>{{ form.username.label }} {{ form.username() }}</p>
<p>{{ form.password.label }} {{ form.password() }}</p>
<p>{{ form.submit() }}</p>
</form>
Explanation:
Flask-WTF
is used for form validation.form.validate_on_submit()
checks if the form is submitted and valid.SECRET_KEY
is required for CSRF protection.
3. User Authentication in Django
Django provides built-in authentication with django.contrib.auth
.
Setting Up Authentication
Ensure django.contrib.auth
is in INSTALLED_APPS
in settings.py
.
User Login in Django
In views.py
:
from django.contrib.auth import authenticate, login
from django.shortcuts import render, redirect
from .forms import LoginForm
def login_view(request):
form = LoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(request, username=username, password=password)
if user:
login(request, user)
return redirect('dashboard')
return render(request, 'login.html', {'form': form})
User Logout in Django
from django.contrib.auth import logout
def logout_view(request):
logout(request)
return redirect('home')
4. User Authentication in Flask
Flask requires Flask-Login
for handling authentication.
Installing Flask-Login
Run:
pip install flask-login
Setting Up Authentication in Flask
In app.py
:
from flask import Flask, render_template, redirect, request, url_for
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key'
login_manager = LoginManager(app)
class User(UserMixin):
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
users = {'admin': User(1, 'admin', 'password')} # Dummy user
@login_manager.user_loader
def load_user(user_id):
return users.get(user_id)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
user = users.get(username)
if user and user.password == password:
login_user(user)
return redirect('/dashboard')
return render_template('login.html')
@app.route('/logout')
@login_required
def logout():
logout_user()
return redirect('/')
@app.route('/dashboard')
@login_required
def dashboard():
return "Welcome to your dashboard"
if __name__ == '__main__':
app.run(debug=True)
Explanation:
Flask-Login
handles user sessions.UserMixin
provides default authentication methods.login_user()
logs the user in.logout_user()
logs the user out.@login_required
restricts access to logged-in users.
Conclusion
- Django provides built-in form handling and authentication with
django.contrib.auth
. - Flask requires
Flask-WTF
for forms andFlask-Login
for authentication. - Both frameworks support session-based authentication.
Prepare for Interview
- Dynamic Programming and Recursion in Python
- Trees and Graphs in Python
- Linked Lists, Stacks, and Queues in Python
- Sorting and Searching in Python
- Debugging in Python
- Unit Testing in Python
- Asynchronous Programming in PYthon
- Multithreading and Multiprocessing in Python
- Context Managers in Python
- Decorators in Python
- Generators in Python
- Requests in Python
- Django
- Flask
- Matplotlib/Seaborn
Random Blogs
- Python Challenging Programming Exercises Part 3
- 10 Awesome Data Science Blogs To Check Out
- Datasets for analyze in Tableau
- Python Challenging Programming Exercises Part 1
- Loan Default Prediction Project Using Machine Learning
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- Important Mistakes to Avoid While Advertising on Facebook
- Transforming Logistics: The Power of AI in Supply Chain Management
- Mastering Python in 2025: A Complete Roadmap for Beginners
- How to Start Your Career as a DevOps Engineer
- The Ultimate Guide to Starting a Career in Computer Vision
- Robotics & AI – How AI is Powering Modern Robotics
- The Ultimate Guide to Data Science: Everything You Need to Know
- Grow your business with Facebook Marketing
- Best Platform to Learn Digital Marketing in Free
Datasets for Machine Learning
- Ozone Level Detection Dataset
- Bank Transaction Fraud Detection
- YouTube Trending Video Dataset (updated daily)
- Covid-19 Case Surveillance Public Use Dataset
- US Election 2020
- Forest Fires Dataset
- Mobile Robots Dataset
- Safety Helmet Detection
- All Space Missions from 1957
- OSIC Pulmonary Fibrosis Progression Dataset
- Wine Quality Dataset
- Google Audio Dataset
- Iris flower dataset
- Artificial Characters Dataset
- Bitcoin Heist Ransomware Address Dataset