-
Notifications
You must be signed in to change notification settings - Fork 467
Expand file tree
/
Copy pathfields.py
More file actions
61 lines (42 loc) · 1.85 KB
/
fields.py
File metadata and controls
61 lines (42 loc) · 1.85 KB
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
"""Model choice fields that take a ContentType too: for generic relations."""
from django.contrib.contenttypes.models import ContentType
class ContentTypeModelFieldMixin(object):
"""
Common methods for form fields for GenericForeignKey.
ModelChoiceFieldMixin expects options to look like::
<option value="4">Model #4</option>
With a ContentType of id 3 for that model, it becomes::
<option value="3-4">Model #4</option>
"""
def prepare_value(self, value):
"""Return a ctypeid-objpk string for value."""
if not value:
return ''
if isinstance(value, str):
# Apparently Django's ModelChoiceField also expects two kinds of
# "value" to be passed in this method.
return value
return '%s-%s' % (ContentType.objects.get_for_model(value).pk,
value.pk)
class ContentTypeModelMultipleFieldMixin(ContentTypeModelFieldMixin):
"""Same as ContentTypeModelFieldMixin, but supports value list."""
def prepare_value(self, value):
"""Run the parent's method for each value."""
if not value: # ModelMultipleChoiceField does it too
return []
return [
super().prepare_value(v)
for v in value
]
class GenericModelMixin(ContentTypeModelFieldMixin):
"""GenericForeignKey support for form fields, with FutureModelForm.
GenericForeignKey enforce editable=false, this class implements
save_object_data() and value_from_object() to allow FutureModelForm to
compensate.
"""
def save_object_data(self, instance, name, value):
"""Set the attribute, for FutureModelForm."""
setattr(instance, name, value)
def value_from_object(self, instance, name):
"""Get the attribute, for FutureModelForm."""
return getattr(instance, name)