-
Notifications
You must be signed in to change notification settings - Fork 2
/
models.py
1542 lines (1245 loc) · 53.9 KB
/
models.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
"""Top level models for pythia."""
from __future__ import (division, print_function, unicode_literals,
absolute_import)
import copy
import logging
import reversion
from django.conf import settings
from django.core import validators
from django.core.mail import send_mail
from django.core.exceptions import ValidationError, ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.contrib.auth.models import (AbstractBaseUser, PermissionsMixin,
BaseUserManager, Group)
from django.contrib.gis.db import models as geo_models
from django.contrib.gis.db.models.query import GeoQuerySet
from django.contrib.gis.db.models.sql.query import GeoQuery
from django.db import router, models
from django.db.models import signals
from django.db.models.deletion import Collector
from django.db.models.query import QuerySet
from django.db.models.sql.query import Query
from django.utils import timezone, six
from django.utils.encoding import python_2_unicode_compatible
from django.utils.html import strip_tags
from django.utils.safestring import mark_safe
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from pythia.middleware import get_current_user
from pythia.utils import texify_filename
from django_resized import ResizedImageField
# from south.modelsinspector import add_introspection_rules
# add_introspection_rules([], ["^myapp\.stuff\.fields\.SomeNewField"])s
logger = logging.getLogger(__name__)
def programs_upload_to(instance, filename):
"""Create a custom upload location for user-submitted program files."""
return "programs/{0}/{1}".format(
instance.slug,
texify_filename(filename)
)
class ActiveQuerySet(QuerySet):
"""Cursom QuerySet."""
def __init__(self, model, query=None, using=None):
"""Define model to be avail for custom query."""
if query is None:
query = Query(model)
query.add_q(models.Q(effective_to__isnull=True))
return super(ActiveQuerySet, self).__init__(model, query, using)
def __deepcopy__(self, memo):
"""Borrow from django.db.models.query.QuerySet.
Required because we need to pass self.model to the self.__class__ call.
"""
obj = self.__class__(self.model)
for k, v in self.__dict__.items():
if k in ('_iter', '_result_cache'):
obj.__dict__[k] = None
else:
obj.__dict__[k] = copy.deepcopy(v, memo)
return obj
def delete(self):
"""see django.db.models.query.QuerySet.delete."""
assert_msg = "Cannot use 'limit' or 'offset' with delete."
assert self.query.can_filter(), assert_msg
del_query = self._clone()
del_query._for_write = True
# Disable non-supported fields.
del_query.query.select_for_update = False
del_query.query.select_related = False
del_query.query.clear_ordering(force_empty=True)
# TODO: this could probably be made more efficient via the django
# Collector, maybe
for obj in del_query:
obj.delete()
# Clear the result cache, in case this QuerySet gets reused.
self._result_cache = None
delete.alters_data = True
class ActiveGeoQuerySet(ActiveQuerySet, GeoQuerySet):
"""Custom GeoQuerySet."""
def __init__(self, model, query=None, using=None):
"""Define model to be avail for custom query."""
if query is None:
query = GeoQuery(model)
query.add_q(geo_models.Q(effective_to__isnull=True))
return super(ActiveGeoQuerySet, self).__init__(model, query, using)
class ActiveModelManager(models.Manager):
"""Exclude inactive ("deleted") objects from the query set."""
def get_query_set(self):
"""Override the default queryset to filter out deleted objects."""
return ActiveQuerySet(self.model)
# __getattr__ borrowed from
# http://lincolnloop.com/django-best-practices/applications.html#managers
def __getattr__(self, attr, *args):
"""see https://code.djangoproject.com/ticket/15062."""
if attr.startswith("_"):
raise AttributeError
return getattr(self.get_query_set(), attr, *args)
class ActiveGeoModelManager(ActiveModelManager, geo_models.GeoManager):
"""ActiveGeoModelManager."""
def get_query_set(self):
"""Query set."""
return ActiveGeoQuerySet(self.model)
class ActiveModel(models.Model):
"""Custom "don't really delete" Mixin.
Model mixin to allow objects to be saved as 'non-current' or 'inactive',
instead of deleting those objects.
The standard model delete() method is overridden.
"effective_from" allows 'past' and/or 'future' objects to be saved.
"effective_to" is used to 'delete' objects (null==not deleted).
"""
effective_from = models.DateTimeField(default=timezone.now)
effective_to = models.DateTimeField(null=True, blank=True)
objects = ActiveModelManager()
# Return all objects, including deleted ones, the default manager:
objects_all = models.Manager()
class Meta:
"""Class opts."""
abstract = True
def __init__(self, *args, **kwargs):
"""Init."""
if not issubclass(type(type(self).objects), ActiveModelManager):
raise ImproperlyConfigured(
"The ActiveModel objects manager is not a subclass of "
"ActiveModelManager, if you "
"created your own objects manager, it must be a subclass of "
"ActiveModelManager.")
super(ActiveModel, self).__init__(*args, **kwargs)
def is_active(self):
"""Whether object is not marked for deletion."""
return self.effective_to is None
def is_deleted(self):
"""Whether object is marked for deletion."""
return not self.is_active()
def delete(self, *args, **kwargs):
"""Overide the standard model delete method.
Sets "effective_to" as the
current date and time and then calls save() instead.
"""
# see django.db.models.deletion.Collection.delete
using = kwargs.get('using',
router.db_for_write(self.__class__, instance=self))
cannot_be_deleted_assert = ("""%s object can't be deleted because its
%s attribute is set to None.""" %
(self._meta.object_name,
self._meta.pk.attname))
assert self._get_pk_val() is not None, cannot_be_deleted_assert
collector = Collector(using=using)
collector.collect([self])
collector.sort()
# send pre_delete signals
def delete(collector):
for model, obj in collector.instances_with_model():
if not model._meta.auto_created:
signals.pre_delete.send(
sender=model, instance=obj, using=using)
# be compatible with django 1.4.x
if hasattr(collector, 'fast_deletes'):
# fast deletes
for qs in collector.fast_deletes:
for instance in qs:
self._delete(instance)
# delete batches
# be compatible with django>=1.6
if hasattr(collector, 'batches'):
for model, batches in six.iteritems(collector.batches):
for field, instances in six.iteritems(batches):
for instance in instances:
self._delete(instance)
# "delete" instances
for model, instances in six.iteritems(collector.data):
for instance in instances:
self._delete(instance)
# send post_delete signals
for model, obj in collector.instances_with_model():
if not model._meta.auto_created:
signals.post_delete.send(
sender=model, instance=obj, using=using)
# another django>=1.6 thing
try:
from django.db.transaction import commit_on_success_unless_managed
except ImportError:
delete(collector)
else:
commit_on_success_unless_managed(using=using)(delete(collector))
delete.alters_data = True
def _delete(self, instance):
instance.effective_to = timezone.now()
instance.save()
class ActiveGeoModel(ActiveModel):
"""Abstract ActiveGeoModel base class."""
objects = ActiveGeoModelManager()
# Return all objects, including deleted ones, the default manager.
objects_all = geo_models.GeoManager()
def __init__(self, *args, **kwargs):
"""Init."""
if not issubclass(type(type(self).objects), ActiveGeoModelManager):
raise ImproperlyConfigured(
"The ActiveGeoModel objects manager is not a subclass of "
"ActiveGeoModelManager, if you "
"created your own objects manager, it must be a subclass of "
"ActiveGeoModelManager.")
super(ActiveGeoModel, self).__init__(*args, **kwargs)
class Meta:
"""Class opts."""
abstract = True
@python_2_unicode_compatible
class Audit(geo_models.Model):
"""Abstract Audit base class."""
class Meta:
"""Class opts."""
abstract = True
creator = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='%(app_label)s_%(class)s_created',
editable=False)
modifier = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='%(app_label)s_%(class)s_modified',
editable=False)
created = models.DateTimeField(default=timezone.now, editable=False)
modified = models.DateTimeField(auto_now=True, editable=False)
def __init__(self, *args, **kwargs):
"""Init."""
super(Audit, self).__init__(*args, **kwargs)
self._changed_data = None
self._initial = {}
if self.pk:
for field in self._meta.fields:
self._initial[field.attname] = getattr(self, field.attname)
def has_changed(self):
"""Return true if the current data differs from initial."""
return bool(self.changed_data)
def _get_changed_data(self):
if self._changed_data is None:
self._changed_data = []
for field, value in self._initial.items():
if field in ["modified", "modifier_id"]:
continue
if getattr(self, field) != value:
self._changed_data.append(field)
return self._changed_data
changed_data = property(_get_changed_data)
def save(self, *args, **kwargs):
"""Set creator and modifier to current user or superuser.
This method uses pythia.middleware.get_current_user to retrieve either
the request.user from thread local storage (as injected by
pythia.middleware.ThreadLocals) or the superuser in case the thread
was not a request (e.g. run through shell or unit tests).
"""
user = get_current_user()
# If saving a new model, set the creator.
if not self.pk:
self.creator = user
created = True
else:
created = False
self.modifier = user
super(Audit, self).save(*args, **kwargs)
if created:
with reversion.create_revision():
reversion.set_comment('Initial version.')
else:
if self.has_changed():
comment = 'Changed ' + ', '.join(self.changed_data) + '.'
with reversion.create_revision():
reversion.set_comment(comment)
else:
with reversion.create_revision():
reversion.set_comment('Nothing changed.')
def __str__(self):
"""String representation."""
return str(self.pk)
def get_absolute_url(self):
"""Absolute base url."""
opts = self._meta.app_label, self._meta.module_name
return reverse("admin:%s_%s_change" % opts, args=(self.pk, ))
def clean_fields(self, exclude=None):
"""Override clean_fields.
Do what model validation should have done in the first place:
call clean_FIELD during model validation.
"""
errors = {}
for f in self._meta.fields:
if f.name in exclude:
continue
if hasattr(self, "clean_%s" % f.attname):
try:
getattr(self, "clean_%s" % f.attname)()
except ValidationError as e:
# TODO: Django 1.6 introduces new features to
# ValidationError class, update it to use e.error_list
errors[f.name] = e.messages
try:
super(Audit, self).clean_fields(exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)
if errors:
raise ValidationError(errors)
# end swingers models
# -----------------------------------------------------------------------------#
# Report Parts
#
class ReportPart(object):
"""Report part class."""
def __str__(self):
"""String representation."""
return str(self.original)
def __init__(self, original, template, context, *args):
"""Init."""
self.original = original
self.template_ = template
self.context_ = context
@property
def template(self):
"""Template."""
return self.base + self.template_ + self.suffix
@property
def context(self):
"""Context."""
if callable(self.context_):
context_ = self.context_(self.original)
elif hasattr(self.original, self.context_):
context_ = getattr(self.original, self.context_)
else:
context_ = self.context_
return context_
class HTMLReportPart(ReportPart):
"""Class HTMLReportPart."""
suffix = '.html'
base = 'admin/pythia/ararreport/includes/'
class LATEXReportPart(ReportPart):
"""Class LATEXReportPart."""
suffix = '.tex'
base = 'latex/includes/'
# -----------------------------------------------------------------------------#
# Shared classes: Administrative departmental structures
#
@python_2_unicode_compatible
class Area(Audit): # , models.PolygonModelMixin):
"""An area of interest to a Project, classified by area type."""
AREA_TYPE_RELEVANT = 1
AREA_TYPE_FIELDWORK = 2
AREA_TYPE_DPAW_REGION = 3
AREA_TYPE_DPAW_DISTRICT = 4
AREA_TYPE_IBRA_REGION = 5
AREA_TYPE_IMCRA_REGION = 6
AREA_TYPE_NRM_REGION = 7
AREA_TYPE_CHOICES = (
(AREA_TYPE_RELEVANT, _("Relevant Area Polygon")),
(AREA_TYPE_FIELDWORK, _("Fieldwork Area Polygon")),
(AREA_TYPE_DPAW_REGION, _("DBCA Region")),
(AREA_TYPE_DPAW_DISTRICT, _("DBCA District")),
(AREA_TYPE_IBRA_REGION, _("IBRA")),
(AREA_TYPE_IMCRA_REGION, _("IMCRA")),
(AREA_TYPE_NRM_REGION, _("Natural Resource Management Region"))
)
area_type = models.PositiveSmallIntegerField(
verbose_name=_("Area Type"), choices=AREA_TYPE_CHOICES,
default=AREA_TYPE_RELEVANT)
name = models.CharField(
max_length=320, null=True, blank=True,
help_text=_("A human-readable, short but descriptive name."))
source_id = models.PositiveIntegerField(
null=True, blank=True,
help_text=_("The source id"))
northern_extent = models.FloatField(
null=True, blank=True,
help_text=_("The maximum northern extent of an Area, "
"useful for sorting by geographic latitude."))
mpoly = geo_models.MultiPolygonField(
blank=True, null=True, srid=4326, verbose_name=_("Spatial extent"),
help_text=_("The spatial extent of this feature, stored as WKT."))
class Meta:
"""Class opts."""
verbose_name = _("Area")
verbose_name_plural = _("Areas")
ordering = ['area_type', '-northern_extent']
def save(self, *args, **kwargs):
"""Save."""
if self.get_northern_extent() is not None:
self.northern_extent = self.get_northern_extent()
super(Area, self).save(*args, **kwargs)
def __str__(self):
"""String representation."""
return '[{0}] {1}'.format(self.get_area_type_display(), self.name)
def get_northern_extent(self):
"""Northernmost latitude."""
return self.mpoly.extent[3] if self.mpoly else None
@property
def area_type_display(self):
"""A human-readable label for the Area type."""
return self.get_area_type_display()
class RegionManager(models.Manager):
"""RegionManager."""
def get_by_natural_key(self, name):
"""Get by natural key."""
return self.get(name=name)
@python_2_unicode_compatible
class Region(models.Model):
"""DBCA Region."""
mpoly = geo_models.MultiPolygonField(
null=True, blank=True, help_text='Optional cache of spatial features.')
# the name should be unique=True
name = models.CharField(max_length=64, null=True, blank=True)
northern_extent = models.FloatField(null=True, blank=True)
objects = RegionManager()
class Meta:
"""Class opts."""
verbose_name = _("Region")
verbose_name_plural = _("Regions")
ordering = ['-northern_extent']
def __str__(self):
"""String representation."""
return self.name if self.name else str(self.pk)
def save(self, *args, **kw):
"""Save."""
self.northern_extent = self.get_northern_extent()
super(Region, self).save(*args, **kw)
def natural_key(self):
"""Natural key."""
return (self.name,)
def get_northern_extent(self):
"""Northern extent."""
return self.mpoly.extent[3] if self.mpoly else 0
class DistrictManager(models.Manager):
"""DistrictManager."""
def get_by_natural_key(self, region, name):
"""Get by natural key."""
region = Region.objects.get_by_natural_key(region)
return self.get(name=name, region=region)
@python_2_unicode_compatible
class District(models.Model):
"""DBCA District."""
# the name should be unique=True
name = models.CharField(max_length=200, null=True, blank=True)
code = models.CharField(max_length=3, null=True, blank=True)
northern_extent = models.FloatField(null=True, blank=True)
objects = DistrictManager()
region = models.ForeignKey(
# ChainedForeignKey(
Region,
# chained_field="name", chained_model_field="name",
# show_all=False, auto_choose=True,
help_text=_("The region to which this district belongs."))
mpoly = geo_models.MultiPolygonField(
null=True, blank=True,
help_text=_("Optional cache of spatial features."))
def __str__(self):
"""String representation."""
return '[{0}] {1}'.format(self.region.name, self.name)
def save(self, *args, **kw):
"""Save."""
self.northern_extent = self.get_northern_extent()
super(District, self).save(*args, **kw)
def natural_key(self):
"""Natural key."""
return self.region.natural_key() + (self.name,)
natural_key.dependencies = ['project.region']
class Meta:
"""Class opts."""
ordering = ['-northern_extent']
verbose_name = _("District")
verbose_name_plural = _("Districts")
def get_northern_extent(self):
"""Northernmost latitude."""
return self.mpoly.extent[3] if self.mpoly else 0
@python_2_unicode_compatible
class Address(Audit, ActiveModel):
"""An address with street 1, street 2, city, and zip code."""
street = models.CharField(
max_length=254, help_text=_("The street address"))
extra = models.CharField(
_("extra"), max_length=254, null=True, blank=True,
help_text=_("Additional address info"))
city = models.CharField(
max_length=254, help_text=_("The city"))
zipcode = models.CharField(
max_length=4, help_text=_("The zip code"))
state = models.CharField(
max_length=254, default="WA", help_text=_("The state"))
country = models.CharField(
max_length=254, default="Australia", help_text=_("The country"))
class Meta:
"""Class opts."""
verbose_name = _("Address")
verbose_name_plural = _("Addresses")
def __str__(self):
"""String representation."""
if self.extra:
return '{0}, {1}, {2} {3} {4}'.format(
self.street, self.extra, self.city, self.zipcode, self.state)
else:
return '{0}, {1} {2} {3}'.format(
self.street, self.city, self.zipcode, self.state)
@python_2_unicode_compatible
class Service(Audit, ActiveModel):
"""Departmental services.
SPMS Science projects provide value to a defined selection of the Departmental Services.
"""
name = models.CharField(max_length=320)
slug = models.SlugField(help_text=_("A URL-safe acronym of the Service's name without whitespace."))
# Key personnel ----------------------------------------------------------#
director = models.ForeignKey(
settings.AUTH_USER_MODEL, related_name='leads_services',
blank=True, null=True, help_text=_("The Service's Director"))
class Meta:
"""Class opts."""
verbose_name = _("Service")
verbose_name_plural = _("Services")
ordering = ['slug', 'name']
def __str__(self):
"""String representation."""
return 'Service {0}: {1}'.format(self.slug, self.name)
@python_2_unicode_compatible
class Division(Audit, ActiveModel):
"""Departmental Division.
Departmental Divisions are the organizational units of the Department.
Each Division has an Executive Director, who is the approver of all Divisional projects.
Each Divisional Program belongs to exactly one Division.
"""
name = models.CharField(max_length=320)
slug = models.SlugField(help_text=_("A URL-safe acronym of the Division's name without whitespace."))
# Key personnel ----------------------------------------------------------#
director = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='leads_divisions',
blank=True,
null=True,
help_text=_("The Division's Director will be attributed as head of the Division in reports."))
approver = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='approves_divisions',
blank=True,
null=True,
help_text=_(
"The Approver receives email notifications about outstanding approval requests and has permissions to approve documents. "
"The Approver can be the Director or someone else, such as (but not limited to) an Assistant Director or Executive Assistant."))
class Meta:
"""Class opts."""
verbose_name = _("Division")
verbose_name_plural = _("Divisions")
ordering = ['slug', 'name']
def __str__(self):
"""String representation."""
#return 'Division {0}: {1}'.format(self.slug, self.name)
return self.name
@python_2_unicode_compatible
class Program(Audit, ActiveModel):
"""A departmental organisational unit inside a Division.
* Biodiversity and Conservation Science Program
* RFMS Region
* CEM Branch
An organizational structure of research scientists, technical officers and
admin staff, such as a dedicated finance admin or a default data custodian,
under the responsibility of a program leader.
A program has a cost center code which is unique across the Department.
"""
name = models.CharField(max_length=320)
slug = models.SlugField(
help_text='A unique slug to be used in folder names etc.')
division = models.ForeignKey(
Division,
verbose_name=_("Division"),
blank=True, null=True,
related_name = "programs",
help_text=_("The Division this program belongs to."))
# Publishing and printing options ----------------------------------------#
# The naming "published" was chosen when SDIS was BCS only, and
# the annual report would include projects of all (implicitly BCS only) programs.
# This flag did and still does exclude projects from that program from annual reporting.
# TODO refactor this field to a better name, e.g. "active"
# (avoid name collisions with parent models).
published = models.BooleanField(
default=True,
verbose_name="Active",
help_text = ("Active programs can be reported on annually. "
"Administrative and deprecated programs are marked as inactive."))
position = models.IntegerField(
help_text='An arbitrary, ascending ordering number.')
# Key personnel ----------------------------------------------------------#
program_leader = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='leads_programs',
blank=True, null=True,
help_text='The Program Leader')
# cost_center should be unique=True
cost_center = models.CharField(
max_length=3, blank=True, null=True,
help_text='The three-digit cost center number for the Program.')
finance_admin = models.ForeignKey(
settings.AUTH_USER_MODEL,
blank=True, null=True,
related_name='finance_admin_on_programs',
help_text='The finance admin.')
data_custodian = models.ForeignKey(
settings.AUTH_USER_MODEL,
blank=True, null=True,
related_name='pythia_data_custodian_on_programs', # clashes with sdis2
help_text='The default custodian of data sets of this Program.')
# About ------------------------------------------------------------------#
focus = models.TextField(
verbose_name='Program focus',
blank=True, null=True,
help_text="The program's focus as a semicolon-separated "
"list of keywords.")
introduction = models.TextField(
verbose_name='Program introduction',
blank=True, null=True,
help_text="The program's mission in about 150 to 300 words.")
image = ResizedImageField(
upload_to=programs_upload_to,
blank=True, null=True,
size=[2480, 1240],
help_text="Upload an image representative of the program."
" Aim for a visually quiet, low contrast image."
" The horizon should be in the top third and level."
" The aspect ratio (width to height) must be 2:1."
" The image will be resized to max 2480 (wt) x 1240 pt"
" (ht).")
class Meta:
"""Class opts."""
ordering = ['division', '-published', 'position', 'cost_center']
verbose_name = "Program"
verbose_name_plural = "Programs"
def __str__(self):
"""The name."""
return '{0} {1}{2}'.format(
self.division.slug if self.division and self.division.slug else "SET DIVISION",
mark_safe(strip_tags(self.name)),
'' if self.published else ' [inactive]'
)
def label(self):
"""The name."""
return '{0}{1}'.format(
mark_safe(strip_tags(self.name)),
'' if self.published else ' [inactive]'
)
def save(self, *args, **kw):
"""Generate slug from name if not set."""
if not self.slug:
self.slug = slugify(self.name)
super(Program, self).save(*args, **kw)
def parts(self, part_class):
"""Parts."""
# TODO: we probably only want projects that are on the current ARAR
# TODO: :) iterators?
# self.project_set.all() should not hit the db as it is prefetched from
# pythia.models.report.programs()
# get all the crap from the db in a couple of queries, let python
# crunch the data up :)
Project = self.project_set.model
projects = self.project_set.filter(
type__in=[Project.SCIENCE_PROJECT,
Project.CORE_PROJECT]).prefetch_related('progressreport')
return [part_class(project, 'project', lambda x: x)
for project in projects]
@property
def latexparts(self):
"""Latex parts."""
return self.parts(LATEXReportPart)
@property
def htmlparts(self):
"""HTML parts."""
return self.parts(HTMLReportPart)
@property
def opts(self):
"""Class opts."""
return self._meta
@property
def projects(self):
"""Projects."""
Project = self.project_set.model
# return Project.objects.filter(program=self
# ).filter(Q(instance_of='pythia.projects.models.ScienceProject') |
# Q(instance_of='pythia.projects.models.CoreFunctionProject')
# ).prefetch_related('documents')
return self.project_set.filter(
type__in=[Project.SCIENCE_PROJECT,
Project.CORE_PROJECT]).prefetch_related('documents')
def set_smt_to_pl(sender, instance, created, **kwargs):
"""Add all Program Leaders to Group SMT.
If clobber==True, drop all SMT members beforehand.
"""
smt, created = Group.objects.get_or_create(name='SMT')
if "clobber" in kwargs and kwargs["clobber"]:
gone = [smt.user_set.remove(x) for x in smt.user_set.all()]
logger.info("Removed all {0} current SMT members.".format(len(gone)))
added = [smt.user_set.add(x.program_leader) for x in Program.objects.all()]
logger.info("Added all {0} current PLs to SMT.".format(len(added)))
# By default, let a Program add its program leader to SMT without removing
# others from it
signals.post_save.connect(set_smt_to_pl, sender=Program)
@python_2_unicode_compatible
class WorkCenter(Audit, ActiveModel):
"""A departmental work center is where staff offices are located."""
name = models.CharField(max_length=200, unique=True)
slug = models.SlugField()
# Location ---------------------------------------------------------------#
physical_address = models.ForeignKey(
Address, related_name='workcenter_physical_address')
postal_address = models.ForeignKey(
Address, related_name='workcenter_postal_address')
district = models.ForeignKey(District, blank=True, null=True)
class Meta:
"""Class opts."""
app_label = 'pythia'
verbose_name = _("Work centre")
verbose_name_plural = _("Work centres")
def __str__(self):
"""String representation."""
return self.name
def save(self, *args, **kw):
"""Generate slug from name if not set."""
if not self.slug:
self.slug = slugify(self.name)
super(WorkCenter, self).save(*args, **kw)
class WebResourceDomain(Audit, ActiveModel):
"""The domain of a Web Resource.
E.g., social networks like Google Scholar, LinkedIn, ResearchGate et al.
"""
CATEGORY_PROJECT = 1
CATEGORY_USER = 2
CATEGORY_CHOICES = (
(CATEGORY_PROJECT, "Project related"),
(CATEGORY_USER, "User related"),
)
category = models.PositiveSmallIntegerField(
max_length=200, choices=CATEGORY_CHOICES, default=CATEGORY_USER)
name = models.CharField(max_length=200)
url = models.CharField(
max_length=2000, help_text='The main URL of the web resource')
class Meta:
"""Class opts."""
verbose_name = _('Web resource domain')
verbose_name_plural = _('Web resource domains')
class URLPrefix(Audit):
"""A base URL of a commonly used resources.
E.g. http or https
"""
slug = models.SlugField(default="Custom Link")
base_url = models.CharField(
max_length=2000, help_text=_("The start of an allowed url (to be "
"joined to an actual url)"))
class Meta:
"""Class opts."""
verbose_name = _('URL prefix')
verbose_name_plural = _('URL prefixes')
class WebResource(Audit):
"""A URI pointing to any web-accessible resource."""
prefix = models.ForeignKey(URLPrefix, editable=False)
suffix = models.CharField(max_length=2000)
class Meta:
"""Class opts."""
app_label = 'pythia'
verbose_name = _("web resource")
verbose_name_plural = _("web resources")
def clean(self):
"""Clean."""
fragments = self.suffix.split("/", 3)
prefix = "/".join(fragments[:3]) + "/"
suffix = fragments[3]
if not self.base and URLPrefix.objects.filter(
base_url__iexact=prefix).exists():
self.prefix = URLPrefix.objects.get(base_url__iexact=prefix)
elif not self.base:
self.prefix = URLPrefix.objects.create(base_url=prefix)
self.suffix = suffix
@property
def url(self):
"""Url."""
return self.prefix + self.suffix
class UserManager(BaseUserManager):
"""UserManager."""
def __init__(self):
"""Init."""
super(BaseUserManager, self).__init__()
self.model = 'pythia.User' # get_user_model()
def _create_user(self, username, password, is_staff, is_superuser,
**extra_fields):
now = timezone.now()
user = self.model(username=username, is_staff=is_staff,
is_active=True, is_superuser=is_superuser,
last_login=now, date_joined=now, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, username, email, password=None, **extra_fields):
"""Create user."""
extra_fields = extra_fields or {}
extra_fields.setdefault('email', email)
return self._create_user(username, password, True, False,
**extra_fields)
def create_superuser(self, username, password, **extra_fields):
"""Create superuser."""
return self._create_user(username, password, True, True,
**extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
"""A custom user model for SDIS.
Mostly intended to make profile modification