Exemple #1
0
class MoviesSerializer(ModelSerializer):
    # country = SlugRelatedField(many=True, read_only=True, slug_field='title')
    country = ListSerializer(child=serializers.CharField())
    genres = ListSerializer(child=serializers.CharField())
    # actors = serializers.StringRelatedField(many=True)
    actors = ParticipantsSerializer(many=True, read_only=True)
    # director = ListSerializer(child=serializers.CharField())
    director = ParticipantsSerializer(many=True, read_only=True)

    class Meta:
        model = Movie
        fields = [
            'title', 'year', 'country', 'actors', 'director', 'genres',
            'poster', 'description', 'url'
        ]
Exemple #2
0
class UserSerializer(ModelSerializer):
    """User Serializer"""

    is_superuser = BooleanField(read_only=True)
    avatar = CharField(read_only=True)
    attributes = JSONField(validators=[is_dict], required=False)
    groups = ListSerializer(child=GroupSerializer(),
                            read_only=True,
                            source="ak_groups")
    uid = CharField(read_only=True)

    class Meta:

        model = User
        fields = [
            "pk",
            "username",
            "name",
            "is_active",
            "last_login",
            "is_superuser",
            "groups",
            "email",
            "avatar",
            "attributes",
            "uid",
        ]
Exemple #3
0
class TransactionSerializer(ModelSerializer):
    movements_specs = ListSerializer(child=MovementSpecSerializer(),
                                     source='get_movements_specs')

    class Meta:
        model = Transaction
        fields = ['pk', 'description', 'date', 'movements_specs']
        read_only_fields = ['pk']

    def create(self, validated_data):
        movements_data = validated_data.pop('get_movements_specs')
        validated_data['movements_specs'] = [
            MovementSpecSerializer().create(mov_data)
            for mov_data in movements_data
        ]
        validated_data['date_'] = validated_data.pop('date')
        return TransactionFactory()(**validated_data)

    def update(self, instance: Transaction, validated_data):
        if 'date' in validated_data:
            instance.set_date(validated_data['date'])
        if 'get_movements_specs' in validated_data:
            movements_data = validated_data.pop('get_movements_specs')
            movements = [
                MovementSpecSerializer().create(mov_data)
                for mov_data in movements_data
            ]
            instance.set_movements(movements)
        if 'description' in validated_data:
            instance.set_description(validated_data['description'])
        return instance
Exemple #4
0
class RuleSerializer(serializers.ModelSerializer):
    conditions = ConditionSerializer(many=True, required=False)
    rules = ListSerializer(child=RecursiveField(), required=False)

    class Meta:
        model = models.SegmentRule
        fields = ("type", "rules", "conditions")
Exemple #5
0
    def get(self, request, format=None):
        """
        Return a list of all users.
        """
        stock = request.query_params.get('stock')
        data_length = request.query_params.get('data-length')
        data_type = request.query_params.get('data-type')
        algorithm = request.query_params.get('algorithm')

        results = Result.objects.filter(stock=stock)

        if data_length:
            results = results.filter(data_length=int(data_length))
        if data_type:
            results = results.filter(data_type=data_type)
        if algorithm == 'svm':
            gamma = request.query_params.get('gamma')
            c = request.query_params.get('c')
            coef0 = request.query_params.get('coef0')
            kernel = request.query_params.get('kernel')
            if gamma:
                results = results.filter(algorithm__svm__gamma=float(gamma))
            if c:
                results = results.filter(algorithm__svm__c=float(c))
            if coef0:
                results = results.filter(algorithm__svm__coef0=float(coef0))
            if kernel:
                results = results.filter(algorithm__svm__kernel=kernel)
        else:
            print('not found')
            return Response(status=404)
        print('returning response')
        return Response(
            ListSerializer(results.all(), child=ResultSerializer()).data)
