Python Web Development in 2025: Getting Started with Flask and Django

Learn Python web development with Flask and Django, covering routes, templates, forms, models, views, admin panels, and REST APIs in this 2025 guide.

Python Web Development in 2025: Getting Started with Flask and Django

Learn Python web development with Flask and Django, covering routes, templates, forms, models, views, admin panels, and REST APIs in this beginner-friendly guide.

Why Python Web Frameworks Matter in 2025

In 2025, Python remains a top choice for web development due to its simplicity and powerful frameworks like Flask and Django. Flask offers lightweight flexibility for small projects, while Django provides a robust, full-stack solution with built-in features like an admin panel and ORM. This beginner-friendly guide introduces both frameworks, covering routes, templates, forms, models, views, and REST APIs, with practical examples to help you build modern web applications.

Developer coding a web app with Python in a modern IDE

Introduction to Web Frameworks

Web frameworks simplify the process of building web applications by providing tools for routing, templating, and database management. Flask is a micro-framework, ideal for small to medium projects requiring flexibility. Django, a full-stack framework, is suited for large-scale applications with built-in features like authentication and an admin panel. Both use Python’s simplicity to create dynamic, user-friendly websites.

To get started, set up a virtual environment:

python -m venv web_env
source web_env/bin/activate  # On Windows: web_env\Scripts\activate
pip install flask django djangorestframework
            

Flask: Building a Simple Web App

Flask is lightweight and easy to learn, making it perfect for beginners. It handles routing, templates, and forms with minimal setup.

Routes

Routes map URLs to functions that return responses.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to Flask in 2025!"

if __name__ == '__main__':
    app.run(debug=True)
            

Save this as app.py and run it with python app.py. Visit http://127.0.0.1:5000 to see the page.

Templates

Templates render dynamic HTML. Create a folder named templates and add index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Flask App</title>
</head>
<body style="background-color: #f0f2f5; text-align: center;">
    <h1>Welcome, {{ name }}!</h1>
</body>
</html>
            

Update app.py to render the template:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/<name>')
def home(name):
    return render_template('index.html', name=name)

if __name__ == '__main__':
    app.run(debug=True)
            

Forms

Handle forms with Flask-WTF. Install it with pip install flask-wtf. Create a form in forms.py:

from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired

class NameForm(FlaskForm):
    name = StringField('Name', validators=[DataRequired()])
    submit = SubmitField('Submit')
            

Update index.html for the form:

<!DOCTYPE html>
<html>
<head>
    <title>Flask Form</title>
</head>
<body style="background-color: #f0f2f5; text-align: center;">
    <form method="POST">
        {{ form.hidden_tag() }}
        {{ form.name.label }} {{ form.name() }}
        {{ form.submit() }}
    </form>
</body>
</html>
            

Update app.py to handle the form:

from flask import Flask, render_template, redirect, url_for
from forms import NameForm

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key'

@app.route('/', methods=['GET', 'POST'])
def home():
    form = NameForm()
    if form.validate_on_submit():
        return render_template('index.html', form=form, name=form.name.data)
    return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run(debug=True)
            

Install Flask with: pip install flask flask-wtf.

Python code editor showing Flask web app

Django: Building a Robust Web App

Django is a full-stack framework with a Model-View-Template (MVT) architecture, offering built-in features like an ORM and admin panel.

Models

Models define the database structure. Create a Django project and app:

django-admin startproject myproject
cd myproject
python manage.py startapp myapp
            

Add myapp to INSTALLED_APPS in myproject/settings.py. Define a model in myapp/models.py:

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.FloatField()

    def __str__(self):
        return self.name
            

Run migrations:

python manage.py makemigrations
python manage.py migrate
            

Views and Templates

Views handle logic, and templates render HTML. Create myapp/views.py:

from django.shortcuts import render
from .models import Product

def product_list(request):
    products = Product.objects.all()
    return render(request, 'myapp/product_list.html', {'products': products})
            

Create myapp/templates/myapp/product_list.html:

<!DOCTYPE html>
<html>
<head>
    <title>Product List</title>
</head>
<body style="background-color: #f0f2f5;">
    <h1>Products</h1>
    <ul>
    {% for product in products %}
        <li>{{ product.name }}: ${{ product.price }}</li>
    {% endfor %}
    </ul>
</body>
</html>
            

Configure URLs in myapp/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.product_list, name='product_list'),
]
            

Update myproject/urls.py to include the app’s URLs:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),
]
            

Admin Panel

Django’s admin panel allows easy data management. Register the model in myapp/admin.py:

from django.contrib import admin
from .models import Product

admin.site.register(Product)
            

Create a superuser to access the admin panel:

python manage.py createsuperuser
            

Run the server with python manage.py runserver and visit http://127.0.0.1:8000/admin.

Python code editor showing Django web app

Building a Basic REST API

Flask REST API

Create a simple REST API with Flask:

from flask import Flask, jsonify

app = Flask(__name__)

products = [{"id": 1, "name": "Laptop", "price": 999.99}]

@app.route('/api/products', methods=['GET'])
def get_products():
    return jsonify(products)

if __name__ == '__main__':
    app.run(debug=True)
            

Access the API at http://127.0.0.1:5000/api/products.

Django REST API

Use Django REST Framework (DRF). Add rest_framework to INSTALLED_APPS in myproject/settings.py. Create myapp/serializers.py:

from rest_framework import serializers
from .models import Product

class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'name', 'price']
            

Update myapp/views.py:

from rest_framework import generics
from .models import Product
from .serializers import ProductSerializer

class ProductList(generics.ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
            

Update myapp/urls.py:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.product_list, name='product_list'),
    path('api/products/', views.ProductList.as_view(), name='product_list_api'),
]
            

Access the API at http://127.0.0.1:8000/api/products/. Install DRF with: pip install djangorestframework.

Best Practices for Web Development

To succeed in Python web development, follow these tips:

  • Use Virtual Environments: Isolate dependencies with venv.
  • Secure Your App: Use secret keys and environment variables.
  • Test Locally: Use debug mode for development.
  • Explore Documentation: Refer to Flask and Django docs for advanced features.
  • Optimize APIs: Use DRF for Django APIs to simplify development.
Start Building Web Apps Now

Conclusion

Python web development with Flask and Django empowers beginners to create dynamic web applications in 2025. Flask offers simplicity for small projects, while Django provides robust tools for complex apps. Start with the examples in this guide, experiment with routes, templates, and APIs, and share your web development tips in the comments below!

© 2025 Your Blog Name. All rights reserved.

Post a Comment