or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

admin.mdconfiguration.mdfields.mdindex.mdmodels.mdtemplate-utils.md

fields.mddocs/

0

# Django Form Fields

1

2

Django Filer provides custom model fields that integrate filer objects into your Django models with rich admin widgets. These fields automatically handle the relationship to filer objects and provide user-friendly interfaces in the Django admin.

3

4

## Capabilities

5

6

### FilerFileField

7

8

A Django ForeignKey field that creates relationships to filer File objects with an integrated admin widget for file selection.

9

10

```python { .api }

11

class FilerFileField(models.ForeignKey):

12

"""

13

Django model field for referencing filer File objects.

14

15

Automatically configures:

16

- to='filer.File' (hard-coded target model)

17

- default_form_class=AdminFileFormField

18

- Admin widget with file browser popup

19

20

Args:

21

All standard ForeignKey arguments except 'to' (which is fixed)

22

"""

23

24

def __init__(self, **kwargs):

25

"""Initialize the field, setting target model to filer.File."""

26

27

def formfield(self, **kwargs):

28

"""Return form field with admin widget."""

29

30

class AdminFileFormField(forms.ModelChoiceField):

31

"""Form field class used by FilerFileField in admin."""

32

33

def __init__(self, rel, queryset, to_field_name, *args, **kwargs):

34

"""

35

Initialize admin form field.

36

37

Args:

38

rel: Field relation object

39

queryset: QuerySet of available files

40

to_field_name: Target field name

41

"""

42

43

class AdminFileWidget(ForeignKeyRawIdWidget):

44

"""Admin widget for file selection with popup browser."""

45

46

def render(self, name, value, attrs=None, renderer=None):

47

"""

48

Render the widget HTML.

49

50

Args:

51

name (str): Field name

52

value: Current field value

53

attrs (dict): HTML attributes

54

renderer: Template renderer

55

56

Returns:

57

str: Rendered HTML

58

"""

59

60

def label_for_value(self, value):

61

"""Get display label for the current value."""

62

63

def obj_for_value(self, value):

64

"""Get File object for the given value."""

65

```

66

67

### FilerImageField

68

69

A specialized field for referencing filer Image objects, extending FilerFileField with image-specific functionality.

70

71

```python { .api }

72

class FilerImageField(FilerFileField):

73

"""

74

Django model field for referencing filer Image objects.

75

76

Inherits from FilerFileField but targets Image model by default.

77

Uses specialized admin widget for image selection.

78

79

Args:

80

All FilerFileField arguments

81

"""

82

83

# Automatically configured

84

default_form_class = AdminImageFormField

85

default_model_class = settings.FILER_IMAGE_MODEL

86

87

class AdminImageFormField(AdminFileFormField):

88

"""Form field class used by FilerImageField in admin."""

89

90

class AdminImageWidget(AdminFileWidget):

91

"""Admin widget for image selection with image preview."""

92

```

93

94

### FilerFolderField

95

96

A Django ForeignKey field for referencing filer Folder objects with folder browser widget.

97

98

```python { .api }

99

class FilerFolderField(models.ForeignKey):

100

"""

101

Django model field for referencing filer Folder objects.

102

103

Automatically configures:

104

- to='filer.Folder' (hard-coded target model)

105

- default_form_class=AdminFolderFormField

106

- Admin widget with folder browser popup

107

108

Args:

109

All standard ForeignKey arguments except 'to' (which is fixed)

110

"""

111

112

def __init__(self, **kwargs):

113

"""Initialize the field, setting target model to filer.Folder."""

114

115

def formfield(self, **kwargs):

116

"""Return form field with admin widget."""

117

118

class AdminFolderFormField(forms.ModelChoiceField):

119

"""Form field class used by FilerFolderField in admin."""

120

121

def __init__(self, rel, queryset, to_field_name, *args, **kwargs):

122

"""

123

Initialize admin form field.

124

125

Args:

126

rel: Field relation object

127

queryset: QuerySet of available folders

128

to_field_name: Target field name

129

"""

130

131

class AdminFolderWidget(ForeignKeyRawIdWidget):

132

"""Admin widget for folder selection with popup browser."""

133

134

def render(self, name, value, attrs=None, renderer=None):

135

"""

136

Render the widget HTML.

137

138

Args:

139

name (str): Field name

140

value: Current field value

141

attrs (dict): HTML attributes

142

renderer: Template renderer

143

144

Returns:

145

str: Rendered HTML with folder browser

146

"""

147

148

def label_for_value(self, value):

149

"""Get display label for the current value."""

150

151

def obj_for_value(self, value):

152

"""Get Folder object for the given value."""

153

```

154

155

### MultiStorageFileField

156

157

Internal field used by filer models to support both public and private file storage.

158

159

```python { .api }

160

class MultiStorageFileField(models.FileField):

161

"""

162

File field supporting both public and private storage backends.

163

164

Automatically routes files to appropriate storage based on

165

the is_public flag of the containing model.

166

167

Args:

168

All standard FileField arguments

169

"""

170

171

def __init__(self, *args, **kwargs):

172

"""Initialize field with storage configuration."""

173

174

class MultiStorageFieldFile:

175

"""File wrapper class handling public/private storage routing."""

176

177

@property

178

def url(self):

179

"""Get URL appropriate for the storage type."""

180

181

class MultiStorageFileDescriptor:

182

"""Field descriptor with data change callbacks."""

183

```

184

185

## Usage Examples

186

187

### Basic Field Usage

188

189

