or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-django-stubs

Comprehensive type stubs for Django framework enabling static type checking with mypy

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/django-stubs@4.2.x

To install, run

npx @tessl/cli install tessl/pypi-django-stubs@4.2.0

0

# Django-Stubs

1

2

Django-stubs provides comprehensive type stubs for the Django web framework, enabling precise static type checking with mypy. It addresses Django's dynamic nature and provides type definitions for Django's models, views, forms, admin interface, authentication system, and all major framework components, along with a mypy plugin for enhanced type inference.

3

4

## Package Information

5

6

- **Package Name**: django-stubs

7

- **Language**: Python

8

- **Installation**: `pip install django-stubs`

9

- **Dependencies**: `django`, `django-stubs-ext>=4.2.7`, `typing-extensions`, `types-pytz`, `types-PyYAML`

10

- **Optional**: `mypy~=1.7.0` (via `django-stubs[compatible-mypy]`)

11

12

## Core Imports

13

14

Django-stubs enables type checking by providing type stubs for Django modules:

15

16

```python

17

import django

18

from django import setup

19

```

20

21

Common Django imports with type support:

22

23

```python

24

# Database and models

25

from django.db import models

26

from django.db.models import QuerySet, Manager

27

from django.db import transaction

28

29

# HTTP request/response handling

30

from django.http import HttpRequest, HttpResponse, JsonResponse

31

from django.shortcuts import render, get_object_or_404, redirect

32

33

# URL routing

34

from django.urls import path, include, reverse

35

36

# Forms

37

from django import forms

38

from django.forms import ModelForm

39

40

# Views

41

from django.views import View

42

from django.views.generic import ListView, DetailView, CreateView, UpdateView

43

44

# Admin

45

from django.contrib import admin

46

47

# Authentication

48

from django.contrib.auth import authenticate, login, logout

49

from django.contrib.auth.models import User

50

from django.contrib.auth.decorators import login_required

51

52

# Configuration

53

from django.conf import settings

54

from django.core.exceptions import ValidationError, ObjectDoesNotExist

55

```

56

57

## Basic Usage

58

59

```python

60

from django.db import models

61

from django.http import HttpRequest, HttpResponse

62

from django.shortcuts import render

63

64

# Define a model with proper type hints

65

class Article(models.Model):

66

title: models.CharField = models.CharField(max_length=200)

67

content: models.TextField = models.TextField()

68

created_at: models.DateTimeField = models.DateTimeField(auto_now_add=True)

69

70

# View function with type hints

71

def article_detail(request: HttpRequest, article_id: int) -> HttpResponse:

72

article = get_object_or_404(Article, pk=article_id)

73

return render(request, 'article_detail.html', {'article': article})

74

75

# URL configuration

76

from django.urls import path

77

from . import views

78

79

urlpatterns = [

80

path('article/<int:article_id>/', views.article_detail, name='article_detail'),

81

]

82

```

83

84

## Architecture

85

86

Django-stubs provides two main components:

87

88

- **Type Stubs**: 684 `.pyi` files mirroring Django's complete API structure with precise type annotations

89

- **MyPy Plugin**: Enhanced type checking for Django-specific patterns, QuerySet operations, model field types, and request handling

90

91

This design enables full static type checking while preserving Django's dynamic capabilities and providing better IDE support through accurate type inference.

92

93

## Capabilities

94

95

### Database and ORM

96

97

Complete type definitions for Django's Object-Relational Mapping system, including model classes, field types, QuerySet operations, database connections, and relationship definitions.

98

99

```python { .api }

100

class Model: ...

101

class QuerySet: ...

102

class Manager: ...

103

104

# Field types

105

class CharField(Field): ...

106

class IntegerField(Field): ...

107

class ForeignKey(Field): ...

108

class ManyToManyField(Field): ...

109

110

# Query functions

111

def get_object_or_404(klass, *args, **kwargs): ...

112

```

113

114

[Database and ORM](./database-orm.md)

115

116

### Database Migrations

117

118

Type definitions for Django's migrations system, providing version control for database schema changes with automated creation, modification, and rollback of database structures.

119

120

```python { .api }

121

class Migration: ...

122

class CreateModel(Operation): ...

123

class AddField(Operation): ...

124

class AlterField(Operation): ...

125

class RunSQL(Operation): ...

126

class RunPython(Operation): ...

127

```

128

129

[Database Migrations](./migrations.md)

130

131

### Database Transactions

132

133

Type definitions for Django's transaction system, providing database transaction management with atomic operations, savepoints, and commit/rollback functionality.

134

135

```python { .api }

136

class Atomic: ...

137

def atomic(using=None, savepoint=True, durable=False) -> Atomic: ...

138

def commit(using=None) -> None: ...

139

def rollback(using=None) -> None: ...

140

def savepoint(using=None) -> str: ...

141

def on_commit(func, using=None, robust=True) -> None: ...

142

```

143

144

[Database Transactions](./transactions.md)

145

146

### Django Signals

147

148

Type definitions for Django's signal system, providing decoupled notifications for actions happening throughout the framework with event-driven programming patterns.

149

150

