Ejemplo n.º 1
0
class StaffAbsenceSerializer(StaffUserDecisionBySerializer):
    user = StaffByUserSerializer('user', required=False)
    decision_by = StaffByUserSerializer('decision_by', required=False, allow_null=True)
    start_date = DateField(required=False, allow_null=True)
    end_date = DateField(required=False, allow_null=True)

    class Meta:
        model = Absence
        fields = FIELDS
Ejemplo n.º 2
0
    def get_queryset(self):
        item_id = self.kwargs.get(self.lookup_field)
        first_day = timezone.now().replace(day=1).date()
        start = DateField().to_internal_value(
            self.request.query_params.get('start')) or first_day

        end = DateField().to_internal_value(
            self.request.query_params.get('end')) or (first_day +
                                                      timedelta(days=31))
        return EventClass.objects.get(id=item_id).get_calendar(start,
                                                               end).values()
Ejemplo n.º 3
0
    def get_queryset(self):
        first_day = timezone.now().replace(day=1).date()
        start = DateField().to_internal_value(
            self.request.query_params.get('start').split('T')[0]
        ) or first_day

        end = DateField().to_internal_value(
            self.request.query_params.get('end').split('T')[0]
        ) or (first_day + timedelta(days=31))

        events = []
        for ec in EventClass.objects.in_range(start, end):
            events.extend(list(ec.get_calendar(start, end).values()))

        return events
Ejemplo n.º 4
0
    def get(self, request: Request):
        user = self.request.user
        theses_ready_for_review = Thesis.objects.filter(
            Q(supervisor=user) | Q(opponent=user),
            state=Thesis.State.READY_FOR_REVIEW,
        ).exclude(review_thesis__user=user)

        reservations_ready_for_prepare = ()
        if self.request.user.has_perm('thesis.change_reservation'):
            reservations_ready_for_prepare = Reservation.objects.filter(
                state=Reservation.State.CREATED, )

        theses_just_submitted = ()
        if self.request.user.has_perm('thesis.change_thesis'):
            theses_just_submitted = Thesis.objects.filter(
                state=Thesis.State.SUBMITTED, )

        author_theses = Thesis.objects.filter(authors=user, )
        author_theses_serializer: ListSerializer = ThesisBaseSerializer(
            many=True, instance=author_theses)
        # dynamically add submit_deadline to standard thesis serializer
        author_theses_serializer.child.fields['submit_deadline'] = DateField()

        return Response(data=dict(
            theses_ready_for_review=ThesisBaseSerializer(
                many=True, instance=theses_ready_for_review).data,
            reservations_ready_for_prepare=ReservationSerializer(
                many=True, instance=reservations_ready_for_prepare).data,
            theses_just_submitted=ThesisBaseSerializer(
                many=True, instance=theses_just_submitted).data,
            author_theses=author_theses_serializer.data,
        ))
Ejemplo n.º 5
0
class BlogPage(Page):
    published_date = models.DateField("Post date")
    intro = models.CharField(max_length=250)
    body = RichTextField(blank=True)

    search_fields = Page.search_fields + [
        index.SearchField('intro'),
        index.SearchField('body'),
    ]

    content_panels = Page.content_panels + [
        FieldPanel('published_date'),
        FieldPanel('intro'),
        FieldPanel('body', classname="full"),
    ]

    # Export fields over the API
    api_fields = [
        APIField('published_date'),  # Date in ISO8601 format (the default)
        APIField(
            'published_date_display',
            serializer=DateField(format='%A $d %B %Y', source='published_date')
        ),  # A separate published_date_display field with a different format
        APIField('body'),
        APIField(
            'authors'
        ),  # This will nest the relevant BlogPageAuthor objects in the API response
    ]
class DailyProductivityLogCreateUpdateSerializer(
    BaseCreateUpdateSerializer, ModelValidatorsMixin
):
    # allow an regular isoformat of milliseconds also be passed
    date = DateField(input_formats=["iso-8601"])
    source = ChoiceField(choices=BETTERSELF_LOG_INPUT_SOURCES, default=WEB_INPUT_SOURCE)
    mistakes = CharField(trim_whitespace=True, default="", allow_blank=True)

    class Meta:
        model = DailyProductivityLog
        fields = (
            "source",
            "date",
            "very_productive_time_minutes",
            "productive_time_minutes",
            "neutral_time_minutes",
            "distracting_time_minutes",
            "very_distracting_time_minutes",
            "pomodoro_count",
            "notes",
            "mistakes",
            "user",
        )

    def validate(self, validated_data):
        user = self.context["request"].user
        is_creating_instance = not self.instance

        if is_creating_instance:
            if self.Meta.model.objects.filter(
                user=user, date=validated_data["date"],
            ).exists():
                raise ValidationError(f"Fields user and date need to be unique!")

        return validated_data