```python

190

from django.db import models

191

from filer.fields import FilerFileField, FilerImageField, FilerFolderField

192

193

class Article(models.Model):

194

title = models.CharField(max_length=200)

195

content = models.TextField()

196

197

# Optional file attachment

198

attachment = FilerFileField(

199

null=True,

200

blank=True,

201

related_name="article_attachments",

202

on_delete=models.SET_NULL

203

)

204

205

# Featured image

206

featured_image = FilerImageField(

207

null=True,

208

blank=True,

209

related_name="article_images",

210

on_delete=models.SET_NULL

211

)

212

213

# Category folder

214

category_folder = FilerFolderField(

215

null=True,

216

blank=True,

217

related_name="article_categories",

218

on_delete=models.SET_NULL

219

)

220

221

class Gallery(models.Model):

222

name = models.CharField(max_length=100)

223

224

# Multiple images using ManyToManyField

225

images = models.ManyToManyField(

226

'filer.Image',

227

through='GalleryImage',

228

blank=True

229

)

230

231

class GalleryImage(models.Model):

232

gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE)

233

image = FilerImageField(on_delete=models.CASCADE)

234

order = models.PositiveIntegerField(default=0)

235

caption = models.CharField(max_length=255, blank=True)

236

```

237

238

### Advanced Field Configuration

239

240

```python

241

from filer.fields import FilerFileField, FilerImageField

242

243

class Document(models.Model):

244

title = models.CharField(max_length=200)

245

246

# File field with custom validation

247

file = FilerFileField(

248

on_delete=models.CASCADE,

249

related_name="document_files",

250

# Add help text for admin

251

help_text="Upload a PDF or Word document"

252

)

253

254

# Thumbnail image with size constraints

255

thumbnail = FilerImageField(

256

null=True,

257

blank=True,

258

on_delete=models.SET_NULL,

259

related_name="document_thumbnails",

260

help_text="Optional thumbnail image (recommended: 300x200px)"

261

)

262

263

class UserProfile(models.Model):

264

user = models.OneToOneField('auth.User', on_delete=models.CASCADE)

265

266

# Avatar image

267

avatar = FilerImageField(

268

null=True,

269

blank=True,

270

on_delete=models.SET_NULL,

271

related_name="user_avatars"

272

)

273

274

# Documents folder

275

documents_folder = FilerFolderField(

276

null=True,

277

blank=True,

278

on_delete=models.SET_NULL,

279

related_name="user_document_folders"

280

)

281

```

282

283

### Working with Field Values

284

285

```python

286

# Accessing file properties through the field

287

article = Article.objects.get(pk=1)

288

289

if article.attachment:

290

print(f"File name: {article.attachment.name}")

291

print(f"File URL: {article.attachment.url}")

292

print(f"File size: {article.attachment.size}")

293

print(f"File extension: {article.attachment.extension}")

294

295

# Check permissions

296

if article.attachment.has_read_permission(request.user):

297

# User can access this file

298

file_url = article.attachment.url

299

300

if article.featured_image:

301

print(f"Image dimensions: {article.featured_image.width}x{article.featured_image.height}")

302

print(f"Image URL: {article.featured_image.url}")

303

304

# Get image EXIF data

305

exif_data = article.featured_image.exif

306

307

if article.category_folder:

308

print(f"Folder path: {article.category_folder.logical_path}")

309

print(f"Files in folder: {article.category_folder.file_count}")

310

```

311

312

### Custom Admin Configuration

313

314

```python

315

from django.contrib import admin

316

from filer.fields import FilerFileField, FilerImageField

317

318

class ArticleAdmin(admin.ModelAdmin):

319

list_display = ['title', 'attachment', 'featured_image']

320

321

# Customize the admin interface

322

fieldsets = (

323

('Content', {

324

'fields': ('title', 'content')

325

}),

326

('Media', {

327

'fields': ('featured_image', 'attachment'),

328

'classes': ('collapse',)

329

}),

330

)

331

332

# Raw ID fields for better performance with large datasets

333

raw_id_fields = ['featured_image', 'attachment']

334

335

admin.site.register(Article, ArticleAdmin)

336

```

337

338

### Form Usage Outside Admin

339

340

```python

341

from django import forms

342

from filer.fields import FilerFileField

343

344

class ArticleForm(forms.ModelForm):

345

class Meta:

346

model = Article

347

fields = ['title', 'content', 'attachment', 'featured_image']

348

349

def __init__(self, *args, **kwargs):

350

super().__init__(*args, **kwargs)

351

352

# Customize field widgets for non-admin forms

353

self.fields['attachment'].widget = forms.HiddenInput()

354

self.fields['featured_image'].widget = forms.HiddenInput()

355

356

# Or use custom widgets

357

# self.fields['attachment'].widget = CustomFileWidget()

358

```

359

360

## Field Configuration Options

361

362

### Common Field Arguments

363

364

All filer fields support standard Django ForeignKey arguments:

365

366

```python

367

# Relationship configuration

368

on_delete=models.CASCADE # Required

369

null=True, blank=True # Optional fields

370

related_name="custom_name" # Reverse relation name

371

372

# Admin configuration

373

help_text="Upload instructions"

374

verbose_name="Display Name"

375

376

# Validation

377

limit_choices_to={'is_public': True} # Limit available choices

378

```

379

380

### Storage Considerations

381

382

```python

383

# Files are automatically routed to public/private storage

384

# based on the File.is_public flag

385

386

# For guaranteed public access:

387

class PublicDocument(models.Model):

388

file = FilerFileField(

389

on_delete=models.CASCADE,

390

limit_choices_to={'is_public': True}

391

)

392

393

# For controlled access:

394

class PrivateDocument(models.Model):

395

file = FilerFileField(

396

on_delete=models.CASCADE,

397

limit_choices_to={'is_public': False}

398

)

399

```