```python { .api }

151

class Signal: ...

152

class ModelSignal(Signal): ...

153

def receiver(signal, sender=None, weak=True, dispatch_uid=None) -> Callable: ...

154

155

# Model signals

156

pre_save: ModelSignal

157

post_save: ModelSignal

158

pre_delete: ModelSignal

159

post_delete: ModelSignal

160

```

161

162

[Django Signals](./signals.md)

163

164

### Forms System

165

166

Type definitions for Django's form handling system, including form classes, field types, widgets, validation, and form processing utilities.

167

168

```python { .api }

169

class Form: ...

170

class ModelForm(Form): ...

171

class Field: ...

172

173

# Form fields

174

class CharField(Field): ...

175

class EmailField(Field): ...

176

class ChoiceField(Field): ...

177

178

# Widgets

179

class TextInput(Widget): ...

180

class Select(Widget): ...

181

```

182

183

[Forms System](./forms.md)

184

185

### HTTP Handling

186

187

Type definitions for HTTP request and response processing, including request objects, response classes, middleware, and cookie handling.

188

189

```python { .api }

190

class HttpRequest: ...

191

class HttpResponse: ...

192

class JsonResponse(HttpResponse): ...

193

194

class QueryDict: ...

195

196

# HTTP exceptions

197

class Http404(Exception): ...

198

```

199

200

[HTTP Handling](./http.md)

201

202

### URL Routing

203

204

Type definitions for Django's URL routing system, including URL patterns, view resolution, reverse URL lookup, and URL configuration.

205

206

```python { .api }

207

def path(route: str, view, kwargs=None, name=None) -> URLPattern: ...

208

def include(arg, namespace=None) -> tuple: ...

209

def reverse(viewname: str, urlconf=None, args=None, kwargs=None, current_app=None) -> str: ...

210

211

class URLPattern: ...

212

class URLResolver: ...

213

```

214

215

[URL Routing](./urls.md)

216

217

### View System

218

219

Type definitions for Django's view system, including class-based views, generic views, template views, and view mixins.

220

221

```python { .api }

222

class View: ...

223

class TemplateView(View): ...

224

class ListView(View): ...

225

class DetailView(View): ...

226

class CreateView(View): ...

227

class UpdateView(View): ...

228

```

229

230

[View System](./views.md)

231

232

### Template System

233

234

Type definitions for Django's template engine system, including template loading, context processing, template tags, and filters.

235

236

```python { .api }

237

class Template: ...

238

class Context: ...

239

class Engine: ...

240

241

def render(request, template_name: str, context=None, content_type=None, status=None, using=None) -> HttpResponse: ...

242

```

243

244

[Template System](./templates.md)

245

246

### Administration Interface

247

248

Type definitions for Django's admin interface, including admin site configuration, model admin classes, inline admin, and admin actions.

249

250

```python { .api }

251

class ModelAdmin: ...

252

class StackedInline: ...

253

class TabularInline: ...

254

255

def register(model_or_iterable, admin_class=None, **options): ...

256

257

site: AdminSite

258

```

259

260

[Administration Interface](./admin.md)

261

262

### Authentication System

263

264

Type definitions for Django's authentication and authorization system, including user models, authentication backends, permissions, and session handling.

265

266

```python { .api }

267

def authenticate(request=None, **credentials): ...

268

def login(request: HttpRequest, user) -> None: ...

269

def logout(request: HttpRequest) -> None: ...

270

def get_user_model(): ...

271

```

272

273

[Authentication System](./auth.md)

274

275

### Contrib Packages

276

277

Type definitions for Django's contributed applications including GIS (GeoDjango), PostgreSQL-specific features, static files handling, sessions, messaging, and more.

278

279

```python { .api }

280

# GIS fields

281

class PointField(Field): ...

282

class PolygonField(Field): ...

283

284

# PostgreSQL fields

285

class ArrayField(Field): ...

286

class JSONField(Field): ...

287

```

288

289

[Contrib Packages](./contrib.md)

290

291

### MyPy Plugin

292

293

Enhanced type checking plugin that provides Django-specific type inference for model fields, QuerySet operations, form processing, and request handling patterns.

294

295

```python { .api }

296

class NewSemanalDjangoPlugin: ...

297

```

298

299

[MyPy Plugin](./mypy-plugin.md)

300

301

## Utilities and Shortcuts

302

303

```python { .api }

304

def render(request, template_name: str, context=None, content_type=None, status=None, using=None) -> HttpResponse: ...

305

def redirect(to, *args, permanent=False, **kwargs) -> HttpResponse: ...

306

def get_object_or_404(klass, *args, **kwargs): ...

307

def get_list_or_404(klass, *args, **kwargs): ...

308

```

309

310

## Configuration

311

312

```python { .api }

313

settings: LazySettings

314

315

class Settings: ...

316

class LazySettings: ...

317

```

318

319

## Exception Types

320

321

```python { .api }

322

# Database exceptions

323

class DatabaseError(Exception): ...

324

class IntegrityError(DatabaseError): ...

325

326

# HTTP exceptions

327

class Http404(Exception): ...

328

329

# URL exceptions

330

class NoReverseMatch(Exception): ...

331

332

# Template exceptions

333

class TemplateDoesNotExist(Exception): ...

334

335

# Form exceptions

336

class ValidationError(Exception): ...

337

```