π§ Django: Beginner Notes (with Spring Boot References)
βοΈ What is Django?
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Itβs built on the Model-View-Template (MVT) architecture.
β Spring Boot analogy: Django is to Python what Spring Boot is to Java. Both are batteries-included frameworks that handle most of the plumbing so you can focus on business logic.
π§± Django Project Structure
When you create a Django project:
[[Creating Django Project|django-admin startproject myproject]]
cd myproject
python manage.py startapp myappYouβll see this structure:
myproject/
βββ myproject/ β Settings, WSGI, ASGI (like `application.properties` in Spring Boot)
β βββ __init__.py
β βββ settings.py β Project-wide configuration
β βββ urls.py β Route definitions (like Spring's @RequestMapping)
β βββ asgi.py
β βββ wsgi.py
βββ myapp/ β App logic (like Spring Boot modules)
β βββ [[Django Concepts#django-model|models.py]] β Define database models (like JPA entities)
β βββ views.py β Define request handlers (like @Controller or @RestController)
β βββ urls.py β App-level routing
β βββ admin.py β Admin interface
β βββ apps.py
βββ db.sqlite3 β Default database (can switch to PostgreSQL, MySQL, etc.)
βββ manage.py β CLI tool (like Spring Boot's `mvn spring-boot:run`)
π MVT Pattern (vs MVC in Spring Boot)
| Django (MVT) | Spring Boot (MVC) | Description |
|---|---|---|
| Model | Model (JPA Entity) | Represents data and DB logic |
| View | Controller | Handles business logic and HTTP requests |
| Template | View (Thymeleaf) | HTML templates rendered with context |
Django calls the Controller the βviewβ and the template is what youβd call βviewβ in Spring MVC. Confusing at first, but youβll get used to it.
ποΈ Models (Spring Bootβs @Entity)
In Django:
# myapp/models.py
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.FloatField()In Spring Boot:
@Entity
public class Product {
@Id
@GeneratedValue
private Long id;
private String name;
private Double price;
}-
Django auto-generates the table.
-
You run
python manage.py makemigrationsandpython manage.py migrateto sync models with the DB.
π Routing and Views (Springβs @Controller)
In Django:
# myapp/views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello, Django!")# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]In Spring Boot:
@RestController
public class HomeController {
@GetMapping("/")
public String home() {
return "Hello, Spring!";
}
}π§Ύ Templates (Springβs Thymeleaf equivalent)
Use Djangoβs template system (.html files):
<!-- templates/home.html -->
<html>
<body>
<h1>Hello, {{ user_name }}!</h1>
</body>
</html>Render it:
from django.shortcuts import render
def home(request):
return render(request, "home.html", {"user_name": "Jonas"})π‘οΈ Forms and Validation (like Springβs DTOs + Validation)
Django has forms.py:
from django import forms
class ProductForm(forms.Form):
name = forms.CharField()
price = forms.FloatField()You use it in views to render and validate input.
Spring Boot analogy:
-
Spring: DTOs +
@Valid+BindingResult -
Django: Form classes handle rendering + validation
π Authentication & Admin Panel
Django gives you a ready-made admin interface and auth system.
python manage.py createsuperuserVisit /admin and log in.
Spring Boot analogy:
-
Django Admin = Pre-built admin dashboard
-
Spring Boot = You usually build your own or use something like Spring Security + custom UI
π ORM vs JPA
-
Django has its own ORM (no need for Hibernate or JPA).
-
You define models as classes, and Django handles SQL generation.
-
No need for
@OneToMany,@ManyToOneβ instead, you useForeignKey,ManyToManyField, etc.
Example:
class Category(models.Model):
name = models.CharField(max_length=50)
class Product(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)Spring Boot equivalent:
@Entity
public class Category {
@OneToMany(mappedBy = "category")
private List<Product> products;
}
@Entity
public class Product {
@ManyToOne
private Category category;
}π Useful Django Commands
| Command | Description |
|---|---|
django-admin startproject myproject | Create a new Django project |
python manage.py startapp myapp | Create a new app inside the project |
python manage.py runserver | Start development server |
python manage.py makemigrations | Create DB migration from models |
python manage.py migrate | Apply DB migrations |
python manage.py createsuperuser | Create admin user |
python manage.py shell | Open Python shell with Django context |
π REST APIs in Django
Use Django REST Framework (DRF) β like Spring Boot REST APIs.
Install:
pip install djangorestframeworkCreate API:
# serializers.py
from rest_framework import serializers
from .models import Product
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = '__all__'# views.py
from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer# urls.py
from rest_framework.routers import DefaultRouter
from .views import ProductViewSet
router = DefaultRouter()
router.register(r'products', ProductViewSet)
urlpatterns = router.urlsDjango REST Framework = Spring Boot + Spring Data REST + Jackson
π‘ Major Differences from Spring Boot
| Django | Spring Boot |
|---|---|
| Python-based | Java-based |
| Built-in ORM | Uses Hibernate (JPA) |
| Built-in Admin panel | No admin panel out of the box |
| Templates: Jinja-like | Templates: Thymeleaf |
Uses manage.py for CLI | Uses mvn or gradle |
| Lightweight | More boilerplate |
| REST via DRF | REST via annotations |
| Convention over configuration | Explicit annotations and XML (less now) |
π Summary
| Concept | Django | Spring Boot Equivalent |
|---|---|---|
| Project structure | startproject & startapp | Spring Initializr modules |
| Models | models.py | @Entity, JPA classes |
| Views | views.py functions | @Controller or @RestController |
| Templates | Django Templates | Thymeleaf |
| Routing | urls.py | @RequestMapping |
| ORM | Built-in | Hibernate + JPA |
| Admin Panel | Built-in /admin | Build manually |
| REST | Django REST Framework | Spring Boot REST |