Django Beginner Notes (with Spring Boot References)

🧠 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 myapp

You’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
ModelModel (JPA Entity)Represents data and DB logic
ViewControllerHandles business logic and HTTP requests
TemplateView (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 makemigrations and python manage.py migrate to 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 createsuperuser

Visit /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 use ForeignKey, 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

CommandDescription
django-admin startproject myprojectCreate a new Django project
python manage.py startapp myappCreate a new app inside the project
python manage.py runserverStart development server
python manage.py makemigrationsCreate DB migration from models
python manage.py migrateApply DB migrations
python manage.py createsuperuserCreate admin user
python manage.py shellOpen Python shell with Django context

🌍 REST APIs in Django

Use Django REST Framework (DRF) β€” like Spring Boot REST APIs.

Install:

pip install djangorestframework

Create 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.urls

Django REST Framework = Spring Boot + Spring Data REST + Jackson


πŸ’‘ Major Differences from Spring Boot

DjangoSpring Boot
Python-basedJava-based
Built-in ORMUses Hibernate (JPA)
Built-in Admin panelNo admin panel out of the box
Templates: Jinja-likeTemplates: Thymeleaf
Uses manage.py for CLIUses mvn or gradle
LightweightMore boilerplate
REST via DRFREST via annotations
Convention over configurationExplicit annotations and XML (less now)

πŸ”š Summary

ConceptDjangoSpring Boot Equivalent
Project structurestartproject & startappSpring Initializr modules
Modelsmodels.py@Entity, JPA classes
Viewsviews.py functions@Controller or @RestController
TemplatesDjango TemplatesThymeleaf
Routingurls.py@RequestMapping
ORMBuilt-inHibernate + JPA
Admin PanelBuilt-in /adminBuild manually
RESTDjango REST FrameworkSpring Boot REST