Exemple #6
0
class RegisterEmployeesSerializer(Serializer):
    """Serializer to register a set of user's."""

    update = None
    create = None

    members = ListSerializer(child=EmailField())
    company = PrimaryKeyRelatedField(queryset=Company.objects.all())

    def save(self, **kwargs):
        """
        Create accounts for all the user's that are registered.

        :param kwargs: Additional creation kwargs (ignored)
        :type kwargs: any

        :return: The number of send emails
        :rtype: int
        """
        group = Group.objects.get(id=Groups.employee)

        company = self.validated_data["company"]
        members = self.validated_data["members"]

        transport = MultiMailTransport({"company": company.name}, 1, company)

        seeder = (transport(*self.employ(a, company, group)) for a in members)
        return transport.finish(seeder)

    @staticmethod
    def employ(account, company, group):
        """
        Create and initialize a single employee.

        :param company: The company to employ the user for
        :type company: companies.models.Company

        :param account: The email address to create the account for
        :type account: str

        :param group: The group to assign the user to
        :type group: django.contrib.models.Group

        :return: The parameters to the transport
        :rtype: tuple
        """
        password = User.objects.make_random_password(12)
        instance = User.objects.create_user(email=account, password=password)
        receiver = instance.email

        instance.group = group
        instance.member.create(company=company)

        return receiver, {"email": receiver, "password": password}
Exemple #7
0
class RentSerializer(EnumSupportSerializerMixin,
                     FieldPermissionsSerializerMixin,
                     serializers.ModelSerializer):
    id = serializers.IntegerField(required=False)
    due_dates = RentDueDateSerializer(many=True,
                                      required=False,
                                      allow_null=True)
    fixed_initial_year_rents = FixedInitialYearRentSerializer(many=True,
                                                              required=False,
                                                              allow_null=True)
    contract_rents = ContractRentSerializer(many=True,
                                            required=False,
                                            allow_null=True)
    index_adjusted_rents = IndexAdjustedRentSerializer(many=True,
                                                       required=False,
                                                       allow_null=True,
                                                       read_only=True)
    rent_adjustments = RentAdjustmentSerializer(many=True,
                                                required=False,
                                                allow_null=True)
    payable_rents = PayableRentSerializer(many=True,
                                          required=False,
                                          allow_null=True,
                                          read_only=True)
    equalized_rents = EqualizedRentSerializer(many=True,
                                              required=False,
                                              allow_null=True,
                                              read_only=True)
    yearly_due_dates = ListSerializer(child=DayMonthField(read_only=True),
                                      source='get_due_dates_as_daymonths',
                                      read_only=True)

    class Meta:
        model = Rent
        fields = ('id', 'type', 'cycle', 'index_type', 'due_dates_type',
                  'due_dates_per_year', 'elementary_index', 'index_rounding',
                  'x_value', 'y_value', 'y_value_start',
                  'equalization_start_date', 'equalization_end_date', 'amount',
                  'note', 'due_dates', 'fixed_initial_year_rents',
                  'contract_rents', 'index_adjusted_rents', 'rent_adjustments',
                  'payable_rents', 'equalized_rents', 'start_date', 'end_date',
                  'yearly_due_dates', 'seasonal_start_day',
                  'seasonal_start_month', 'seasonal_end_day',
                  'seasonal_end_month', 'manual_ratio',
                  'manual_ratio_previous')

    def override_permission_check_field_name(self, field_name):
        if field_name == 'yearly_due_dates':
            return 'due_dates'

        return field_name
Exemple #8
0
def react_user_list(users, project, identifier):
    users = users.order_by(Lower('username'))
    user_list = ListSerializer(users, child=UserWithMailSerializer()).data

    format_strings = {
        'users': json.dumps(user_list),
        'project': project.pk,
        'listen_to': identifier,
    }

    return format_html(('<span data-euth-widget="userlist"'
                        ' data-users="{users}"'
                        ' data-project="{project}"'
                        ' data-listen-to="{listen_to}"></span>'),
                       **format_strings)
Exemple #9
0
    def __init__(self, *args, **kwargs):
        """
        Override init to add in the object serializer field on-the-fly.
        """
        super(ContextPassingPaginationSerializer,
              self).__init__(*args, **kwargs)
        results_field = self.results_field

        try:
            object_serializer = self.Meta.object_serializer_class
        except AttributeError:
            object_serializer = DefaultObjectSerializer

        self.fields[results_field] = ListSerializer(
            child=object_serializer(context=kwargs["context"]),
            source='object_list')
Exemple #10
0
    def many_init(cls, *args, **kwargs):
        """
        This method implements the creation of a `ListSerializer` parent
        class when `many=True` is used. You can customize it if you need to
        control which keyword arguments are passed to the parent, and
        which are passed to the child.

        Note that we're over-cautious in passing most arguments to both parent
        and child classes in order to try to cover the general case. If you're
        overriding this method you'll probably want something much simpler, eg:

        @classmethod
        def many_init(cls, *args, **kwargs):
            kwargs['child'] = cls()
            return CustomListSerializer(*args, **kwargs)
        """
        kwargs['child'] = BasePageSerializer(*args, **kwargs)
        return ListSerializer(*args, **kwargs)