Ejemplo n.º 7
0
class GameResultsSerializer(ModelSerializer):
    date = DateField(format="%Y/%m/%d")

    def create(self, validated_data):
        game_result = super(GameResultsSerializer, self).create(validated_data)
        token = Token.objects.create(game_result=game_result)
        send_game_results_email(player=validated_data['player'],
                                scores={
                                    'stage1Score':
                                    validated_data['stage1Score'],
                                    'stage2Score':
                                    validated_data['stage2Score'],
                                    'stage3Score':
                                    validated_data['stage3Score'],
                                    'stage4Score':
                                    validated_data['stage4Score'],
                                },
                                host=self.context['request'].get_host(),
                                game_result=game_result,
                                token=token)
        if self.context['request'].GET.get('push') == 'true':
            push_players()
        return game_result

    class Meta:
        model = GameResult
        list_serializer_class = FilteredGameResultsSerializer
        fields = '__all__'
Ejemplo n.º 8
0
class NewsLinkSerializer(Serializer):
    id = IntegerField(read_only=True)
    title = CharField(max_length=63)
    slug = SlugField(max_length=63)
    pub_date = DateField()
    link = URLField(max_length=255)
    startup = StartupSerializer()
Ejemplo n.º 9
0
def format_date_or_datetime(value):
    """
    Formats a date or datetime using DRF fields.

    This is for use in tests when comparing dates and datetimes with JSON-formatted values.
    """
    if isinstance(value, datetime):
        return DateTimeField().to_representation(value)
    return DateField().to_representation(value)
Ejemplo n.º 10
0
class StartupSerializer(Serializer):
    id = IntegerField(read_only=True)
    name = CharField(max_length=31)
    slug = SlugField(max_length=31)
    description = CharField()
    founded_date = DateField()
    contact = EmailField()
    website = URLField(max_length=255)
    tags = TagSerializer(many=True)
Ejemplo n.º 11
0
 def test_to_native_with_item_field(self):
     """
     When a ListField has an item-field, to_native should return a list of elements resulting
     from the application of the item-field's to_native method to each element of the input
     object list.
     """
     field = ListField(DateField(format=ISO_8601))
     obj = [date(2000, 1, 1), date(2000, 1, 2)]
     data = field.to_native(obj)
     self.assertEqual(["2000-01-01", "2000-01-02"], data)
Ejemplo n.º 12
0
 def test_from_native_with_item_field(self):
     """
     When a ListField has an item-field, from_native should return a list of elements resulting
     from the application of the item-field's from_native method to each element of the input
     data list.
     """
     field = ListField(DateField())
     data = ["2000-01-01", "2000-01-02"]
     obj = field.from_native(data)
     self.assertEqual([date(2000, 1, 1), date(2000, 1, 2)], obj)
Ejemplo n.º 13
0
 def test_to_native_with_value_field(self):
     """
     When a DictField has an value-field, to_native should return a dict of elements resulting
     from the application of the value-field's to_native method to each value of the input
     object dict.
     """
     field = DictField(DateField(format=ISO_8601))
     obj = {"a": date(2000, 1, 1), "b": date(2000, 1, 2)}
     data = field.to_native(obj)
     self.assertEqual({"a": "2000-01-01", "b": "2000-01-02"}, data)
Ejemplo n.º 14
0
 def test_from_native_with_value_field(self):
     """
     When a DictField has an value-field, from_native should return a dict of elements resulting
     from the application of the value-field's from_native method to each value of the input
     data dict.
     """
     field = DictField(DateField())
     data = {"a": "2000-01-01", "b": "2000-01-02"}
     obj = field.from_native(data)
     self.assertEqual({"a": date(2000, 1, 1), "b": date(2000, 1, 2)}, obj)
