Beispiel #1
0
class CommentSerializer(BasisModelSerializer):
    author = PublicUserSerializer(read_only=True, source="created_by")
    created_at = DateTimeField(read_only=True)
    updated_at = DateTimeField(read_only=True)
    content_target = GenericRelationField(source="content_object")
    text = ContentSerializerField()

    class Meta:
        model = Comment
        fields = (
            "id",
            "text",
            "author",
            "content_target",
            "created_at",
            "updated_at",
            "parent",
        )

    def validate(self, attrs):
        content_target = attrs.get("content_object")

        if content_target and "parent" in attrs:
            parent = attrs["parent"]
            if (
                parent.object_id != content_target.id
                or parent.content_type
                != ContentType.objects.get_for_model(content_target)
            ):
                raise ValidationError(
                    {"parent": "parent does not point to the same content_target"}
                )

        return attrs
 def expected_response(self, app_instance):
     return {
         'application_template_name':
         app_instance.application_template.name,
         'commit_id':
         app_instance.commit_id,
         'cpu':
         app_instance.cpu,
         'id':
         str(app_instance.id),
         'memory':
         app_instance.memory,
         'owner_id':
         app_instance.owner_id,
         'proxy_url':
         app_instance.proxy_url,
         'public_host':
         app_instance.public_host,
         'spawner':
         app_instance.spawner,
         'spawner_application_instance_id':
         str(app_instance.spawner_application_instance_id),
         'spawner_cpu':
         app_instance.spawner_cpu,
         'spawner_created_at':
         DateTimeField().to_representation(app_instance.spawner_created_at),
         'spawner_memory':
         app_instance.spawner_memory,
         'spawner_stopped_at':
         DateTimeField().to_representation(app_instance.spawner_stopped_at),
         'state':
         app_instance.get_state_display(),
     }
Beispiel #3
0
class SourceDetailSerializer(SourceCreateOrUpdateSerializer):
    type = CharField(source='resource_type')
    uuid = CharField(source='id')
    id = CharField(source='mnemonic')
    short_code = CharField(source='mnemonic')
    owner = CharField(source='parent_resource')
    owner_type = CharField(source='parent_resource_type')
    owner_url = CharField(source='parent_url')
    versions = IntegerField(source='num_versions')
    created_on = DateTimeField(source='created_at')
    updated_on = DateTimeField(source='updated_at')
    supported_locales = ListField(required=False, allow_empty=True)
    created_by = CharField(source='created_by.username', read_only=True)
    updated_by = DateTimeField(source='updated_by.username', read_only=True)

    class Meta:
        model = Source
        lookup_field = 'mnemonic'
        fields = ('type', 'uuid', 'id', 'short_code', 'name', 'full_name',
                  'description', 'source_type', 'custom_validation_schema',
                  'public_access', 'default_locale', 'supported_locales',
                  'website', 'url', 'owner', 'owner_type', 'owner_url',
                  'versions', 'created_on', 'updated_on', 'created_by',
                  'updated_by', 'extras', 'external_id', 'versions_url',
                  'version', 'concepts_url', 'mappings_url', 'active_concepts',
                  'active_mappings')
Beispiel #4
0
class BillableItemSerializer(Serializer):
    type = ChoiceField([
        'missed_reservation', 'tool_usage', 'area_access', 'consumable',
        'staff_charge', 'training_session'
    ])
    name = CharField(max_length=200, read_only=True)
    details = CharField(max_length=500, read_only=True)
    account = CharField(max_length=200, read_only=True)
    account_id = IntegerField(read_only=True)
    project = CharField(max_length=200, read_only=True)
    project_id = IntegerField(read_only=True)
    application = CharField(max_length=200, read_only=True)
    user = CharField(max_length=255, read_only=True)
    username = CharField(max_length=200, read_only=True)
    user_id = IntegerField(read_only=True)
    start = DateTimeField(read_only=True)
    end = DateTimeField(read_only=True)
    quantity = DecimalField(read_only=True, decimal_places=2, max_digits=8)

    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        pass

    class Meta:
        fields = '__all__'