Exemple #11
0
class GroupSerializer(ModelSerializer):
    """Group Serializer"""

    attributes = JSONField(validators=[is_dict], required=False)
    users_obj = ListSerializer(child=GroupMemberSerializer(),
                               read_only=True,
                               source="users",
                               required=False)
    parent_name = CharField(source="parent.name", read_only=True)

    class Meta:

        model = Group
        fields = [
            "pk",
            "name",
            "is_superuser",
            "parent",
            "parent_name",
            "users",
            "attributes",
            "users_obj",
        ]
Exemple #12
0
class UserSerializer(ModelSerializer):
    """User Serializer"""

    is_superuser = BooleanField(read_only=True)
    avatar = CharField(read_only=True)
    attributes = JSONField(validators=[is_dict], required=False)
    groups = PrimaryKeyRelatedField(allow_empty=True,
                                    many=True,
                                    source="ak_groups",
                                    queryset=Group.objects.all())
    groups_obj = ListSerializer(child=GroupSerializer(),
                                read_only=True,
                                source="ak_groups")
    uid = CharField(read_only=True)

    class Meta:

        model = User
        fields = [
            "pk",
            "username",
            "name",
            "is_active",
            "last_login",
            "is_superuser",
            "groups",
            "groups_obj",
            "email",
            "avatar",
            "attributes",
            "uid",
        ]
        extra_kwargs = {
            "name": {
                "allow_blank": True
            },
        }
Exemple #13
0
 def get_non_deleted(self,user):
     qs = List.objects.filter(is_deleted=False).filter(Q(owner=user)|Q(shared_with=user))
     lists = ListSerializer(instance=qs,many=True)
     return lists.data
 def make_list(self, data_list, serializer):
     list_serializer = ListSerializer(child=serializer)
     return ReturnList(data_list, serializer=list_serializer)
Exemple #15
0
class Answer(Serializer):
    """User's Choice serializer."""

    user_id = IntegerField()
    answers = ListSerializer(child=JSONField(), allow_empty=False)

    class Meta:
        fields = 'user_id', 'answers'

    def validate_user_id(self, value):
        poll = self.context['poll']
        if models.Answer.objects.filter(user_id=value, poll=poll).exists():
            raise ValidationError("You've already answered this poll.")
        return value

    def validate_answers(self, value):
        if not value:
            raise ValidationError("Please, provide some answers.")
        poll = self.context['poll']
        questions = {q.id: q for q in poll.questions.all()}
        valid_answers = []
        found_answers = set()
        for raw_answer in value:
            if not (question := questions.get(raw_answer.get('question_id'),
                                              None)):
                continue

            choice = raw_answer.get('choice')
            question_type = QType(question.q_type)

            if question_type != QType.MANY and question.id in found_answers:
                raise ValidationError(
                    f"Only single choice allowed for question id {question.id}"
                )
            found_answers.add(question.id)

            if question_type == QType.ARBITRARY:
                if not isinstance(choice, str):
                    raise ValidationError(
                        "Answer to question of this type must be a string.")
                valid_answers.append(raw_answer)
                continue

            if not isinstance(choice, int):
                raise ValidationError(
                    f"Answer to question id {question.id} must be an integer id of a choice."
                )

            try:
                existing_choice = models.Choice.objects.get(id=choice)
            except models.Choice.DoesNotExist as e:
                raise ValidationError(f"Choice id {choice} not found.") from e
            if existing_choice.question != question:
                raise ValidationError(
                    f"Choice id {choice} is for anoher question.")
            valid_answers.append(raw_answer)

        if len(found_answers) != len(questions):
            raise ValidationError(
                f"Please, provide answers to questions: {list(questions)}.")
        return valid_answers
Exemple #16
0
class BaseListSerializer(Serializer):
    data = ListSerializer(
        required=False, allow_empty=True,
        child=BaseSerializer(required=False, allow_null=True),
    )
