class MembershipSerializer(SetModifyingUserOnIdentityMixin, serializers.ModelSerializer): identity = serializers.ResourceRelatedField( queryset=models.Identity.objects.filter(is_organisation=False)) organisation = serializers.ResourceRelatedField( queryset=models.Identity.objects.filter(is_organisation=True)) time_slot = DateRangeField() included_serializers = { "role": MembershipRoleSerializer, } def validate(self, *args, **kwargs): validated_data = super().validate(*args, **kwargs) if not self.instance: return validated_data for field in ["identity", "organisation"]: if validated_data.get(field) and validated_data[field] != getattr( self.instance, field): raise ValidationError(f'Field "{field}" can\'t be modified.') return validated_data class Meta: model = models.Membership fields = ( "identity", "organisation", "role", "authorized", "time_slot", "next_election", "comment", "inactive", )
def test_no_source_on_child(self): with pytest.raises(AssertionError) as exc_info: DateRangeField(child=serializers.IntegerField(source='other')) assert str(exc_info.value) == ( "The `source` argument is not meaningful when applied to a `child=` field. " "Remove `source=` from the field declaration.")
class TestDateRangeField(FieldValues): """ Values for `ListField` with CharField as child. """ serializer_class = DateRangeSerializer if compat.DateRange is not None: valid_inputs = [ ({'lower': '2001-01-01', 'upper': '2001-02-02', 'bounds': '[)'}, compat.DateRange( **{'lower': datetime.date(2001, 1, 1), 'upper': datetime.date(2001, 2, 2), 'bounds': '[)'})), ({'upper': '2001-02-02', 'bounds': '[)'}, compat.DateRange( **{'upper': datetime.date(2001, 2, 2), 'bounds': '[)'})), ({'lower': '2001-01-01', 'bounds': '[)'}, compat.DateRange( **{'lower': datetime.date(2001, 1, 1), 'bounds': '[)'})), ({'empty': True}, compat.DateRange(**{'empty': True})), ({}, compat.DateRange()), ] invalid_inputs = [ ({'lower': 'a'}, ['Date has wrong format. Use one of these' ' formats instead: ' 'YYYY-MM-DD.']), ('not a dict', ['Expected a dictionary of items but got type "str".']), ] outputs = [ (compat.DateRange( **{'lower': datetime.date(2001, 1, 1), 'upper': datetime.date(2001, 2, 2)}), {'lower': '2001-01-01', 'upper': '2001-02-02', 'bounds': '[)'}), (compat.DateRange(**{'empty': True}), {'empty': True}), (compat.DateRange(), {'bounds': '[)', 'lower': None, 'upper': None}), ] field = DateRangeField() def test_no_source_on_child(self): with pytest.raises(AssertionError) as exc_info: DateRangeField(child=serializers.IntegerField(source='other')) assert str(exc_info.value) == ( "The `source` argument is not meaningful when applied to a `child=` field. " "Remove `source=` from the field declaration." )
class DateRangeSerializer(serializers.Serializer): range = DateRangeField()
class JobSerializer(DynamicFieldsModelSerializer): created_by = serializers.PrimaryKeyRelatedField( read_only=True, default=serializers.CurrentUserDefault()) application = serializers.SerializerMethodField() location = serializers.SlugRelatedField(slug_field='name_std', queryset=City.objects.only( "id", "name", "name_std").all()) required_gender = ChoicesField(choices=choices.GENDER_CHOICES) likes = serializers.SerializerMethodField(read_only=True) required_information_to_apply = RequiredInformationSerializerFiled( read_only=True) reason_for_rejection = serializers.SerializerMethodField() group = GroupSerializer(required=False) images = ImageSerializer(many=True, read_only=True) status = ChoicesField(choices=choices.JOB_STATE_CHOICES, default=choices.PENDING_APPROVAL) job_type = ChoicesField(choices=choices.JOB_TYPE_CHOICES, default=choices.OTHER) submission_deadline = serializers.DateField(read_only=True) ages = IntegerRangeField() heights = FloatRangeField() budgets = IntegerRangeField() audition_range = DateRangeField() class Meta: model = Job fields = ('id', 'created_at', 'created_by', 'role_position', 'title', 'description', 'ages', 'required_gender', 'location', 'required_information_to_apply', 'required_tokens', 'status', 'reason_for_rejection', 'application', 'submission_deadline', 'group', 'likes', 'images', 'number_of_vacancies', 'featured', 'skin_type', 'hair_type', 'eye_color', 'body_type', 'audition_range', 'language', 'heights', 'budgets', 'job_type') def create(self, validated_data): return Job.objects.create(**validated_data) def get_required_gender(self, obj): return obj.get_required_gender_display() def get_job_type(self, obj): return obj.get_job_type_display() def get_application(self, obj): try: if 'request' in self.context: request = self.context['request'] user = request.user from application.serializers import ApplicationSerializer return ApplicationSerializer(obj.applications.get(user=user), context={ 'request': self.context['request'] }).data except: pass return None def get_reason_for_rejection(self, obj): if obj.status == choices.REMOVED: return obj.reason_for_rejection else: return None def get_likes(self, obj): try: if 'request' in self.context: user = self.context['request'].user like = Like.objects.filter( sender=user, receiver_content_type=ContentType.objects.get_for_model( Job), receiver_object_id=obj.id) if like: return True except: pass return False
class DateRangeWithAllowEmptyTrueSerializer(serializers.Serializer): range = DateRangeField(allow_empty=True)
class DateRangeWithAllowEmptyFalseSerializer(serializers.Serializer): range = DateRangeField(allow_empty=False)
class DateRangeSerializer(serializers.Serializer): range = DateRangeField(initial=DateRange(None, None))
class TestDateRangeField(FieldValues): """ Values for `ListField` with CharField as child. """ serializer_class = DateRangeSerializer valid_inputs = [ ({ 'lower': '2001-01-01', 'upper': '2001-02-02', 'bounds': '[)' }, DateRange( **{ 'lower': datetime.date(2001, 1, 1), 'upper': datetime.date(2001, 2, 2), 'bounds': '[)' })), ({ 'upper': '2001-02-02', 'bounds': '[)' }, DateRange(**{ 'upper': datetime.date(2001, 2, 2), 'bounds': '[)' })), ({ 'lower': '2001-01-01', 'bounds': '[)' }, DateRange(**{ 'lower': datetime.date(2001, 1, 1), 'bounds': '[)' })), ({ 'empty': True }, DateRange(**{'empty': True})), ({}, DateRange()), ] invalid_inputs = [ ({ 'lower': 'a' }, [ 'Date has wrong format. Use one of these' ' formats instead: ' 'YYYY-MM-DD.' ]), ('not a dict', ['Expected a dictionary of items but got type "str".']), ({ 'lower': '2001-02-02', 'upper': '2001-01-01' }, ['The start of the range must not exceed the end of the range.']), ] outputs = [ (DateRange( **{ 'lower': datetime.date(2001, 1, 1), 'upper': datetime.date(2001, 2, 2) }), { 'lower': '2001-01-01', 'upper': '2001-02-02', 'bounds': '[)' }), (DateRange(**{'empty': True}), { 'empty': True }), (DateRange(), { 'bounds': '[)', 'lower': None, 'upper': None }), ({ 'lower': '2001-01-01', 'upper': '2001-02-02', 'bounds': '[)' }, { 'lower': '2001-01-01', 'upper': '2001-02-02', 'bounds': '[)' }), ({ 'lower': datetime.date(2001, 1, 1), 'upper': datetime.date(2001, 2, 2), 'bounds': '[)' }, { 'lower': '2001-01-01', 'upper': '2001-02-02', 'bounds': '[)' }), ({ 'upper': '2001-02-02', 'bounds': '[)' }, { 'lower': None, 'upper': '2001-02-02', 'bounds': '[)' }), ({ 'lower': '2001-01-01', 'bounds': '[)' }, { 'lower': '2001-01-01', 'upper': None, 'bounds': '[)' }), ({}, {}), ] field = DateRangeField() def test_no_source_on_child(self): with pytest.raises(AssertionError) as exc_info: DateRangeField(child=serializers.IntegerField(source='other')) assert str(exc_info.value) == ( "The `source` argument is not meaningful when applied to a `child=` field. " "Remove `source=` from the field declaration.") def test_initial_value_of_field(self): serializer = DateRangeSerializer() assert serializer.data['range'] == { 'lower': None, 'upper': None, 'bounds': '[)' } def test_allow_empty(self): serializer = DateRangeWithAllowEmptyFalseSerializer(data={"range": {}}) with pytest.raises(serializers.ValidationError) as exc_info: serializer.is_valid(raise_exception=True) assert exc_info.value.detail == [ "This dictionary may not be empty." ] serializer = DateRangeWithAllowEmptyTrueSerializer(data={"range": {}}) assert serializer.is_valid()