Ejemplo n.º 15
0
class ArticlesSerializer(serializers.ModelSerializer):
    title = CharField(validators=[required])
    excerpt = CharField(validators=[required])
    text = CharField(validators=[required])
    date_created = DateField(validators=[required])
    date_updated = DateField(validators=[required])
    writer = WritersSerializer(validators=[required])

    def create(self, validated_data):
        writer_data = validated_data.pop('writer')
        article = Articles.objects.create(**validated_data,
                                          writer=Writers.objects.create(
                                              **writer_data))
        return article

    class Meta:
        model = Articles
        fields = ('id', 'title', 'excerpt', 'text', 'date_created',
                  'date_updated', 'writer')
Ejemplo n.º 16
0
class BillSerializer(Serializer):
    '''
    Serializes a `CompletedCall` queryset into as a bill.
    '''
    calls = BillCompletedCallSerializer(many=True)
    total = SerializerMethodField()
    period = DateField(format=PERIOD_FORMAT)
    source = RegexField(PHONE_REGEX)

    def get_total(self, obj):
        if obj['calls']:
            return sum(call.price for call in obj['calls'])
Ejemplo n.º 17
0
class AggregrateViewParamsSerializer(Serializer):
    start_date = DateField()
    end_date = DateField()
    supplement_uuids = ListField(
        child=UUIDField(validators=[generic_model_uuid_validator(Supplement)]),
        required=False,
    )
    activity_uuids = ListField(
        child=UUIDField(validators=[generic_model_uuid_validator(Activity)]),
        required=False,
    )
    food_uuids = ListField(
        child=UUIDField(validators=[generic_model_uuid_validator(Food)]), required=False
    )

    class Meta:
        fields = (
            "start_date",
            "end_date",
            "supplement_uuids",
            "activity_uuids",
            "food_uuids",
        )
Ejemplo n.º 18
0
class ThesisFullPublicSerializer(ThesisBaseSerializer):
    category = CategorySerializer(read_only=True)
    category_id = PrimaryKeyRelatedField(
        write_only=True, source='category', allow_null=True, required=False,
        queryset=Category.objects.all(),
    )
    published_at = DateField(format="%Y/%m", required=False, read_only=True)
    reservable = BooleanField(read_only=True, source='_reservable')  # set by queryset from viewset

    submit_deadline = DateField(required=False, allow_null=True)

    class Meta:
        model = Thesis
        fields = ThesisBaseSerializer.Meta.fields + (
            'registration_number',
            'published_at',
            'category',
            'category_id',

            'available_for_reservation',
            'reservable',
            'open_reservations_count',
            'submit_deadline',
        )
Ejemplo n.º 19
0
class UserSerializer(serializers.ModelSerializer):
    # images = serializers.SlugRelatedField(
    #     many=True,
    #     read_only=True,
    #     slug_field='photo'
    # )

    # images = ImageSerializer()

    # images = serializers.HyperlinkedRelatedField(many=True, view_name='api:images-detail', read_only=True)

    birth = DateField(format='%d.%m.%Y', input_formats=None)

    class Meta:
        model = User
        fields = ('id', 'name', 'surname', 'age', 'birth', 'images')
Ejemplo n.º 20
0
class BillInputSerializer(Serializer):
    '''
    Serializes and validate a `Bill` get request.
    '''
    source = RegexField(PHONE_REGEX)
    period = DateField(required=False,
                       format=PERIOD_FORMAT,
                       input_formats=[PERIOD_FORMAT],
                       default=_todays_period)

    def get_bill_data(self):
        calls_queryset = CompletedCall.objects.get_bill_queryset(
            **self.validated_data)
        serializer = BillSerializer({
            'calls': calls_queryset,
            'period': self.validated_data['period'],
            'source': self.validated_data['source']
        })
        return serializer.data
Ejemplo n.º 21
0
class BlogPage(Page):
    date = models.DateField("Post date")
    intro = models.CharField(max_length=250)
    body = RichTextField(blank=True)

    search_fields = Page.search_fields + [
        index.SearchField('intro'),
        index.SearchField('body'),
    ]

    content_panels = Page.content_panels + [
        FieldPanel('date'),
        FieldPanel('intro'),
        FieldPanel('body', classname="full"),
    ]

    api_fields = [
                  APIField('pub_date', serializer=DateField(format='%d %B %Y', source='date')),
                  APIField('body'),
                 ]