Exemple #17
0
class UserSelfSerializer(ModelSerializer):
    """User Serializer for information a user can retrieve about themselves and
    update about themselves"""

    is_superuser = BooleanField(read_only=True)
    avatar = CharField(read_only=True)
    groups = SerializerMethodField()
    uid = CharField(read_only=True)
    settings = DictField(source="attributes.settings", default=dict)

    @extend_schema_field(
        ListSerializer(child=inline_serializer(
            "UserSelfGroups",
            {
                "name": CharField(read_only=True),
                "pk": CharField(read_only=True)
            },
        )))
    def get_groups(self, _: User):
        """Return only the group names a user is member of"""
        for group in self.instance.ak_groups.all():
            yield {
                "name": group.name,
                "pk": group.pk,
            }

    def validate_email(self, email: str):
        """Check if the user is allowed to change their email"""
        if self.instance.group_attributes().get(
                USER_ATTRIBUTE_CHANGE_EMAIL,
                CONFIG.y_bool("default_user_change_email", True)):
            return email
        if email != self.instance.email:
            raise ValidationError("Not allowed to change email.")
        return email

    def validate_name(self, name: str):
        """Check if the user is allowed to change their name"""
        if self.instance.group_attributes().get(
                USER_ATTRIBUTE_CHANGE_NAME,
                CONFIG.y_bool("default_user_change_name", True)):
            return name
        if name != self.instance.name:
            raise ValidationError("Not allowed to change name.")
        return name

    def validate_username(self, username: str):
        """Check if the user is allowed to change their username"""
        if self.instance.group_attributes().get(
                USER_ATTRIBUTE_CHANGE_USERNAME,
                CONFIG.y_bool("default_user_change_username", True)):
            return username
        if username != self.instance.username:
            raise ValidationError("Not allowed to change username.")
        return username

    def save(self, **kwargs):
        if self.instance:
            attributes: dict = self.instance.attributes
            attributes.update(self.validated_data.get("attributes", {}))
            self.validated_data["attributes"] = attributes
        return super().save(**kwargs)

    class Meta:

        model = User
        fields = [
            "pk",
            "username",
            "name",
            "is_active",
            "is_superuser",
            "groups",
            "email",
            "avatar",
            "uid",
            "settings",
        ]
        extra_kwargs = {
            "is_active": {
                "read_only": True
            },
            "name": {
                "allow_blank": True
            },
        }
Exemple #18
0
class RentSerializer(
        EnumSupportSerializerMixin,
        FieldPermissionsSerializerMixin,
        serializers.ModelSerializer,
):
    id = serializers.IntegerField(required=False)
    due_dates = RentDueDateSerializer(many=True,
                                      required=False,
                                      allow_null=True)
    fixed_initial_year_rents = FixedInitialYearRentSerializer(many=True,
                                                              required=False,
                                                              allow_null=True)
    contract_rents = ContractRentSerializer(many=True,
                                            required=False,
                                            allow_null=True)
    index_adjusted_rents = IndexAdjustedRentSerializer(many=True,
                                                       required=False,
                                                       allow_null=True,
                                                       read_only=True)
    rent_adjustments = RentAdjustmentSerializer(many=True,
                                                required=False,
                                                allow_null=True)
    payable_rents = PayableRentSerializer(many=True,
                                          required=False,
                                          allow_null=True,
                                          read_only=True)
    equalized_rents = EqualizedRentSerializer(many=True,
                                              required=False,
                                              allow_null=True,
                                              read_only=True)
    yearly_due_dates = ListSerializer(
        child=DayMonthField(read_only=True),
        source="get_due_dates_as_daymonths",
        read_only=True,
    )

    class Meta:
        model = Rent
        fields = (
            "id",
            "type",
            "cycle",
            "index_type",
            "due_dates_type",
            "due_dates_per_year",
            "elementary_index",
            "index_rounding",
            "x_value",
            "y_value",
            "y_value_start",
            "equalization_start_date",
            "equalization_end_date",
            "amount",
            "note",
            "due_dates",
            "fixed_initial_year_rents",
            "contract_rents",
            "index_adjusted_rents",
            "rent_adjustments",
            "payable_rents",
            "equalized_rents",
            "start_date",
            "end_date",
            "yearly_due_dates",
            "seasonal_start_day",
            "seasonal_start_month",
            "seasonal_end_day",
            "seasonal_end_month",
            "manual_ratio",
            "manual_ratio_previous",
        )

    def override_permission_check_field_name(self, field_name):
        if field_name == "yearly_due_dates":
            return "due_dates"

        return field_name
Exemple #19
0
 def many_init(cls, *args, **kwargs):
     kwargs['child'] = PageSerializer(*args, **kwargs)
     return ListSerializer(*args, **kwargs)