Beispiel #5
0
class ProctoredExamStudentAttemptSerializer(serializers.ModelSerializer):
    """
    Serializer for the ProctoredExamStudentAttempt Model.
    """
    proctored_exam = ProctoredExamSerializer()
    user = UserSerializer()

    # Django Rest Framework v3 defaults to `settings.DATE_FORMAT` when serializing
    # datetime fields.  We need to specify `format=None` to maintain the old behavior
    # of returning raw `datetime` objects instead of unicode.
    started_at = DateTimeField(format=None)
    completed_at = DateTimeField(format=None)
    last_poll_timestamp = DateTimeField(format=None)

    class Meta:
        """
        Meta Class
        """
        model = ProctoredExamStudentAttempt

        fields = (
            "id", "created", "modified", "user", "started_at", "completed_at",
            "external_id", "status", "proctored_exam", "allowed_time_limit_mins",
            "attempt_code", "is_sample_attempt", "taking_as_proctored", "last_poll_timestamp",
            "last_poll_ipaddr", "review_policy_id", "student_name", "is_status_acknowledged",
            "time_remaining_seconds", "is_resumable"
        )
Beispiel #6
0
 def expected_response(self, app_instance):
     return {
         "application_template_name":
         app_instance.application_template.name,
         "commit_id":
         app_instance.commit_id,
         "cpu":
         app_instance.cpu,
         "id":
         str(app_instance.id),
         "memory":
         app_instance.memory,
         "owner_id":
         app_instance.owner_id,
         "proxy_url":
         app_instance.proxy_url,
         "public_host":
         app_instance.public_host,
         "spawner":
         app_instance.spawner,
         "spawner_application_instance_id":
         str(app_instance.spawner_application_instance_id),
         "spawner_cpu":
         app_instance.spawner_cpu,
         "spawner_created_at":
         DateTimeField().to_representation(app_instance.spawner_created_at),
         "spawner_memory":
         app_instance.spawner_memory,
         "spawner_stopped_at":
         DateTimeField().to_representation(app_instance.spawner_stopped_at),
         "state":
         app_instance.get_state_display(),
     }
Beispiel #7
0
class CommentSerializer(BasisModelSerializer):
    author = PublicUserSerializer(read_only=True, source='created_by')
    created_at = DateTimeField(read_only=True)
    updated_at = DateTimeField(read_only=True)
    comment_target = GenericRelationField(source='content_object')
    text = ContentSerializerField()

    class Meta:
        model = Comment
        fields = ('id', 'text', 'author', 'comment_target', 'created_at', 'updated_at', 'parent')

    def validate(self, attrs):
        comment_target = attrs.get('content_object')

        if comment_target and 'parent' in attrs:
            parent = attrs['parent']
            if parent.object_id != comment_target.id or parent.content_type != \
                    ContentType.objects.get_for_model(comment_target):
                raise ValidationError(
                    {
                        'parent': 'parent does not point to the same comment_target'
                    }
                )

        return attrs
Beispiel #8
0
class SourceVersionDetailSerializer(SourceCreateOrUpdateSerializer):
    type = CharField(source='resource_type')
    uuid = CharField(source='id')
    id = CharField(source='version')
    short_code = CharField(source='mnemonic')
    owner = CharField(source='parent_resource')
    owner_type = CharField(source='parent_resource_type')
    owner_url = CharField(source='parent_url')
    created_on = DateTimeField(source='created_at')
    updated_on = DateTimeField(source='updated_at')
    created_by = CharField(source='created_by.username', read_only=True)
    updated_by = DateTimeField(source='updated_by.username', read_only=True)
    supported_locales = ListField(required=False, allow_empty=True)
    is_processing = BooleanField(read_only=True)
    released = BooleanField(default=False)
    version_url = CharField(source='uri')
    url = CharField(source='versioned_object_url')
    previous_version_url = CharField(source='prev_version_uri')
    summary = SerializerMethodField()

    class Meta:
        model = Source
        lookup_field = 'mnemonic'
        fields = ('type', 'uuid', 'id', 'short_code', 'name', 'full_name',
                  'description', 'source_type', 'custom_validation_schema',
                  'public_access', 'default_locale', 'supported_locales',
                  'website', 'url', 'owner', 'owner_type', 'owner_url',
                  'retired', 'version_url', 'previous_version_url',
                  'created_on', 'updated_on', 'created_by', 'updated_by',
                  'extras', 'external_id', 'version', 'concepts_url',
                  'mappings_url', 'is_processing', 'released', 'canonical_url',
                  'identifier', 'publisher', 'contact', 'jurisdiction',
                  'purpose', 'copyright', 'content_type', 'revision_date',
                  'summary', 'text')

    def __init__(self, *args, **kwargs):
        params = get(kwargs, 'context.request.query_params')
        self.include_summary = False
        if params:
            self.query_params = params.dict()
            self.include_summary = self.query_params.get(INCLUDE_SUMMARY) in [
                'true', True
            ]

        try:
            if not self.include_summary:
                self.fields.pop('summary', None)
        except:  # pylint: disable=bare-except
            pass

        super().__init__(*args, **kwargs)

    def get_summary(self, obj):
        summary = None

        if self.include_summary:
            summary = SourceVersionSummarySerializer(obj).data

        return summary