Ejemplo n.º 22
0
    class serializer_class(Serializer):
        id = IntegerField()
        date = DateField()
        headline = HighlightField()
        mediumid = IntegerField()
        medium = CharField()
        creator = CharField()
        byline = CharField()
        addressee = CharField()
        section = CharField()
        url = CharField()
        length = IntegerField()
        page = IntegerField()

        def __init__(self, *args, **kwargs):
            Serializer.__init__(self, *args, **kwargs)
            ctx = kwargs.get("context", {})
            columns = ctx.get("columns", [])
            queries = ctx.get("queries", None)

            if ctx.get('minimal'):
                for fn in list(self.fields):
                    if fn != 'id' and fn not in list(columns):
                        del self.fields[fn]

            if "hits" in columns and queries:
                for q in queries:
                    self.fields[q.label] = ScoreField()
            if "text" in columns:
                self.fields['text'] = CharField()
            if "projectid" in columns:
                self.fields['projectid'] = IntegerField()
            if "lead" in columns:
                self.fields['lead'] = HighlightField()
            if "kwic" in columns:
                self.fields['left'] = KWICField(kwic='left')
                self.fields['keyword'] = KWICField(kwic='keyword')
                self.fields['right'] = KWICField(kwic='right')
Ejemplo n.º 23
0
    class serializer_class(Serializer):
        id = IntegerField()
        date = DateField()
        headline = HighlightField()
        mediumid = IntegerField()
        medium = CharField()
        author = CharField()
        addressee = CharField()
        length = IntegerField()

        def __init__(self, *args, **kwargs):
            Serializer.__init__(self, *args, **kwargs)
            ctx = kwargs.get("context", {})
            columns = ctx.get("columns", [])
            queries = ctx.get("queries", None)

            if "hits" in columns and queries:
                for q in queries:
                    self.fields[q.label] = ScoreField()
            if "text" in columns:
                self.fields['text'] = CharField()
            if "lead" in columns:
                self.fields['lead'] = HighlightField()
Ejemplo n.º 24
0
class ProfileQuerySerializer(Serializer):
    """GET Profiles list query serializer."""

    orderable_fields = ('full_name', 'date_created', 'rating', 'location')
    default_ordering = '-rating'

    order_by = CharField(default=default_ordering)
    full_name = CharField(required=False)
    registered_before = DateField(required=False)
    min_rating = IntegerField(required=False)
    online = BooleanField(required=False, allow_null=True, default=None)

    def validate_order_by(self, order_by):
        if not order_by.removeprefix('-') in self.orderable_fields:
            return self.default_ordering
        return order_by

    def to_representation(self, validated_data):
        filters = {}
        if full_name := validated_data.get('full_name'):
            filters['full_name__icontains'] = full_name
        if registered_before := validated_data.get('registered_before'):
            filters['date_created__lt'] = registered_before
Ejemplo n.º 25
0
class DateRangeField(RangeField):
    child = DateField()
    range_type = DateRange
Ejemplo n.º 26
0
def parse_date(value):
    """Parses a date from a string."""
    return _parse_value(value, DateField())
Ejemplo n.º 27
0
class SubscriptionSerializer(serializers.Serializer):
    cardHolderName = CharField(min_length=4, max_length=40, required=True)
    cardNumber = CharField(min_length=16, max_length=40, required=True)
    expiry = DateField(required=True)
    cvc = CharField(max_length=4, required=True)
Ejemplo n.º 28
0
 def list_archive_dates(self, request, *args, **kwargs):
     dates = Post.objects.dates('created_time', 'month', order='DESC')
     date_field = DateField()
     data = [date_field.to_representation(date) for date in dates]
     return Response(data=data, status=status.HTTP_200_OK)
Ejemplo n.º 29
0
class MetadataSerializer(Serializer):
    sam_load_date = DateField()
    fpds_load_date = DateField()
Ejemplo n.º 30
0
     # CharField, TextField
     CharField(allow_blank=False),
     {
         'type': 'string'
     },
 ),
 (
     # CharField, TextField
     CharField(trim_whitespace=False),
     {
         'type': 'string'
     },
 ),
 (
     # DateField
     DateField(),
     {
         'type': 'string',
         'format': 'date'
     },
 ),
 (
     # DateTimeField
     DateTimeField(),
     {
         'type': 'string',
         'format': 'date-time'
     },
 ),
 (
     # DecimalField