Django · PyTorch · Python
Django vs PyTorch: What Each Does and How They Work Together
Two tools, two jobs
| Django | PyTorch | |
|---|---|---|
| What it is | Web framework | Deep learning library (tensors, automatic differentiation, neural network layers) |
| First released | 2005 | 2016, from Meta's AI research lab; governed by the PyTorch Foundation since 2022 |
| You use it to | Handle HTTP requests, store data, render pages, build REST APIs | Define models, train them on data, run predictions, often on GPUs |
| Key pieces | URL routing, views, ORM, templates, admin, auth | torch.Tensor, autograd, torch.nn, optimisers, data loaders |
| Typical users | Backend and full-stack developers | ML engineers, researchers, data scientists |
Neither can do the other's job. Django has no neural network layers, and PyTorch has no web server or database layer.
PyTorch in a few lines
A single linear layer computes y = w·x + b. Here the weights are set by hand so the output is predictable:
import torch
import torch.nn as nn
model = nn.Linear(2, 1)
with torch.no_grad():
model.weight.copy_(torch.tensor([[2.0, -1.0]]))
model.bias.fill_(0.5)
model.eval()
x = torch.tensor([[3.0, 4.0]])
with torch.no_grad():
print(model(x))Output:
tensor([[2.5000]])That is 2 × 3 − 1 × 4 + 0.5. In real work the weights are learned: you run batches of data through the model, compute a loss, call loss.backward() and let an optimiser update the weights. Judging whether training worked is covered in model evaluation metrics.
Django in a few lines
# views.py
from django.http import JsonResponse
def health(request):
return JsonResponse({"status": "ok"})
# urls.py
from django.urls import path
from . import views
urlpatterns = [path("health/", views.health)]A request to /health/ returns {"status": "ok"}. Django's real strength shows with models and the admin: define a table as a Python class and you get migrations, queries and an admin screen. If you are choosing a Python web framework, see Flask vs Django.
How they work together: serving a model
A common pattern is to train a model in PyTorch, save its weights, and load it once inside a Django app that exposes a prediction endpoint.
# predict/model_loader.py
import torch
import torch.nn as nn
model = nn.Linear(2, 1)
model.load_state_dict(torch.load("weights.pt", map_location="cpu"))
model.eval() # loaded once, when the module is imported# predict/views.py
import json
import torch
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .model_loader import model
@csrf_exempt # API called by other programs; protect it with auth instead
@require_POST
def predict(request):
data = json.loads(request.body)
x = torch.tensor([data["features"]], dtype=torch.float32)
with torch.no_grad():
y = model(x).item()
return JsonResponse({"prediction": y})If weights.pt holds the weights from the earlier example, posting {"features": [3, 4]} returns:
{"prediction": 2.5}Points to get right in production:
- Load the model once, not inside the view, or every request pays the loading time.
- Validate input: check that
featuresexists and has the right length before building the tensor. - Authentication:
csrf_exemptis acceptable for a machine-to-machine API only if you add token authentication, for example with Django REST Framework. - Slow models: move long predictions to a background worker such as Celery, or run inference as a separate service that Django calls.
- Load only trusted weight files.
torch.loadcan execute code from a malicious file unless you useweights_only=True, which recent PyTorch versions make the default.
REST basics for designing such endpoints are in REST APIs with a simple example.
Which to learn, for which goal
- Web development: Django (or Flask/FastAPI). PyTorch is not needed.
- Machine learning or deep learning: PyTorch, after NumPy, basic linear algebra and classic ML. Knowing when deep learning is worth it at all is discussed in deep learning vs traditional ML.
- ML engineering: both are useful, because deploying models means building services around them. A portfolio project that trains a model and serves it through a small web app shows both skills; see building ML portfolio projects.