Beispiel #9
0
class PharmacyShiftSerializer(DynamicModelSerializer):
    pharmacy = DynamicRelationField(BusinessSerializer, embed=True)
    start = DateTimeField(default_timezone=utc_timezone)
    end = DateTimeField(default_timezone=utc_timezone)

    class Meta:
        model = PharmacyShift
        fields = ["pharmacy", "start", "end"]
Beispiel #10
0
class CollectionVersionDetailSerializer(CollectionCreateOrUpdateSerializer):
    type = CharField(source='resource_type')
    uuid = CharField(source='id')
    id = CharField(source='version')
    short_code = CharField(source='mnemonic')
    owner = CharField(source='parent_resource')
    owner_type = CharField(source='parent_resource_type')
    owner_url = CharField(source='parent_url')
    versions = IntegerField(source='num_versions')
    created_on = DateTimeField(source='created_at')
    updated_on = DateTimeField(source='updated_at')
    supported_locales = ListField(required=False, allow_empty=True)
    is_processing = BooleanField(read_only=True)
    version_url = CharField(source='uri')
    url = CharField(source='versioned_object_url')
    previous_version_url = CharField(source='prev_version_uri')

    class Meta:
        model = Collection
        lookup_field = 'mnemonic'
        fields = (
            'type',
            'uuid',
            'id',
            'short_code',
            'name',
            'full_name',
            'description',
            'collection_type',
            'custom_validation_schema',
            'public_access',
            'default_locale',
            'supported_locales',
            'website',
            'url',
            'owner',
            'owner_type',
            'owner_url',
            'versions',
            'version_url',
            'previous_version_url',
            'created_on',
            'updated_on',
            'created_by',
            'updated_by',
            'extras',
            'external_id',
            'version',
            'version',
            'concepts_url',
            'mappings_url',
            'is_processing',
            'canonical_url',
            'released',
            'retired',
        )
Beispiel #11
0
class SourceCreateSerializer(SourceCreateOrUpdateSerializer):
    type = CharField(source='resource_type', read_only=True)
    uuid = CharField(source='id', read_only=True)
    id = CharField(required=True,
                   validators=[RegexValidator(regex=NAMESPACE_REGEX)],
                   source='mnemonic')
    short_code = CharField(source='mnemonic', read_only=True)
    name = CharField(required=True)
    full_name = CharField(required=False)
    description = CharField(required=False, allow_blank=True)
    source_type = CharField(required=False, allow_blank=True)
    custom_validation_schema = CharField(required=False,
                                         allow_blank=True,
                                         allow_null=True)
    public_access = ChoiceField(required=False, choices=ACCESS_TYPE_CHOICES)
    default_locale = CharField(required=False, allow_blank=True)
    supported_locales = ListField(required=False, allow_empty=True)
    website = CharField(required=False, allow_blank=True)
    url = CharField(read_only=True)
    canonical_url = CharField(required=False,
                              allow_null=True,
                              allow_blank=True)
    versions_url = CharField(read_only=True)
    concepts_url = CharField(read_only=True)
    mappings_url = CharField(read_only=True)
    owner = CharField(source='parent_resource', read_only=True)
    owner_type = CharField(source='parent_resource_type', read_only=True)
    owner_url = CharField(source='parent_url', read_only=True)
    versions = IntegerField(source='num_versions', read_only=True)
    created_on = DateTimeField(source='created_at', read_only=True)
    updated_on = DateTimeField(source='updated_at', read_only=True)
    created_by = CharField(source='owner', read_only=True)
    updated_by = CharField(read_only=True)
    extras = JSONField(required=False, allow_null=True)
    external_id = CharField(required=False, allow_blank=True)
    user_id = PrimaryKeyRelatedField(required=False,
                                     queryset=UserProfile.objects.all(),
                                     allow_null=True)
    organization_id = PrimaryKeyRelatedField(
        required=False, queryset=Organization.objects.all(), allow_null=True)
    version = CharField(default=HEAD)

    def create(self, validated_data):
        source = self.prepare_object(validated_data)
        user = self.context['request'].user
        errors = Source.persist_new(source, user)
        self._errors.update(errors)
        return source

    def create_version(self, validated_data):
        source = self.prepare_object(validated_data)
        user = self.context['request'].user
        errors = Source.persist_new_version(source, user)
        self._errors.update(errors)
        return source
