0
# Core Framework
1
2
Core functionality providing the foundation for all Nautobot modules including Django setup, base models, API infrastructure, form handling, job system, and plugin architecture.
3
4
## Capabilities
5
6
### Setup and Initialization
7
8
Configure Django with Nautobot settings and initialize the application.
9
10
```python { .api }
11
def setup(config_path=None):
12
"""
13
Configure Django with Nautobot settings.
14
15
Args:
16
config_path (str, optional): Path to configuration file
17
"""
18
19
def add_success_logger():
20
"""Add a custom log level for success messages."""
21
22
def add_failure_logger():
23
"""Add a custom log level for failure messages."""
24
```
25
26
### Base Model Classes
27
28
Foundation classes for all Nautobot models providing common functionality.
29
30
```python { .api }
31
class BaseModel:
32
"""
33
Abstract base model with UUID primary key, natural keys, and validation.
34
35
Attributes:
36
id (UUID): Primary key
37
created (datetime): Creation timestamp
38
last_updated (datetime): Last modification timestamp
39
"""
40
41
class BaseManager:
42
"""Custom model manager with additional functionality."""
43
44
class RestrictedQuerySet:
45
"""Queryset with user permissions filtering."""
46
47
class ContentTypeRelatedQuerySet:
48
"""ContentType-aware queryset for generic relations."""
49
50
class CompositeKeyQuerySetMixin:
51
"""Mixin for composite key support."""
52
```
53
54
### Model Utilities
55
56
Helper functions for working with models and keys.
57
58
```python { .api }
59
def construct_composite_key(*args):
60
"""Build composite keys from multiple values."""
61
62
def construct_natural_slug(value, max_length=50):
63
"""Generate natural slugs from values."""
64
65
def deconstruct_composite_key(key):
66
"""Parse composite keys into components."""
67
```
68
69
### API Serializers
70
71
Base serializer classes for REST API operations.
72
73
```python { .api }
74
class BaseModelSerializer:
75
"""Base serializer for all Nautobot models."""
76
77
class NautobotModelSerializer:
78
"""Main model serializer with common functionality."""
79
80
class BulkOperationSerializer:
81
"""Serializer for bulk operations."""
82
83
class BulkOperationIntegerIDSerializer:
84
"""Serializer for bulk operations using integer IDs."""
85
86
class CustomFieldModelSerializerMixin:
87
"""Mixin for custom fields integration."""
88
89
class GraphQLAPISerializer:
90
"""Serializer for GraphQL API operations."""
91
92
class OptInFieldsMixin:
93
"""Mixin for optional field selection."""
94
95
class PolymorphicProxySerializer:
96
"""Serializer for polymorphic proxy models."""
97
98
class RenderJinjaSerializer:
99
"""Serializer for Jinja template rendering."""
100
101
class ValidatedModelSerializer:
102
"""Serializer with comprehensive validation."""
103
104
class WritableNestedSerializer:
105
"""Serializer for nested object creation/updates."""
106
107
class NotesSerializerMixin:
108
"""Mixin for notes functionality."""
109
110
class RelationshipModelSerializerMixin:
111
"""Mixin for object relationships."""
112
113
class TreeModelSerializerMixin:
114
"""Mixin for hierarchical data support."""
115
```
116
117
### API Fields
118
119
Specialized field types for API serialization.
120
121
```python { .api }
122
class ChoiceField:
123
"""Choice field for API serialization."""
124
125
class ContentTypeField:
126
"""Django ContentType field for APIs."""
127
128
class LaxURLField:
129
"""URL field with relaxed validation."""
130
131
class NautobotHyperlinkedRelatedField:
132
"""Hyperlinked related object field."""
133
134
class ObjectTypeField:
135
"""Field for object type selection."""
136
137
class SerializedPKRelatedField:
138
"""Primary key relation field."""
139
140
class TimeZoneSerializerField:
141
"""Timezone handling field."""
142
```
143
144
### Form Classes
145
146
Base form classes with Bootstrap styling and common functionality.
147
148
```python { .api }
149
class BootstrapMixin:
150
"""Bootstrap UI styling mixin."""
151
152
class BulkEditForm:
153
"""Form for bulk editing operations."""
154
155
class BulkRenameForm:
156
"""Form for bulk renaming operations."""
157
158
class ConfirmationForm:
159
"""User confirmation dialog form."""
160
161
class CSVModelForm:
162
"""Form for CSV import/export operations."""
163
164
class DynamicFilterForm:
165
"""Form for dynamic filtering."""
166
167
class ImportForm:
168
"""Data import form."""
169
170
class ReturnURLForm:
171
"""Form with return URL handling."""
172
173
class TableConfigForm:
174
"""Table configuration form."""
175
176
class SearchForm:
177
"""Search functionality form."""
178
```
179
180
### Form Fields
181
182
Specialized form field types with validation and widgets.
183
184
```python { .api }
185
class AutoPositionField:
186
"""Field with automatic positioning."""
187
188
class CSVChoiceField:
189
"""CSV choice field."""
190
191
class CSVModelChoiceField:
192
"""CSV model choice field."""
193
194
class DynamicModelChoiceField:
195
"""Dynamic model selection field."""
196
197
class ExpandableIPAddressField:
198
"""IP address field with expansion support."""
199
200
class JSONField:
201
"""JSON data input field."""
202
203
class MACAddressField:
204
"""MAC address validation field."""
205
206
class SlugField:
207
"""URL-safe slug field."""
208
209
class TagFilterField:
210
"""Tag filtering field."""
211
```
212
213
### Form Widgets
214
215
Custom widgets for form fields.
216
217
```python { .api }
218
class APISelect:
219
"""API-driven select widget."""
220
221
class APISelectMultiple:
222
"""API-driven multi-select widget."""
223
224
class ColorSelect:
225
"""Color picker widget."""
226
227
class DatePicker:
228
"""Date selection widget."""
229
230
class StaticSelect2:
231
"""Select2 integration widget."""
232
```
233
234
### System Jobs
235
236
Built-in system jobs for common operations.
237
238
```python { .api }
239
class GitRepositorySync:
240
"""Job to sync Git repositories."""
241
242
class GitRepositoryDryRun:
243
"""Job for dry run Git sync operations."""
244
245
class ExportObjectList:
246
"""Job to export objects to CSV/YAML."""
247
248
class ImportObjects:
249
"""Job to import objects from CSV."""
250
251
class BulkDeleteObjects:
252
"""Job for bulk delete operations."""
253
254
class BulkEditObjects:
255
"""Job for bulk edit operations."""
256
257
class LogsCleanup:
258
"""Job to clean up old logs."""
259
260
class RefreshDynamicGroupCaches:
261
"""Job to refresh dynamic group caches."""
262
```
263
264
### App Configuration
265
266
Base classes for app and plugin configuration.
267
268
```python { .api }
269
class NautobotConfig:
270
"""Base app configuration class."""
271
272
class CoreConfig:
273
"""Core app configuration."""
274
```
275
276
### UI Components
277
278
Components for building the Nautobot user interface.
279
280
```python { .api }
281
class HomePagePanel:
282
"""Homepage layout panels."""
283
284
class HomePageGroup:
285
"""Homepage panel groups."""
286
287
class HomePageItem:
288
"""Homepage panel items."""
289
290
class NavMenuTab:
291
"""Navigation menu tabs."""
292
293
class NavMenuGroup:
294
"""Navigation menu groups."""
295
296
class NavMenuItem:
297
"""Navigation menu items."""
298
299
class NavMenuButton:
300
"""Navigation menu buttons."""
301
302
class NavMenuAddButton:
303
"""Navigation menu add buttons."""
304
305
class NavMenuImportButton:
306
"""Navigation menu import buttons."""
307
308
class PermissionsMixin:
309
"""Permissions mixin for UI components."""
310
```
311
312
### Registration Functions
313
314
Functions for registering UI components and extensions.
315
316
```python { .api }
317
def register_menu_items(menu_items):
318
"""Register navigation menu items."""
319
320
def register_homepage_panels(panels):
321
"""Register homepage panels."""
322
```
323
324
### GraphQL Interface
325
326
GraphQL query execution and utilities.
327
328
```python { .api }
329
def execute_query(query, variables=None, request=None, user=None):
330
"""Execute GraphQL queries."""
331
332
def execute_saved_query(saved_query_name, **kwargs):
333
"""Execute saved GraphQL queries."""
334
```
335
336
### CLI Management
337
338
Command-line interface utilities and management commands.
339
340
The `nautobot-server` command provides extensive CLI functionality:
341
342
```bash
343
nautobot-server --help
344
nautobot-server migrate
345
nautobot-server runserver
346
nautobot-server createsuperuser
347
nautobot-server collectstatic
348
```
349
350
## Usage Examples
351
352
### Basic Setup
353
354
```python
355
import nautobot
356
357
# Initialize Nautobot with default configuration
358
nautobot.setup()
359
360
# Check version
361
print(f"Nautobot version: {nautobot.__version__}")
362
```
363
364
### Custom Model Creation
365
366
```python
367
from nautobot.core.models import BaseModel
368
from django.db import models
369
370
class MyCustomModel(BaseModel):
371
name = models.CharField(max_length=100)
372
description = models.TextField(blank=True)
373
374
class Meta:
375
ordering = ['name']
376
377
def __str__(self):
378
return self.name
379
```
380
381
### API Serializer Usage
382
383
```python
384
from nautobot.core.api.serializers import NautobotModelSerializer
385
from .models import MyCustomModel
386
387
class MyCustomModelSerializer(NautobotModelSerializer):
388
class Meta:
389
model = MyCustomModel
390
fields = '__all__'
391
```
392
393
### Form Creation
394
395
```python
396
from nautobot.core.forms import BootstrapMixin
397
from django import forms
398
from .models import MyCustomModel
399
400
class MyCustomModelForm(BootstrapMixin, forms.ModelForm):
401
class Meta:
402
model = MyCustomModel
403
fields = ['name', 'description']
404
```
405
406
### Job Implementation
407
408
```python
409
from nautobot.core.jobs import Job
410
from nautobot.extras.models import Status
411
412
class MyCustomJob(Job):
413
class Meta:
414
name = "My Custom Job"
415
description = "Performs custom automation task"
416
417
def run(self):
418
self.log_info("Starting custom job")
419
420
# Job logic here
421
result = "Job completed successfully"
422
423
self.log_success(result)
424
return result
425
```
426
427
## Error Handling
428
429
Common error patterns and handling:
430
431
```python
432
from nautobot.core.models import BaseModel
433
from django.core.exceptions import ValidationError
434
435
try:
436
obj = BaseModel.objects.get(id=some_uuid)
437
except BaseModel.DoesNotExist:
438
# Handle missing object
439
pass
440
except ValidationError as e:
441
# Handle validation errors
442
print(f"Validation error: {e}")
443
```