Debian Codegraph @

docs/admin.rst

raw
1 .. _admin-interface:
2
3 Admin Interface
4 ===============
5
6 Many web applications ship with an "admin area", where priveleged users can
7 view and modify content. By introspecting your application's models, flask-peewee
8 can provide you with straightforward, easily-extensible forms for managing your
9 application content.
10
11 Here's a screen-shot of the admin dashboard:
12
13 .. image:: fp-admin.png
14
15 You can also try out a custom theme. Here is the *crux* theme:
16
17 .. image:: fp-crux-full.png
18
19 Getting started
20 ---------------
21
22 To get started with the admin, there are just a couple steps:
23
24 1. Instantiate an :py:class:`Auth` backend for your project -- this component
25 is responsible for providing the security for the admin area
26
27 .. code-block:: python
28
29 from flask import Flask
30
31 from flask_peewee.auth import Auth
32 from flask_peewee.db import Database
33
34 app = Flask(__name__)
35 db = Database(app)
36
37 # needed for authentication
38 auth = Auth(app, db)
39
40
41 2. Instantiate an :py:class:`Admin` object
42
43 .. code-block:: python
44
45 # continued from above...
46 from flask_peewee.admin import Admin
47
48 admin = Admin(app, auth)
49
50 3. Register any :py:class:`ModelAdmin` or :py:class:`AdminPanel` objects you
51 would like to expose via the admin
52
53 .. code-block:: python
54
55 # continuing... assuming "Blog" and "Entry" models
56 admin.register(Blog) # register "Blog" with vanilla ModelAdmin
57 admin.register(Entry, EntryAdmin) # register "Entry" with a custom ModelAdmin subclass
58
59 # assume we have an "AdminPanel" called "NotePanel"
60 admin.register_panel('Notes', NotePanel)
61
62 4. Call :py:meth:`Admin.setup()`, which registers the admin blueprint and configures the urls
63
64 .. code-block:: python
65
66 # after all models and panels are registered, configure the urls
67 admin.setup()
68
69 .. note::
70
71 For a complete example, check the `example app
72 <https://github.com/coleifer/flask-peewee/tree/master/example>`_ which ships
73 with the project.
74
75
76 Customizing how models are displayed
77 ------------------------------------
78
79 We'll use the "Message" model taken from the `example app <https://github.com/coleifer/flask-peewee/tree/master/example>`_,
80 which looks like this:
81
82 .. code-block:: python
83
84 class Message(db.Model):
85 user = ForeignKeyField(User)
86 content = TextField()
87 pub_date = DateTimeField(default=datetime.datetime.now)
88
89 def __str__(self):
90 return '%s: %s' % (self.user, self.content)
91
92 If we were to simply register this model with the admin, it would look something
93 like this:
94
95 .. code-block:: python
96
97 admin = Admin(app, auth)
98 admin.register(Message)
99
100 admin.setup()
101
102 .. image:: fp-message-admin-plain.png
103
104 A quick way to improve the appearance of this view is to specify which columns
105 to display. To start customizing how the ``Message`` model is displayed in the
106 admin, we'll subclass :py:class:`ModelAdmin`.
107
108 .. code-block:: python
109
110 from flask_peewee.admin import ModelAdmin
111
112 class MessageAdmin(ModelAdmin):
113 columns = ('user', 'content', 'pub_date',)
114 foreign_key_lookups = {'user': 'username'}
115 filter_fields = ('user', 'content', 'pub_date', 'user__username')
116 search_fields = ('content', 'user__username')
117
118 admin.register(Message, MessageAdmin)
119
120 admin.setup()
121
122 Now the admin shows all the columns and they can be clicked to sort the data.
123 Filtering is available, as is search:
124
125 .. image:: fp-message-admin.png
126
127 Searching
128 ^^^^^^^^^
129
130 Set ``search_fields`` to add a quick-search box above the list. It runs a
131 case-insensitive substring match over char/text fields and supports ``__``
132 traversal into related models -- so ``('content', 'user__username')`` searches
133 both the message body and the author's username, joining ``User`` automatically:
134
135 .. code-block:: python
136
137 class MessageAdmin(ModelAdmin):
138 columns = ('user', 'content', 'pub_date',)
139 search_fields = ('content', 'user__username')
140
141 Leaving ``search_fields`` empty (the default) hides the search box entirely.
142
143 Filtering
144 ^^^^^^^^^
145
146 The list and export views expose per-field filters (equals, less-than, contains,
147 etc., chosen by field type). By default every field is filterable; two
148 attributes narrow that:
149
150 * ``filter_fields`` -- a whitelist of the only fields that may be filtered
151 * ``filter_exclude`` -- a blacklist of fields to hide from filtering
152
153 Both accept ``__`` notation for related fields, so
154 ``filter_exclude = ('user__password',)`` keeps a sensitive related column out of
155 the filter UI entirely.
156
157 Restricting the queryset
158 ^^^^^^^^^^^^^^^^^^^^^^^^^
159
160 Suppose privacy is a big concern, and under no circumstances should a user be
161 able to see another user's messages -- even in the admin. This can be done by overriding
162 the :py:meth:`~ModelAdmin.get_query` method:
163
164 .. code-block:: python
165
166 def get_query(self):
167 return self.model.select().where(self.model.user == g.user)
168
169 Now a user will only be able to see and edit their own messages.
170
171
172 Overriding Admin Templates
173 ^^^^^^^^^^^^^^^^^^^^^^^^^^
174
175 Use the :py:meth:`ModelAdmin.get_template_overrides` method to override templates
176 for an individual ``Model``:
177
178 .. code-block:: python
179
180 class MessageAdmin(ModelAdmin):
181 # ...
182
183 def get_template_overrides(self):
184 # override the edit template with a custom one
185 return {'edit': 'messages/admin/edit.html'}
186
187 admin.register(Message, MessageAdmin)
188
189 This instructs the admin to use a custom template for the edit page in the Message
190 admin. That template is stored in the application's templates. It might look
191 something like this:
192
193 .. code-block:: jinja
194
195 {% extends "admin/models/edit.html" %} {# override the default edit template #}
196
197 {# override any blocks here #}
198
199 There are five templates that can be overridden:
200
201 * index
202 * add
203 * edit
204 * delete
205 * export
206
207
208 Nicer display for Foreign Key fields
209 ------------------------------------
210
211 By default a foreign key renders as a ``<select>`` of the related rows. How that
212 holds up when the related table is large depends on where it appears:
213
214 * In **filters**, the ``<select>`` is automatically capped at the first 20 rows
215 (plus whichever row is currently selected), so the page never balloons -- but
216 only those 20 rows are reachable.
217 * In **model forms** (add/edit), the ``<select>`` is *not* capped: every related
218 row is rendered, which is slow to load and hammers the database on a large
219 table.
220
221 To handle large related tables, set ``foreign_key_lookups`` -- a mapping of the
222 foreign-key field name to the related field to search and display on. This
223 replaces the plain ``<select>`` with a paginated, type-ahead search backed by the
224 model admin's ``ajax_list`` endpoint (matching ``<field> LIKE '%query%'``, a page
225 at a time), so any row is reachable no matter how large the table:
226
227 .. code-block:: python
228
229 class MessageAdmin(ModelAdmin):
230 columns = ('user', 'content', 'pub_date',)
231 foreign_key_lookups = {'user': 'username'}
232
233 The widget differs between the two contexts:
234
235 Filters
236 ^^^^^^^
237
238 Without ``foreign_key_lookups`` the ``user`` filter is a ``<select>`` of the
239 first 20 users -- fine for a small table, but on a large one you can only filter
240 by those first 20. With it, the ``<select>`` gains an inline type-ahead search
241 that repopulates its options from ``ajax_list`` as you type, so any user can be
242 selected.
243
244 Model forms
245 ^^^^^^^^^^^
246
247 Without ``foreign_key_lookups`` an add or edit form renders every related row in a
248 single ``<select>`` -- the case worth avoiding on a large table. With it, the
249 field becomes a button showing the current selection; clicking it opens a modal
250 with a paginated, type-ahead list:
251
252 .. image:: fp-message-fk-btn.png
253
254 .. image:: fp-message-fk-modal.png
255
256
257 Bulk actions
258 ------------
259
260 Every row in the list view has a checkbox, and the **"With selected..."**
261 dropdown offers *Export* and *Delete* out-of-the-box. You can add your own
262 bulk operations by subclassing :py:class:`Action` and listing instances in your
263 :py:class:`ModelAdmin`'s ``actions`` attribute.
264
265 An action implements a single ``callback(self, id_list)`` method, which receives
266 the list of primary keys the user checked. Suppose our ``Message`` model has a
267 ``flagged`` boolean and we want a one-click way to flag the selected rows:
268
269 .. code-block:: python
270
271 from flask_peewee.admin import Action, ModelAdmin
272
273 class FlagAction(Action):
274 def callback(self, id_list):
275 Message.update(flagged=True).where(Message.id << id_list).execute()
276
277 class MessageAdmin(ModelAdmin):
278 columns = ('user', 'content', 'pub_date', 'flagged',)
279 actions = [FlagAction()]
280
281 admin.register(Message, MessageAdmin)
282
283 The action shows up in the "With selected..." dropdown labeled with its
284 ``name``, which defaults to the class name minus the "Action" suffix
285 (``FlagAction`` becomes "Flag"). Pass ``name`` (and optionally ``description``)
286 to the constructor to override it, e.g. ``FlagAction(name='Flag as spam')``.
287
288 If a callback returns a Flask ``Response``, it is sent to the user as-is -- handy
289 for generating a download from the selected rows:
290
291 .. code-block:: python
292
293 from flask import Response
294
295 class ExportContentAction(Action):
296 def callback(self, id_list):
297 rows = Message.select().where(Message.id << id_list)
298 body = '\n'.join(msg.content for msg in rows)
299 return Response(body, mimetype='text/plain', headers={
300 'Content-Disposition': 'attachment; filename=messages.txt'})
301
302 If the callback returns anything else, the user is redirected back to the list
303 view. Submitting an action with no rows selected simply flashes a warning and
304 does nothing.
305
306
307 Exporting data
308 --------------
309
310 Every registered model gets an **Export** view (also reachable from the list
311 view's "With selected..." dropdown). It lets you choose which fields to include
312 -- across foreign keys, too -- and downloads the result as a JSON file, honoring
313 whatever filters are currently applied.
314
315 By default every field is exportable. Two :py:class:`ModelAdmin` attributes
316 restrict that:
317
318 * ``export_fields`` -- a whitelist of field names that may be exported
319 * ``export_exclude`` -- a blacklist of field names to withhold
320
321 .. code-block:: python
322
323 class UserAdmin(ModelAdmin):
324 columns = ('username', 'email',)
325 export_exclude = ('password',) # never allow the password hash out
326
327 These restrictions are enforced **server-side**: hand-posting a withheld field
328 name will not dump it, so ``export_exclude = ('password',)`` is a real guarantee
329 rather than a merely-hidden checkbox.
330
331 Related fields are exported nested under their foreign key. A related model
332 defers to *its own* registered :py:class:`ModelAdmin`'s
333 ``export_fields``/``export_exclude``, so once ``UserAdmin`` excludes ``password``
334 above, no other model's export can reach ``user__password`` either. Exporting,
335 say, the ``user``, ``content`` and ``user__username`` fields of ``Message``
336 produces:
337
338 .. code-block:: json
339
340 [
341 {"user": {"username": "admin"}, "content": "hello"},
342 {"user": {"username": "coleifer"}, "content": "flask + peewee"}
343 ]
344
345 .. note::
346 Because related data nests under its foreign key, that foreign key is
347 included automatically -- there is no way to nest a related field without it.
348
349
350 Creating admin panels
351 ---------------------
352
353 :py:class:`AdminPanel` classes provide a way of extending the admin dashboard with arbitrary functionality.
354 These are displayed as "panels" on the admin dashboard with a customizable
355 template. They may additionally, however, define any views and urls. These
356 views will automatically be protected by the same authentication used throughout
357 the admin area.
358
359 Some example use-cases for AdminPanels might be:
360
361 * Display some at-a-glance functionality in the dashboard, like stats on new
362 user signups.
363 * Provide a set of views that should only be visible to site administrators,
364 for example a mailing-list app.
365 * Control global site settings, turn on and off features, etc.
366
367 Referring to the `example app <https://github.com/coleifer/flask-peewee/tree/master/example>`_,
368 we'll look at a simple panel that allows administrators to leave "notes" in the admin area:
369
370 .. image:: fp-notes-panel.png
371
372 Here's what the panel class looks like:
373
374 .. code-block:: python
375
376 class NotePanel(AdminPanel):
377 template_name = 'admin/notes.html'
378
379 def get_urls(self):
380 return (
381 ('/create/', self.create),
382 )
383
384 def create(self):
385 if request.method == 'POST':
386 if request.form.get('message'):
387 Note.create(
388 user=auth.get_logged_in_user(),
389 message=request.form['message'])
390
391 next = request.form.get('next') or self.dashboard_url()
392 return redirect(next)
393
394 def get_context(self):
395 # Get the 3 latest notes.
396 notes = Note.select().order_by(Note.created_date.desc()).paginate(1, 3)
397 return {'note_list': notes}
398
399 When the admin dashboard is rendered (``/admin/``), all panels are rendered using
400 the templates the specify. The template is rendered with the context provided
401 by the panel's ``get_context`` method.
402
403 And the template:
404
405 .. code-block:: jinja
406
407 {% extends "admin/panels/default.html" %}
408
409 {% block panel_content %}
410 {% for note in note_list %}
411 <p>{{ note.user.username }}: {{ note.message }}</p>
412 {% endfor %}
413 <form method="post" action="{{ url_for(panel.get_url_name('create')) }}">
414 <input type="hidden" value="{{ request.url }}" />
415 <p><textarea name="message" class="form-control"></textarea></p>
416 <button type="submit" class="btn btn-secondary btn-sm">Save</button>
417 </form>
418 {% endblock %}
419
420 A panel can provide as many urls and views as you like. These views will all be
421 protected by the same authentication as other parts of the admin area.
422
423
424 Handling File Uploads
425 ---------------------
426
427 Flask and wtforms both provide support for handling file uploads (on the server
428 and generating form fields). Peewee, however, does not have a "file field" --
429 generally I store a path to a file on disk and thus use a ``CharField`` for
430 the storage.
431
432 Here's a very simple example of a "photo" model and a ``ModelAdmin`` that enables
433 file uploads.
434
435 .. code-block:: python
436
437 # models.py
438 import datetime
439 import os
440
441 from markupsafe import Markup
442 from peewee import *
443 from werkzeug.utils import secure_filename
444
445 from app import app, db
446
447
448 class Photo(db.Model):
449 image = CharField()
450
451 def __str__(self):
452 return self.image
453
454 def save_image(self, file_obj):
455 self.image = secure_filename(file_obj.filename)
456 full_path = os.path.join(app.config['MEDIA_ROOT'], self.image)
457 file_obj.save(full_path)
458 self.save()
459
460 def url(self):
461 return os.path.join(app.config['MEDIA_URL'], self.image)
462
463 def thumb(self):
464 return Markup('<img src="%s" style="height: 80px;" />' % self.url())
465
466 .. code-block:: python
467
468 # admin.py
469 from flask import request
470 from flask_peewee.admin import Admin, ModelAdmin
471 from wtforms.fields import FileField, HiddenField
472 from wtforms.form import Form
473
474 from app import app, db
475 from auth import auth
476 from models import Photo
477
478
479 admin = Admin(app, auth)
480
481
482 class PhotoAdmin(ModelAdmin):
483 columns = ['image', 'thumb']
484
485 def get_form(self, adding=False):
486 class PhotoForm(Form):
487 image = HiddenField()
488 image_file = FileField('Image file')
489
490 return PhotoForm
491
492 def save_model(self, instance, form, adding=False):
493 instance = super(PhotoAdmin, self).save_model(instance, form, adding)
494 if 'image_file' in request.files:
495 file = request.files['image_file']
496 instance.save_image(file)
497 return instance
498
499 admin.register(Photo, PhotoAdmin)