Beispiel #12
0
class EventCreateUpdateSerializer(ModelSerializer):
    start = DateTimeField(format="%Y-%m-%dT%X", )
    end = DateTimeField(format="%Y-%m-%dT%X", )

    class Meta:
        model = Event
        fields = [
            "title",
            "start",
            "end",
        ]
class TeamSubmissionSerializer(serializers.ModelSerializer):
    """ Serializer for TeamSubmissions """

    team_submission_uuid = serializers.UUIDField(source='uuid', read_only=True)
    submission_uuids = serializers.SlugRelatedField(source='submissions',
                                                    many=True,
                                                    read_only=True,
                                                    slug_field='uuid')

    # See comments on SubmissionSerializer below
    submitted_at = DateTimeField(format=None, required=False)
    created_at = DateTimeField(source='created', format=None, required=False)
    attempt_number = IntegerField(min_value=0)
    # Prevent Django Rest Framework from converting the answer (dict or str)
    # to a string.
    # answer is not a part of TeamSubmission model. We populate it externally.
    answer = serializers.SerializerMethodField()

    def get_answer(self, obj):
        """
        Regular submissions are created after a team submission. In this case, the answer is passed as part of context
        otherwise, get the answer from its related submission. All individual submissions are identical except for
        student data. Therefore, get the answer of the first submitter
        """
        answer = self.context.get("answer")
        if answer is None and obj.submissions is not None:
            #  retrieve answer submissions from the linked submission model. There are n identical submissions
            answer = obj.submissions.first().answer
        return answer

    def validate_answer(self, value):
        """
        Check that the answer is JSON-serializable and not too long.
        """
        # Check that the answer is JSON-serializable
        try:
            serialized = json.dumps(value)
        except (ValueError, TypeError):
            raise serializers.ValidationError(
                "Answer value must be JSON-serializable")

        # Check the length of the serialized representation
        if len(serialized) > Submission.MAXSIZE:
            raise serializers.ValidationError("Maximum answer size exceeded.")

        return value

    class Meta:
        model = TeamSubmission
        fields = ('team_submission_uuid', 'attempt_number', 'submitted_at',
                  'course_id', 'item_id', 'team_id', 'submitted_by',
                  'created_at', 'answer', 'submission_uuids')
Beispiel #14
0
class UserSerializer(ModelSerializer):
    last_login = DateTimeField(read_only=True)
    date_joined = DateTimeField(read_only=True)
    password = CharField(write_only=True)
    country = CountryField()

    class Meta:
        model = User
        fields = [
            'username', 'password', 'email', 'first_name', 'last_name',
            'organisation', 'last_login', 'date_joined', 'country', 'orcid',
            'id', 'copied_runs'
        ]
class BuyerSerializer(serializers.ModelSerializer):
    last_scan = DateTimeField(source="last_successful_scan",
                              format="%c",
                              read_only=True)
    next_scan = DateTimeField(source="next_scheduled_scan",
                              format="%c",
                              read_only=True)
    last_successful = DateTimeField(source="last_successful_scan",
                                    format="%c",
                                    read_only=True)

    class Meta:
        model = Buyer
        fields = "__all__"
