-
Notifications
You must be signed in to change notification settings - Fork 323
/
serializers.py
245 lines (198 loc) · 9.34 KB
/
serializers.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
from rest_framework import serializers as ser
from rest_framework import exceptions
from framework.exceptions import PermissionsError
from api.base.exceptions import InvalidModelValueError
from api.base.serializers import ValuesListField, RelationshipField, LinksField, HideIfDraftRegistration, IDField
from api.base.utils import absolute_reverse, get_user_auth
from api.nodes.serializers import (
DraftRegistrationLegacySerializer,
DraftRegistrationDetailLegacySerializer,
update_institutions,
get_license_details,
NodeSerializer,
NodeLicenseSerializer,
NodeLicenseRelationshipField,
NodeContributorsSerializer,
NodeContributorsCreateSerializer,
NodeContributorDetailSerializer,
RegistrationSchemaRelationshipField,
)
from api.taxonomies.serializers import TaxonomizableSerializerMixin
from osf.exceptions import DraftRegistrationStateError
from osf.models import Node
from website import settings
class NodeRelationshipField(RelationshipField):
def to_internal_value(self, node_id):
return {'branched_from': Node.load(node_id)}
class DraftRegistrationSerializer(DraftRegistrationLegacySerializer, TaxonomizableSerializerMixin):
"""
New DraftRegistrationSerializer - instead of the node_id being provided in the URL, an optional
node is passed in under `branched_from`.
DraftRegistrations have several fields that can be edited that are persisted to the final registration.
"""
category_choices = list(settings.NODE_CATEGORY_MAP.items())
category_choices_string = ', '.join(["'{}'".format(choice[0]) for choice in category_choices])
title = ser.CharField(required=False, allow_blank=True)
description = ser.CharField(required=False, allow_blank=True, allow_null=True)
category = ser.ChoiceField(required=False, choices=category_choices, help_text='Choices: ' + category_choices_string)
tags = ValuesListField(attr_name='name', child=ser.CharField(), required=False)
node_license = NodeLicenseSerializer(required=False, source='license')
links = LinksField({
'self': 'get_absolute_url',
})
affiliated_institutions = RelationshipField(
related_view='draft_registrations:draft-registration-institutions',
related_view_kwargs={'draft_id': '<_id>'},
self_view='draft_registrations:draft-registration-relationships-institutions',
self_view_kwargs={'draft_id': '<_id>'},
read_only=False,
many=True,
required=False,
)
branched_from = NodeRelationshipField(
related_view=lambda n: 'draft_nodes:draft-node-detail' if getattr(n, 'type', False) == 'osf.draftnode' else 'nodes:node-detail',
related_view_kwargs={'node_id': '<branched_from._id>'},
read_only=False,
required=False,
)
contributors = RelationshipField(
related_view='draft_registrations:draft-registration-contributors',
related_view_kwargs={'draft_id': '<_id>'},
)
bibliographic_contributors = RelationshipField(
related_view='draft_registrations:draft-registration-bibliographic-contributor-detail',
related_view_kwargs={'draft_id': '<_id>'},
)
current_user_permissions = ser.SerializerMethodField(
help_text='List of strings representing the permissions '
'for the current user on this draft registratione.',
)
license = NodeLicenseRelationshipField(
related_view='licenses:license-detail',
related_view_kwargs={'license_id': '<license.node_license._id>'},
read_only=False,
)
has_project = ser.SerializerMethodField()
def get_has_project(self, obj):
return obj.has_project
@property
def subjects_related_view(self):
# Overrides TaxonomizableSerializerMixin
return 'draft_registrations:draft-registration-subjects'
@property
def subjects_view_kwargs(self):
# Overrides TaxonomizableSerializerMixin
return {'draft_id': '<_id>'}
@property
def subjects_self_view(self):
# Overrides TaxonomizableSerializerMixin
return 'draft_registrations:draft-registration-relationships-subjects'
def get_self_url(self, obj):
return absolute_reverse(
'draft_registrations:draft-registration-list',
kwargs={
'version': self.context['request'].parser_context['kwargs']['version'],
},
)
def get_absolute_url(self, obj):
return obj.get_absolute_url()
# Overrides DraftRegistrationLegacySerializer
def get_node(self, validated_data):
# Node comes from branched_from relationship rather than from URL
return validated_data.pop('branched_from', None)
def get_current_user_permissions(self, obj):
return NodeSerializer.get_current_user_permissions(self, obj)
def expect_subjects_as_relationships(self, request):
"""Determines whether subjects should be serialized as a relationship.
Older serializers expect subjects as attributes for earlier versions,
but this new serializer does not have to adhere to that same behavior.
:param object request: Request object
:return bool: Subjects should be serialized as relationships
"""
# Overrides TaxonomizableSerializerMixin
return True
class DraftRegistrationDetailSerializer(DraftRegistrationSerializer, DraftRegistrationDetailLegacySerializer):
"""
Overrides DraftRegistrationLegacySerializer to make id required.
registration_supplement, node, cannot be changed after draft has been created.
"""
id = IDField(source='_id', required=True)
registration_schema = RegistrationSchemaRelationshipField(
related_view='schemas:registration-schema-detail',
related_view_kwargs={'schema_id': '<registration_schema._id>'},
required=False,
read_only=False,
)
links = LinksField({
'self': 'get_self_url',
})
def get_self_url(self, obj):
return absolute_reverse(
'draft_registrations:draft-registration-detail',
kwargs={
'version': self.context['request'].parser_context['kwargs']['version'],
'draft_id': self.context['request'].parser_context['kwargs']['draft_id'],
},
)
def update(self, draft, validated_data):
draft = super(DraftRegistrationDetailSerializer, self).update(draft, validated_data)
user = self.context['request'].user
auth = get_user_auth(self.context['request'])
if 'tags' in validated_data:
new_tags = set(validated_data.pop('tags', []))
draft.update_tags(new_tags, auth=auth)
if 'license_type' in validated_data or 'license' in validated_data:
license_details = get_license_details(draft, validated_data)
validated_data['node_license'] = license_details
if 'affiliated_institutions' in validated_data:
institutions_list = validated_data.pop('affiliated_institutions')
new_institutions = [{'_id': institution} for institution in institutions_list]
update_institutions(draft, new_institutions, user)
if 'subjects' in validated_data:
subjects = validated_data.pop('subjects', None)
self.update_subjects(draft, subjects, auth)
try:
draft.update(validated_data, auth=auth)
except PermissionsError:
raise exceptions.PermissionDenied
except DraftRegistrationStateError as e:
raise InvalidModelValueError(detail=str(e))
return draft
class DraftRegistrationContributorsSerializer(NodeContributorsSerializer):
draft_registration = RelationshipField(
related_view='draft_registrations:draft-registration-detail',
related_view_kwargs={'draft_id': '<draft_registration._id>'},
)
node = HideIfDraftRegistration(RelationshipField(
related_view='nodes:node-detail',
related_view_kwargs={'node_id': '<node._id>'},
))
class Meta:
type_ = 'contributors'
links = LinksField({
'self': 'get_absolute_url',
})
def get_absolute_url(self, obj):
return absolute_reverse(
'draft_registrations:draft-registration-contributor-detail',
kwargs={
'user_id': obj.user._id,
'draft_id': self.context['request'].parser_context['kwargs']['draft_id'],
'version': self.context['request'].parser_context['kwargs']['version'],
},
)
class DraftRegistrationContributorsCreateSerializer(NodeContributorsCreateSerializer, DraftRegistrationContributorsSerializer):
"""
Overrides DraftRegistrationContributorsSerializer to add email, full_name, send_email, and non-required index and users field.
id and index redefined because of the two serializers we've inherited
"""
id = IDField(source='_id', required=False, allow_null=True)
index = ser.IntegerField(required=False, source='_order')
email_preferences = ['draft_registration', 'false']
class DraftRegistrationContributorDetailSerializer(NodeContributorDetailSerializer, DraftRegistrationContributorsSerializer):
"""
Overrides NodeContributorDetailSerializer to set the draft registration instead of the node
id and index redefined because of the two serializers we've inherited
"""
id = IDField(required=True, source='_id')
index = ser.IntegerField(required=False, read_only=False, source='_order')