rapidfields.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # coding=utf-8
  2. from __future__ import absolute_import
  3. from __future__ import division
  4. from __future__ import print_function
  5. from __future__ import unicode_literals
  6. from django.contrib.contenttypes.fields import GenericForeignKey
  7. from django.contrib.contenttypes.models import ContentType
  8. from rapid.rapidforms import RapidAlternativesField
  9. from django.db import models
  10. __author__ = 'marcos'
  11. """
  12. Model fields specific for Rapid Django.
  13. """
  14. class AlternativeData(GenericForeignKey):
  15. """
  16. A generic relation that Rapid will display as an inline form or a group of data at the
  17. edit and view actions.
  18. Create like a Django GenericForeignKey, but use an AlternativeDataTables instead of a
  19. ForeignKey to ContentTypes.
  20. """
  21. is_rapid_alternatives = True
  22. def __init__(self, *args, **kwargs):
  23. verbose_name = kwargs.get('verbose_name')
  24. if 'verbose_name' in kwargs:
  25. del(kwargs['verbose_name'])
  26. super(AlternativeData, self).__init__(*args, **kwargs)
  27. if verbose_name:
  28. self.verbose_name = verbose_name
  29. elif self.name:
  30. self.verbose_name = self.name.replace('_', ' ')
  31. def formfield(self, **kwargs):
  32. kwargs['form_class'] = RapidAlternativesField
  33. # noinspection PyUnresolvedReferences
  34. return super(GenericForeignKey, self).formfield(**kwargs)
  35. class AlternativeDataTables(models.ForeignKey):
  36. """
  37. Use an AlternativeDataTables model field on AlternativeData representations, instead of
  38. a ForeignKey with ContentTypes.
  39. """
  40. is_rapid_alternatives = True
  41. def __init__(self, alternatives=(), **kwargs):
  42. """
  43. Receives the same named parameters of a ForeignKey, but instead of a target table,
  44. receives a list of the tables that may keep the alternative data.
  45. :param alternatives: List of the tables that hold the alternative data.
  46. :param kwargs: Arguments to the ForeignKey, without a relationship target.
  47. """
  48. pks = []
  49. try:
  50. pks = [ContentType.objects.get_for_model(a).pk for a in alternatives]
  51. except RuntimeError:
  52. # Querying ContentType within a content type is an issue at migrations
  53. pass
  54. kwargs['limit_choices_to'] = {'pk__in': pks}
  55. kwargs['to'] = ContentType
  56. super(AlternativeDataTables, self).__init__(**kwargs)
  57. self.alternatives = alternatives