Beispiel #16
0
class ConceptListSerializer(ModelSerializer):
    uuid = CharField(source='id', read_only=True)
    id = CharField(source='mnemonic')
    source = CharField(source='parent_resource')
    owner = CharField(source='owner_name')
    update_comment = CharField(source='comment', required=False, allow_null=True, allow_blank=True)
    locale = SerializerMethodField()
    url = CharField(required=False, source='versioned_object_url')
    version_created_on = DateTimeField(source='created_at', read_only=True)
    version_created_by = DateTimeField(source='created_by.username', read_only=True)
    mappings = SerializerMethodField()

    def __init__(self, *args, **kwargs):
        params = get(kwargs, 'context.request.query_params')
        self.query_params = params.dict() if params else dict()
        self.include_indirect_mappings = self.query_params.get(INCLUDE_INVERSE_MAPPINGS_PARAM) in ['true', True]
        self.include_direct_mappings = self.query_params.get(INCLUDE_MAPPINGS_PARAM) in ['true', True]
        self.include_extras = self.query_params.get(INCLUDE_EXTRAS_PARAM) in ['true', True]

        try:
            if not self.include_extras:
                self.fields.pop('extras', None)
        except:  # pylint: disable=bare-except
            pass

        super().__init__(*args, **kwargs)

    class Meta:
        model = Concept
        fields = (
            'uuid', 'id', 'external_id', 'concept_class', 'datatype', 'url', 'retired', 'source',
            'owner', 'owner_type', 'owner_url', 'display_name', 'display_locale', 'version', 'update_comment',
            'locale', 'version_created_by', 'version_created_on', 'mappings', 'is_latest_version', 'versions_url',
            'version_url', 'extras',
        )

    @staticmethod
    def get_locale(obj):
        return obj.iso_639_1_locale

    def get_mappings(self, obj):
        from core.mappings.serializers import MappingDetailSerializer
        context = get(self, 'context')
        if self.include_direct_mappings:
            return MappingDetailSerializer(obj.get_unidirectional_mappings(), many=True, context=context).data
        if self.include_indirect_mappings:
            return MappingDetailSerializer(obj.get_bidirectional_mappings(), many=True, context=context).data

        return []
Beispiel #17
0
class ConceptVersionDetailSerializer(ModelSerializer):
    type = CharField(source='resource_type')
    uuid = CharField(source='id')
    id = CharField(source='mnemonic')
    names = LocalizedNameSerializer(many=True)
    descriptions = LocalizedDescriptionSerializer(many=True, required=False, allow_null=True)
    source = CharField(source='parent_resource')
    source_url = URLField(source='parent_url')
    owner = CharField(source='owner_name')
    created_on = DateTimeField(source='created_at', read_only=True)
    updated_on = DateTimeField(source='updated_at', read_only=True)
    version_created_on = DateTimeField(source='created_at')
    version_created_by = CharField(source='created_by')
    locale = CharField(source='iso_639_1_locale')
    mappings = SerializerMethodField()
    url = CharField(source='versioned_object_url', read_only=True)
    previous_version_url = CharField(source='prev_version_uri', read_only=True)
    update_comment = CharField(source='comment', required=False, allow_null=True, allow_blank=True)

    def __init__(self, *args, **kwargs):
        params = get(kwargs, 'context.request.query_params')

        self.include_indirect_mappings = False
        self.include_direct_mappings = False
        self.query_params = params.dict() if params else dict()
        self.include_indirect_mappings = self.query_params.get(INCLUDE_INVERSE_MAPPINGS_PARAM) == 'true'
        self.include_direct_mappings = self.query_params.get(INCLUDE_MAPPINGS_PARAM) == 'true'

        super().__init__(*args, **kwargs)

    class Meta:
        model = Concept
        fields = (
            'type', 'uuid', 'id', 'external_id', 'concept_class', 'datatype', 'display_name', 'display_locale',
            'names', 'descriptions', 'extras', 'retired', 'source', 'source_url', 'owner', 'owner_name', 'owner_url',
            'version', 'created_on', 'updated_on', 'version_created_on', 'version_created_by', 'update_comment',
            'is_latest_version', 'locale', 'url', 'owner_type', 'version_url', 'mappings', 'previous_version_url'
        )

    def get_mappings(self, obj):
        from core.mappings.serializers import MappingDetailSerializer
        context = get(self, 'context')
        if self.include_direct_mappings:
            return MappingDetailSerializer(obj.get_unidirectional_mappings(), many=True, context=context).data
        if self.include_indirect_mappings:
            return MappingDetailSerializer(obj.get_bidirectional_mappings(), many=True, context=context).data

        return []
