+class AttributeValue(models.Model):
+ attribute_set = generic.GenericRelation('Attribute', content_type_field='value_content_type', object_id_field='value_object_id')
+
+ @property
+ def attribute(self):
+ return self.attribute_set.all()[0]
+
+ def apply_data(self, data):
+ raise NotImplementedError
+
+ def value_formfield(self, **kwargs):
+ raise NotImplementedError
+
+ def __unicode__(self):
+ return unicode(self.value)
+
+ class Meta:
+ abstract = True
+
+
+attribute_value_limiter = ContentTypeSubclassLimiter(AttributeValue)
+
+
+class JSONValue(AttributeValue):
+ value = JSONField() #verbose_name='Value (JSON)', help_text='This value must be valid JSON.')
+
+ def __unicode__(self):
+ return self.value_json
+
+ def value_formfield(self, **kwargs):
+ kwargs['initial'] = self.value_json
+ return self._meta.get_field('value').formfield(**kwargs)
+
+ def apply_data(self, cleaned_data):
+ self.value = cleaned_data.get('value', None)
+
+ class Meta:
+ app_label = 'philo'
+
+
+class ForeignKeyValue(AttributeValue):
+ content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
+ object_id = models.PositiveIntegerField(verbose_name='Value ID', null=True, blank=True)
+ value = generic.GenericForeignKey()
+
+ def value_formfield(self, form_class=forms.ModelChoiceField, **kwargs):
+ if self.content_type is None:
+ return None
+ kwargs.update({'initial': self.object_id, 'required': False})
+ return form_class(self.content_type.model_class()._default_manager.all(), **kwargs)
+
+ def apply_data(self, cleaned_data):
+ if 'value' in cleaned_data and cleaned_data['value'] is not None:
+ self.value = cleaned_data['value']
+ else:
+ self.content_type = cleaned_data.get('content_type', None)
+ # If there is no value set in the cleaned data, clear the stored value.
+ self.object_id = None
+
+ class Meta:
+ app_label = 'philo'
+
+
+class ManyToManyValue(AttributeValue):
+ content_type = models.ForeignKey(ContentType, limit_choices_to=value_content_type_limiter, verbose_name='Value type', null=True, blank=True)
+ values = models.ManyToManyField(ForeignKeyValue, blank=True, null=True)
+
+ def get_object_id_list(self):
+ if not self.values.count():
+ return []
+ else:
+ return self.values.values_list('object_id', flat=True)