/
grids.py
1638 lines (1268 loc) · 55.5 KB
/
grids.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Components for creating customizable datagrids from database data.
Datagrids are used to display a table-based view of data from a database,
complete with pagination, batch selection, sorting, and flexible column
rendering.
Datagrids have one or more :py:class:`Column` subclasses associated, which will
render the data. The datagrid may display a subset of the rendered columns,
and users can choose which of those columns they want displayed, and in which
order.
There are two main types of datagrids:
* :py:class:`DataGrid` is the base class for a datagrid, and will display
the data with standard numerical page-based pagination.
* :py:class:`AlphanumericDataGrid` is similar, but uses a more specific
paginator that allows the user to paginate by the first letter/number/symbol
of the data in a given field. This is useful for lists of users, for
example.
All datagrids are meant to be subclassed.
"""
import logging
import re
import string
import traceback
import pytz
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import InvalidPage, Paginator
from django.http import Http404, HttpResponse
from django.template.defaultfilters import date, timesince
from django.template.loader import get_template, render_to_string
from django.utils.cache import patch_cache_control
from django.utils.functional import cached_property
from django.utils.html import escape, format_html
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from djblets.template.context import get_default_template_context_processors
from djblets.util.http import get_url_params_except
logger = logging.getLogger(__name__)
# Registration of all datagrid classes to columns.
_column_registry = {}
class Column(object):
"""A column in a datagrid.
The column is the primary component of the datagrid. It is used to
display not only the column header but the HTML for the cell as well.
Columns can be tied to database fields and can be used for sorting.
Not all columns have to allow for this, though.
Columns can have an image, text, or both in the column header. The
contents of the cells can be instructed to link to the object on the
row or the data in the cell.
If a Column defines an :py:attr:`image_class`, then it will be assumed that
the class represents an icon, perhaps as part of a spritesheet, and will
display it in a ``<div>``. An :py:attr:`image_url` cannot also be defined.
Attributes:
cell_template (unicode):
The path to a template. If this is not None, this will override
the default cell_template for the DataGrid the column is in.
"""
#: Descending sort order for columns.
SORT_DESCENDING = 0
#: Ascending sort order for columns.
SORT_ASCENDING = 1
def __init__(self, label=None, id=None, detailed_label=None,
detailed_label_html=None, field_name=None, db_field=None,
image_url=None, image_class=None, image_width=None,
image_height=None, image_alt="", shrink=False, expand=False,
sortable=False,
default_sort_dir=SORT_DESCENDING, link=False,
link_func=None, link_css_class=None, cell_clickable=False,
css_class=""):
"""Initialize the column.
When initializing a column as part of a :py:class:`DataGrid` subclass,
a number of options can be provided.
Args:
id (unicode, optional):
The unique ID of the column on the datagrid.
label (unicode, optional):
The label to show in the column header.
detailed_label (unicode, optional):
A detailed label to display in the column customization
menu. Defaults to ``label``.
detailed_label_html (unicode, optional):
A detailed label in HTML form to display in the column
customization menu. This takes precedence over
``detailed_label``.
field_name (unicode, optional):
The name of the field on the model containing the data to
render.
db_field (unicode, optional):
The name of the database field containing the field used
for sorting. Defaults to ``field_name``.
image_url (unicode, optional):
The URL to the image used in the header and navigation menu.
This cannot be used with ``image_class``.
image_class (unicode, optional):
The CSS class of a spritesheet icon to use in the header
and navigation menu. This cannot be used with ``image_url``.
image_width (int, optional):
The width of the image.
image_height (int, optional):
The height of the image.
image_alt (unicode, optional):
The alt text for the image.
shrink (bool, optional):
If ``True``, the column's width will be calculated to its
minimum size.
expand (bool, optional):
If ``True``, the column's width will be calculated to its
maximum size. If there are other expanded columns, they'll
share the available width equally.
sortable (bool, optional):
If ``True``, the column can be sorted. This requires a
``db_field`` that allows for sorting.
default_sort_dir (int, optional):
The default sorting direction when the user activates sorting.
Either :py:attr:`SORT_DESCENDING`
or :py:attr:`SORT_ASCENDING`.
link (bool, optional):
If ``True``, the contents will be linked to the URL
returned by ``link_func`` or
:py:meth:`DataGrid.link_to_object`.
link_func (callable, optional):
Optional function that returns a URL for the link.
link_css_class (unicode or callable, optional):
The CSS class or classes to define on ``<a>`` for the link
for the cell, if setting ``link=True``. This can be a
function returning the classes.
cell_clickable (bool, optional):
If ``True``, clicking anywhere on the cell will navigate to
the URL defined, if any.
css_class (unicode, optional):
The CSS class or classes to define on the cell. This can be
a function returning the classes.
"""
assert not (image_class and image_url)
self.id = id
self.field_name = field_name
self.db_field = db_field or field_name
self.label = label
self.detailed_label = detailed_label or self.label
self.detailed_label_html = detailed_label_html or self.detailed_label
self.image_url = image_url
self.image_class = image_class
self.image_width = image_width
self.image_height = image_height
self.image_alt = image_alt
self.shrink = shrink
self.expand = expand
self.sortable = sortable
self.default_sort_dir = default_sort_dir
self.cell_clickable = False
self.link = link
self.link_func = (
link_func or
(lambda state, x, y: state.datagrid.link_to_object(state, x, y)))
self.link_css_class = link_css_class
self.css_class = css_class
self.cell_template = None
@cached_property
def cell_template_obj(self):
"""Return the cell template, if it exists."""
if self.cell_template:
return get_template(self.cell_template)
return None
def setup_state(self, state):
"""Set up any state that may be needed for the column.
This is called once per column per datagrid instance.
By default, no additional state is set up. Subclasses can override
this to set any variables they may need.
Args:
state (StatefulColumn):
The state for the DataGrid instance.
"""
pass
def get_sort_field(self, state):
"""Return the field used for sorting this column.
By default, this uses the provided db_field.
Args:
state (StatefulColumn):
The state for the DataGrid instance.
Returns:
unicode:
The field on the model used for sorting. Defaults
to ``db_field``.
"""
return self.db_field
def get_toggle_url(self, state):
"""Return a URL to toggle this column's visibility.
Args:
state (StatefulColumn):
The state for the DataGrid instance.
Returns:
unicode: The URL used to toggle column visibility.
"""
columns = [column.id for column in state.datagrid.columns]
if state.active:
try:
columns.remove(self.id)
except ValueError:
pass
else:
columns.append(self.id)
url_params = get_url_params_except(state.datagrid.request.GET,
'columns')
if url_params:
url_params = url_params + '&'
return "?%scolumns=%s" % (url_params, ",".join(columns))
def get_header(self, state):
"""Render the header for the column.
The column header will include the current sort indicator, if it
belongs in the sort list. It will also be made clickable in order
to modify the sort order appropriately, if sortable.
Args:
state (StatefulColumn):
The state for the DataGrid instance.
Returns:
unicode: The HTML for the header.
"""
datagrid = state.datagrid
in_sort = False
sort_direction = self.SORT_DESCENDING
sort_primary = False
sort_url = ""
unsort_url = ""
if self.sortable:
sort_list = list(datagrid.sort_list)
if sort_list:
rev_column_id = "-%s" % self.id
new_column_id = self.id
cur_column_id = ""
if self.id in sort_list:
# This column is currently being sorted in
# ascending order.
sort_direction = self.SORT_ASCENDING
cur_column_id = self.id
new_column_id = rev_column_id
elif rev_column_id in sort_list:
# This column is currently being sorted in
# descending order.
sort_direction = self.SORT_DESCENDING
cur_column_id = rev_column_id
new_column_id = self.id
if cur_column_id:
in_sort = True
sort_primary = (sort_list[0] == cur_column_id)
if not sort_primary:
# If this is not the primary column, we want to keep
# the sort order intact.
new_column_id = cur_column_id
# Remove this column from the current location in the list
# so we can move it to the front of the list.
sort_list.remove(cur_column_id)
# Insert the column name into the beginning of the sort list.
sort_list.insert(0, new_column_id)
else:
# There's no sort list to begin with. Make this column
# the only entry.
sort_list = [self.id]
# We can only support two entries in the sort list, so truncate
# this.
del(sort_list[2:])
url_params = get_url_params_except(
datagrid.request.GET,
"sort", "datagrid-id", "gridonly", "columns")
if url_params:
url_params = url_params + '&'
url_prefix = "?%ssort=" % url_params
unsort_url = url_prefix + ','.join(sort_list[1:])
sort_url = url_prefix + ','.join(sort_list)
return datagrid.column_header_template_obj.render(context={
'column': self,
'column_state': state,
'in_sort': in_sort,
'sort_ascending': sort_direction == self.SORT_ASCENDING,
'sort_primary': sort_primary,
'sort_url': sort_url,
'unsort_url': unsort_url,
})
def collect_objects(self, state, object_list):
"""Iterate through the objects and builds a cache of data to display.
This optimizes the fetching of data in the grid by grabbing all the
IDs of related objects that will be queried for rendering, loading
them all at once, and populating the cache.
Args:
state (StatefulColumn):
The state for the DataGrid instance.
object_list (list):
The list of objects being rendered on the datagrid.
"""
id_field = '%s_id' % self.field_name
ids = set()
model = None
for obj in object_list:
if not hasattr(obj, id_field):
# This isn't the field type you're looking for.
return
id_value = getattr(obj, id_field)
if id_value is None:
continue
ids.add(id_value)
if not model:
field = getattr(obj.__class__, self.field_name).field
try:
model = field.rel.to
except AttributeError:
# No idea what this is. Bail.
return
if model and ids:
for obj in model.objects.filter(pk__in=ids):
state.data_cache[obj.pk] = obj
def render_cell(self, state, obj, render_context):
"""Render the table cell containing column data.
Args:
state (StatefulColumn):
The state for the DataGrid instance.
obj (object):
The object being rendered for this row.
render_context (Context):
The shared context used for cell renders.
Returns:
unicode: The rendered cell as HTML.
"""
try:
rendered_data = self.render_data(state, obj)
except Exception as e:
logger.exception('Error when calling render_data for DataGrid '
'Column %r: %s',
self, e)
rendered_data = ''
# We use empty strings instead of None just to keep cache keys small.
url = ''
css_class = ''
link_css_class = ''
if self.link:
if self.link_func:
try:
url = self.link_func(state, obj, rendered_data)
except AttributeError:
pass
elif render_context:
url = render_context.get('_datagrid_object_url')
if self.css_class:
if callable(self.css_class):
css_class = self.css_class(obj)
else:
css_class = self.css_class
if self.link_css_class:
if callable(self.link_css_class):
link_css_class = self.link_css_class(obj)
else:
link_css_class = self.link_css_class
key = '%s:%s:%s:%s:%s' % (state.last, rendered_data, url, css_class,
link_css_class)
if key not in state.cell_render_cache:
if url:
css_class = '%s has-link' % css_class
ctx = {}
if render_context:
ctx.update(render_context)
ctx.update({
'column': self,
'column_state': state,
'css_class': css_class.strip(),
'link_css_class': link_css_class,
'url': url,
'data': mark_safe(rendered_data)
})
template = self.cell_template_obj
if template is None:
template = state.datagrid.cell_template_obj
state.cell_render_cache[key] = template.render(ctx)
return state.cell_render_cache[key]
def render_data(self, state, obj):
"""Render the column data within the cell.
Args:
state (StatefulColumn):
The state for the DataGrid instance.
obj (object):
The object being rendered for this row.
Returns:
unicode: The rendered data as HTML.
"""
id_field = '%s_id' % self.field_name
# Look for this directly so that we don't end up fetching the
# data for the object.
if id_field in obj.__dict__:
pk = obj.__dict__[id_field]
if pk in state.data_cache:
return state.data_cache[pk]
else:
value = getattr(obj, self.field_name)
state.data_cache[pk] = escape(value)
return value
else:
# Follow . separators like in the django template library
value = obj
for field_name in self.field_name.split('.'):
if field_name:
value = getattr(value, field_name)
if callable(value):
value = value()
return escape(value)
def augment_queryset(self, state, queryset):
"""Augment a queryset with new queries.
Subclasses can override this to extend the queryset to provide
additional information, usually using queryset.extra(). This must
return a queryset based on the original queryset.
This should not restrict the query in any way, or the datagrid may
not operate properly. It must only add additional data to the
queryset.
Args:
state (StatefulColumn):
The state for the DataGrid instance.
queryset (QuerySet):
The queryset to augment.
Returns:
QuerySet: The resulting QuerySet.
"""
return queryset
class StatefulColumn(object):
"""A stateful wrapper for a Column instance.
Columns must be stateless, as they are shared across all instances of
a particular DataGrid. However, some state is needed for columns, such
as their widths or active status.
StatefulColumn wraps a :py:class:`Column` instance and provides state
storage, and also provides a convenient way to call methods on a Column and
pass the state.
Attributes owned by the Column can be accessed directly through the
StatefulColumn.
Likewise, any functions owned by the Column can be accessed as well.
The function will be invoked with this StatefulColumn as the first
parameter passed.
"""
def __init__(self, datagrid, column):
"""Initialize the column state.
Args:
datagrid (DataGrid):
The DataGrid instance owning this column state.
column (Column):
The column instance this state is associated with.
"""
self.datagrid = datagrid
self.column = column
self.active = False
self.last = False
self.width = 0
self.data_cache = {}
self.cell_render_cache = {}
try:
column.setup_state(self)
except Exception as e:
logger.exception('Error when calling setup_state for DataGrid '
'Column %r: %s',
self.column, e)
@property
def toggle_url(self):
"""The visibility toggle URL of the column.
This is a convenience used by templates to call
:py:meth:`Column.get_toggle_url` with the current state.
"""
return self.column.get_toggle_url(self)
@property
def header(self):
"""The header of the column.
This is a convenience used by templates to call
:py:meth:`Column.get_header` with the current state.
"""
return self.column.get_header(self)
def __getattr__(self, name):
"""Returns an attribute from the parent Column.
This is called when accessing an attribute not found directly on
StatefulColumn. The attribute will be fetched from the Column
(if it exists there).
In the case of accessing a function, a wrapper will be returned
that will automatically pass this StatefulColumn instance as the
first parameter.
Args:
name (unicode): The attribute to fetch from the column.
Returns:
The attribute value from the column.
"""
result = getattr(self.column, name)
if callable(result):
return lambda *args, **kwargs: result(self, *args, **kwargs)
return result
class CheckboxColumn(Column):
"""A column that renders a checkbox.
The :py:meth:`is_selectable` and :py:meth:`is_selected` functions can be
overridden to control whether a checkbox is displayed in a row and whether
that checkbox is initially checked.
The checkboxes have a ``data-object-id`` attribute that contains the ID of
the object that row represents. This allows the JavaScript code to
determine which rows have been checked, and operate on that
accordingly.
The checkboxes also have a ``data-checkbox-name`` attribute that
contains the value passed in to the ``checkbox_name`` parameter of its
constructor.
"""
def __init__(self, checkbox_name='select', shrink=True,
show_checkbox_header=True,
detailed_label=_('Select Rows'),
*args, **kwargs):
"""Initialize the column.
Args:
checkbox_name (unicode):
The name set in ``data-checkbox-name``.
shrink (bool):
If ``True``, the column's width will be calculated to its
minimum size.
show_checkbox_header (bool):
If ``True``, a checkbox will be used for the column header.
"""
super(CheckboxColumn, self).__init__(
shrink=shrink,
label=format_html(
'<input class="datagrid-header-checkbox"'
' type="checkbox" data-checkbox-name="{0}" />',
checkbox_name),
detailed_label=detailed_label,
detailed_label_html=format_html(
'<input type="checkbox" /> {0}',
detailed_label),
*args, **kwargs)
self.show_checkbox_header = show_checkbox_header
self.checkbox_name = checkbox_name
self.cell_template = 'datagrid/cell_no_link.html'
def render_data(self, state, obj):
if self.is_selectable(state, obj):
checked = ''
if self.is_selected(state, obj):
checked = mark_safe('checked="true"')
return format_html('<input type="checkbox" data-object-id="{0}" '
'data-checkbox-name="{1}" {2} />',
obj.pk, self.checkbox_name, checked)
else:
return ''
def is_selectable(self, state, obj):
"""Returns whether an object can be selected.
If this returns False, no checkbox will be rendered for this item.
"""
return True
def is_selected(self, state, obj):
"""Returns whether an object has been selected.
If this returns True, the checkbox will be checked.
"""
return False
class DateTimeColumn(Column):
"""A column that renders a date or time."""
def __init__(self, label, format=None, sortable=True,
timezone=pytz.utc, *args, **kwargs):
super(DateTimeColumn, self).__init__(label, sortable=sortable,
*args, **kwargs)
self.format = format
self.timezone = timezone
def render_data(self, state, obj):
# If the datetime object is tz aware, conver it to local time
datetime = getattr(obj, self.field_name)
if settings.USE_TZ:
datetime = pytz.utc.normalize(datetime).\
astimezone(self.timezone)
return date(datetime, self.format)
class DateTimeSinceColumn(Column):
"""A column that renders a date or time relative to now."""
def __init__(self, label, sortable=True, timezone=pytz.utc,
*args, **kwargs):
super(DateTimeSinceColumn, self).__init__(label, sortable=sortable,
*args, **kwargs)
def render_data(self, state, obj):
return _("%s ago") % timesince(getattr(obj, self.field_name))
class DataGrid(object):
"""A paginated table of data based on queries from a database.
A datagriad represents a list of objects, sorted and organized by
columns. The sort order and column lists can be customized. allowing
users to view this data however they prefer.
This is meant to be subclassed for specific uses. The subclasses are
responsible for defining one or more column types. It can also set
one or more of the following optional variables:
Attributes:
title (unicode):
The title of the grid.
profile_sort_field (unicode):
The variable name in the user profile where the sort order can be
loaded and saved.
profile_columns_field (unicode):
The variable name in the user profile where the columns list can be
loaded and saved.
paginate_by (int):
The number of items to show on each page of the grid. The default
is 50.
paginate_orphans (int):
If this number of objects or fewer are on the last page, it will be
rolled into the previous page. The default is 3.
page (int):
The page to display. If this is not specified, the ``?page=``
variable passed in the URL will be used, or 1 if that is not
specified.
listview_template (unicode):
The template used to render the list view. The default is
:file:`datagrid/listview.html`.
column_header_template (unicode):
The template used to render each column header. The default is
:file:`datagrid/column_header.html`.
cell_template (unicode):
The template used to render a cell of data. The default is
:file:`datagrid/cell.html`.
optimize_sorts (bool):
Whether or not to optimize queries when using multiple sorts. This
can offer a speed improvement, but may need to be turned off for
more advanced querysets (such as when using ``extra()``).
The default is ``True``.
"""
_columns = None
@classmethod
def add_column(cls, column):
"""Add a new column for this datagrid.
This can be used to add columns to a DataGrid subclass after
the subclass has already been defined.
The column added must have a unique ID already set.
Args:
column (Column):
The column to add.
"""
cls._populate_columns()
if not column.id:
raise KeyError(
'Custom datagrid columns must have a unique id attribute.')
if column.id in _column_registry[cls]:
raise KeyError('"%s" is already a registered column for %s'
% (column.id, cls.__name__))
_column_registry[cls][column.id] = column
@classmethod
def remove_column(cls, column):
"""Remove a column from this datagrid.
This can be used to remove columns previously added through
:py:meth:`add_column`.
Args:
column (Column):
The column to remove.
"""
cls._populate_columns()
try:
del _column_registry[cls][column.id]
except KeyError:
raise KeyError('"%s" is not a registered column for %s'
% (column.id, cls.__name__))
@classmethod
def get_column(cls, column_id):
"""Return the column with the given ID.
If not found, this will return None.
Args:
column_id (int):
The index of the column to return.
Returns:
Column: The resulting column at the given index.
"""
cls._populate_columns()
return _column_registry[cls].get(column_id)
@classmethod
def get_columns(cls):
"""Return the list of registered columns for this datagrid.
Returns:
list of Column: The list of columns registered on this datagrid.
"""
cls._populate_columns()
return _column_registry[cls].values()
@classmethod
def _populate_columns(cls):
"""Populate the default list of columns for the datagrid.
The default list contains all columns added in the class definition.
"""
if cls not in _column_registry:
_column_registry[cls] = {}
for key in dir(cls):
column = getattr(cls, key)
if isinstance(column, Column):
column.id = key
if not column.field_name:
column.field_name = column.id
if not column.db_field:
column.db_field = column.field_name
cls.add_column(column)
def __init__(self, request, queryset=None, title="", extra_context={},
optimize_sorts=True, model=None):
"""Initialize the datagrid.
Args:
request (HttpRequest):
The HTTP request from the client.
queryset (QuerySet):
A QuerySet returning the objects to render in the grid.
title (unicode):
The displayed title of the datagrid.
extra_context (dict):
Extra context variables to render on the datagrid template.
optimize_sorts (bool):
If ``True``, sorting will be optimized, reducing the
complexity of the queries. This is the default.
model (Model):
The model for the objects in the datagrid. Defaults to the
model associated with ``queryset``.
"""
self.request = request
self.queryset = queryset
self.rows = []
self.columns = []
self.column_map = {}
self.id_list = []
self.paginator = None
self.page = None
self.sort_list = None
self.state_loaded = False
self.page_num = 0
self.id = None
self.extra_context = dict(extra_context)
self.optimize_sorts = optimize_sorts
self.special_query_args = []
self._model = model
self.default_sort = []
if not hasattr(request, "datagrid_count"):
request.datagrid_count = 0
self.id = "datagrid-%s" % request.datagrid_count
request.datagrid_count += 1
# Customizable variables
self.title = title
self.profile_sort_field = None
self.profile_columns_field = None
self.paginate_by = 50
self.paginate_orphans = 3
self.listview_template = 'datagrid/listview.html'
self.column_header_template = 'datagrid/column_header.html'
self.cell_template = 'datagrid/cell.html'
self.paginator_template = 'datagrid/paginator.html'
@cached_property
def cell_template_obj(self):
"""The rendered template used for cells on this datagrid.
This will only be generated once, and reused for all cells.
"""
obj = get_template(self.cell_template)
if not obj:
logger.error("Unable to load template '%s' for datagrid "
"cell. This may be an installation issue.",
self.cell_template,
extra={'request': self.request})
return obj
@cached_property
def column_header_template_obj(self):
"""The rendered template used for column headers on this datagrid.
This will only be generated once, and reused for all headers.
"""
obj = get_template(self.column_header_template)
if not obj:
logger.error("Unable to load template '%s' for datagrid "
"column headers. This may be an installation "
"issue.",
self.column_header_template,
extra={'request': self.request})
return obj
@property
def all_columns(self):
"""All columns in the datagrid, sorted by label."""
return [
self.get_stateful_column(column)
for column in sorted(self.get_columns(),
key=lambda x: x.detailed_label)
]
@property
def model(self):
"""The model representing the objects shown in the grid."""
if self._model is None:
return self.queryset.model
return self._model
def get_stateful_column(self, column):
"""Return a StatefulColumn for the given Column instance.