class SubmissionSerializer(serializers.ModelSerializer):
    """ Submission Serializer. """

    # Django Rest Framework v3 uses the Django setting `DATETIME_FORMAT`
    # when serializing datetimes.  This differs from v2, which always
    # returned a datetime.  To preserve the old behavior, we explicitly
    # set `format` to None.
    # http://www.django-rest-framework.org/api-guide/fields/#datetimefield
    submitted_at = DateTimeField(format=None, required=False)
    created_at = DateTimeField(format=None, required=False)

    # Django Rest Framework v3 apparently no longer validates that
    # `PositiveIntegerField`s are positive!
    attempt_number = IntegerField(min_value=0)

    # Prevent Django Rest Framework from converting the answer (dict or str)
    # to a string.
    answer = RawField()

    team_submission_uuid = serializers.SlugRelatedField(
        slug_field='uuid',
        source='team_submission',
        queryset=TeamSubmission.objects.all(),
        allow_null=True,
        required=False,
    )

    def validate_answer(self, value):
        """
        Check that the answer is JSON-serializable and not too long.
        """
        # Check that the answer is JSON-serializable
        try:
            serialized = json.dumps(value)
        except (ValueError, TypeError):
            raise serializers.ValidationError(
                "Answer value must be JSON-serializable")

        # Check the length of the serialized representation
        if len(serialized) > Submission.MAXSIZE:
            raise serializers.ValidationError("Maximum answer size exceeded.")

        return value

    class Meta:
        model = Submission
        fields = ('uuid', 'student_item', 'attempt_number', 'submitted_at',
                  'created_at', 'answer', 'team_submission_uuid')
Beispiel #19
0
class DateTimeRangeField(serializers.Field):
    child = DateTimeField()

    default_error_messages = {
        'list': _('Must be a list'),
        'length': _('Must be a list with one or two values'),
        'required': _('Must pass start value'),
    }

    def to_representation(self, value):
        return [
            self.child.to_representation(value.lower),
            self.child.to_representation(value.upper),
        ]

    def to_internal_value(self, data):
        if not isinstance(data, list):
            self.fail('list')
        if not 0 < len(data) <= 2:
            self.fail('length')
        lower = data[0]
        upper = data[1] if len(data) > 1 else None
        lower = self.child.to_internal_value(lower) if lower else None
        upper = self.child.to_internal_value(upper) if upper else None
        if not lower:
            self.fail('required')
        upper = lower + timedelta(minutes=30) if not upper else upper
        return CustomDateTimeTZRange(lower, upper)
Beispiel #20
0
class OutpostHealthSerializer(PassiveSerializer):
    """Outpost health status"""

    last_seen = DateTimeField(read_only=True)
    version = CharField(read_only=True)
    version_should = CharField(read_only=True)
    version_outdated = BooleanField(read_only=True)
Beispiel #21
0
class MappingListSerializer(ModelSerializer):
    id = CharField(source='mnemonic', required=False)
    uuid = CharField(source='id', read_only=True)
    source = CharField(source='parent_resource', read_only=True)
    owner = CharField(source='owner_name', read_only=True)
    update_comment = CharField(source='comment', required=False, allow_null=True, allow_blank=True)
    url = CharField(required=False, source='versioned_object_url')
    version = CharField(read_only=True)
    version_created_on = DateTimeField(source='created_at', read_only=True)
    from_concept = ConceptListSerializer()
    to_concept = ConceptListSerializer()
    from_source = SourceListSerializer()
    to_source = SourceListSerializer()
    from_concept_name_resolved = CharField(source='from_concept.display_name', read_only=True)
    to_concept_name_resolved = CharField(source='to_concept.display_name', read_only=True)

    class Meta:
        model = Mapping
        fields = (
            'external_id', 'retired', 'map_type', 'source', 'owner', 'owner_type',
            'from_concept_code', 'from_concept_name', 'from_concept_url',
            'to_concept_code', 'to_concept_name', 'to_concept_url',
            'from_source_owner', 'from_source_owner_type', 'from_source_url', 'from_source_name',
            'to_source_owner', 'to_source_owner_type', 'to_source_url', 'to_source_name',
            'url', 'version', 'id', 'versioned_object_id', 'versioned_object_url',
            'is_latest_version', 'update_comment', 'version_url', 'uuid', 'version_created_on',
            'from_source_version', 'to_source_version', 'from_concept', 'to_concept', 'from_source', 'to_source',
            'from_concept_name_resolved', 'to_concept_name_resolved', 'extras',
        )

    def __init__(self, *args, **kwargs):
        params = get(kwargs, 'context.request.query_params')
        self.query_params = params.dict() if params else dict()
        self.include_from_source = self.query_params.get(MAPPING_LOOKUP_FROM_SOURCE) in ['true', True]
        self.include_to_source = self.query_params.get(MAPPING_LOOKUP_TO_SOURCE) in ['true', True]
        self.include_sources = self.query_params.get(MAPPING_LOOKUP_SOURCES) in ['true', True]
        self.include_from_concept = self.query_params.get(MAPPING_LOOKUP_FROM_CONCEPT) in ['true', True]
        self.include_to_concept = self.query_params.get(MAPPING_LOOKUP_TO_CONCEPT) in ['true', True]
        self.include_concepts = self.query_params.get(MAPPING_LOOKUP_CONCEPTS) in ['true', True]

        self.include_extras = self.query_params.get(INCLUDE_EXTRAS_PARAM) in ['true', True]

        if not self.include_concepts:
            if not self.include_from_concept:
                self.fields.pop('from_concept')
            if not self.include_to_concept:
                self.fields.pop('to_concept')

        if not self.include_sources:
            if not self.include_from_source:
                self.fields.pop('from_source')
            if not self.include_to_source:
                self.fields.pop('to_source')

        if not self.include_extras and self.__class__.__name__ in [
                'MappingListSerializer', 'MappingVersionListSerializer'
        ]:
            self.fields.pop('extras', None)

        super().__init__(*args, **kwargs)
Beispiel #22
0
    def filter_queryset(self, request, queryset, view):
        fields = self._get_date_range_filter_fields(view)

        kwargs = {}
        for attr, date_range_keyword in fields.items():
            if len(date_range_keyword) != 2:
                continue
            for i, v in enumerate(date_range_keyword):
                value = request.query_params.get(v)
                if not value:
                    continue
                try:
                    field = DateTimeField()
                    value = field.to_internal_value(value)
                    if i == 0:
                        lookup = "__gte"
                    else:
                        lookup = "__lte"
                    kwargs[attr + lookup] = value
                except ValidationError as e:
                    print(e)
                    continue
        if kwargs:
            queryset = queryset.filter(**kwargs)
        return queryset
Beispiel #23
0
 def get_updated_at(self, conversation):
     participant = self._participant(conversation)
     if participant.updated_at > conversation.updated_at:
         date = participant.updated_at
     else:
         date = conversation.updated_at
     return DateTimeField().to_representation(date)
Beispiel #24
0
class MappingListSerializer(ModelSerializer):
    id = CharField(source='mnemonic', required=False)
    uuid = CharField(source='id', read_only=True)
    source = CharField(source='parent_resource', read_only=True)
    owner = CharField(source='owner_name', read_only=True)
    update_comment = CharField(source='comment', required=False)
    url = CharField(source='version_url', read_only=True)
    version = CharField(read_only=True)
    to_concept_code = SerializerMethodField()
    to_concept_name = SerializerMethodField()
    version_created_on = DateTimeField(source='created_at', read_only=True)

    class Meta:
        model = Mapping
        fields = ('external_id', 'retired', 'map_type', 'source', 'owner',
                  'owner_type', 'from_concept_code', 'from_concept_name',
                  'from_concept_url', 'to_concept_code', 'to_concept_name',
                  'to_concept_url', 'from_source_owner',
                  'from_source_owner_type', 'from_source_url',
                  'from_source_name', 'to_source_owner',
                  'to_source_owner_type', 'to_source_url', 'to_source_name',
                  'url', 'version', 'id', 'versioned_object_id',
                  'versioned_object_url', 'is_latest_version',
                  'update_comment', 'version_url', 'uuid',
                  'version_created_on')

    @staticmethod
    def get_to_concept_code(obj):
        return obj.get_to_concept_code()

    @staticmethod
    def get_to_concept_name(obj):
        return obj.get_to_concept_name()
Beispiel #25
0
class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = '__all__'

    created_by = serializers.ReadOnlyField(source='created_by.username')
    creation_date = DateTimeField(format='%d-%m-%Y %H:%M:%S', read_only=True)
Beispiel #26
0
class BlacklistSerializer(ModelSerializer):
    date = DateTimeField(read_only=True)
    added_by = ReadOnlyField(source='added_by.username')

    class Meta:
        model = BlacklistedUser
        fields = ('uid', 'username', 'date', 'added_by')
Beispiel #27
0
class ScoreSerializer(serializers.ModelSerializer):

    # Ensure that the created_at datetime is not converted to a string.
    created_at = DateTimeField(format=None, required=False)
    annotations = serializers.SerializerMethodField()

    def get_annotations(self, obj):
        """
        Inspect ScoreAnnotations to attach all relevant annotations.
        """
        annotations = ScoreAnnotation.objects.filter(score_id=obj.id)
        return [
            ScoreAnnotationSerializer(instance=annotation).data
            for annotation in annotations
        ]

    class Meta:
        model = Score
        fields = (
            'student_item',
            'submission',
            'points_earned',
            'points_possible',
            'created_at',

            # Computed
            'submission_uuid',
            'annotations',
        )
    def test_campaigns_list_serializer(self):
        queryset = models.Campaign.objects.all()
        serializer = serializers.CampaignSerializer(queryset, many=True)

        # Check that 5 campaigns was serialized
        self.assertEqual(len(serializer.data), 5)

        campaigns_data_list = []
        for campaign in self.campaigns:

            # to comply with djangorestframework datetime formatting
            date_time_object = DateTimeField()
            created = DateTimeField.to_representation(date_time_object, campaign.created)

            campaign_dict = OrderedDict(
                [
                    ('id', campaign.id), ('key', campaign.key), ('description', campaign.description),
                    ('is_active', campaign.is_active), ('created', created)
                ]
                                        )
            campaigns_data_list.append(campaign_dict)

        self.assertListEqual(serializer.data, campaigns_data_list)

        campaign_description = serializer.data[0]['description']

        # Check correct initial data
        self.assertEqual(campaign_description, "some some")
 def filter_queryset(self, request, queryset, view):
     if not hasattr(view, 'date_range_filter_fields'):
         return queryset
     try:
         fields = dict(view.date_range_filter_fields)
     except ValueError:
         msg = "View {} datetime_filter_fields set is error".format(
             view.name)
         logging.error(msg)
         return queryset
     kwargs = {}
     for attr, date_range_keyword in fields.items():
         if len(date_range_keyword) != 2:
             continue
         for i, v in enumerate(date_range_keyword):
             value = request.query_params.get(v)
             if not value:
                 continue
             try:
                 field = DateTimeField()
                 value = field.to_internal_value(value)
                 if i == 0:
                     lookup = "__gte"
                 else:
                     lookup = "__lte"
                 kwargs[attr + lookup] = value
             except ValidationError as e:
                 print(e)
                 continue
     if kwargs:
         queryset = queryset.filter(**kwargs)
     return queryset
Beispiel #30
0
class RawTextBaseSerizlizer(Serializer):
    id = IntegerField()
    created_at = DateTimeField()
    slug = SerializerMethodField()

    def get_slug(self, instance: RawText):
        return instance.raw_content[:42] + '...'