Exemple #1
0
class FarmImageSerializer(serializers.ModelSerializer):
    image = Base64ImageField()
    id = serializers.IntegerField(required=False)

    class Meta:
        model = FarmImage
        fields = ('image', 'label', 'copyright', 'id')
class ProfileSerializer(serializers.ModelSerializer):
    picture = Base64ImageField(required=False, max_length=None, use_url=True)

    class Meta:
        model = models.Profile
        fields = '__all__'
        read_only_fields = ['id', 'owner']
Exemple #3
0
class PublicCanteenSerializer(serializers.ModelSerializer):

    sectors = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    diagnostics = PublicDiagnosticSerializer(many=True,
                                             read_only=True,
                                             source="diagnostic_set")
    logo = Base64ImageField(required=False, allow_null=True)
    images = MediaListSerializer(child=CanteenImageSerializer(),
                                 read_only=True)

    class Meta:
        model = Canteen
        fields = (
            "id",
            "name",
            "diagnostics",
            "city",
            "city_insee_code",
            "postal_code",
            "sectors",
            "daily_meal_count",
            "region",
            "department",
            "logo",
            "images",
            "publication_comments",
            "quality_comments",
            "waste_comments",
            "diversification_comments",
            "plastics_comments",
            "information_comments",
        )
Exemple #4
0
class FarmerBriefsFastSerializer(serializers.Serializer):
    """
    Serializer to be used in retrieval actions. By bypassing
    the overhead of the ModelSerializer it is significantly
    faster : https://hakibenita.com/django-rest-framework-slow
    """
    id = serializers.UUIDField(read_only=True)
    sequence_number = serializers.IntegerField(read_only=True)
    external_id = serializers.CharField(read_only=True)
    approved = serializers.BooleanField()
    name = serializers.CharField()
    farm_name = serializers.CharField()
    production = serializers.ListField()
    groups = serializers.ListField()
    agriculture_types = serializers.ListField()
    profile_image = Base64ImageField()
    experiments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    lat = serializers.DecimalField(max_digits=9, decimal_places=6)
    lon = serializers.DecimalField(max_digits=9, decimal_places=6)
    cultures = serializers.CharField()
    surface = serializers.CharField()
    surface_cultures = serializers.CharField()
    surface_meadows = serializers.CharField()
    output = serializers.CharField()
    url_slug = serializers.CharField(read_only=True)
Exemple #5
0
class ProductSerializer(serializers.ModelSerializer):
    photo1 = Base64ImageField()
    photo2 = Base64ImageField()
    photo3 = Base64ImageField()
    photo4 = Base64ImageField()

    category = serializers.SlugRelatedField(read_only=False,
                                            queryset=Category.objects.all(),
                                            slug_field="name")
    added_by = serializers.PrimaryKeyRelatedField(
        read_only=False,
        queryset=User.objects.all(),
        default=serializers.CurrentUserDefault())

    class Meta:
        model = Product
        fields = '__all__'
Exemple #6
0
class CanteenImageSerializer(serializers.ModelSerializer):
    image = Base64ImageField()
    id = serializers.IntegerField(required=False)

    class Meta:
        model = CanteenImage
        fields = (
            "id",
            "image",
        )
Exemple #7
0
class ExperimentImageFastSerializer(serializers.Serializer):
    """
    Serializer to be used in retrieval actions. By bypassing
    the overhead of the ModelSerializer it is significantly
    faster : https://hakibenita.com/django-rest-framework-slow
    """
    image = Base64ImageField()
    id = serializers.IntegerField(required=False)
    label = serializers.CharField()
    copyright = serializers.CharField()
Exemple #8
0
class BlogPostAuthor(serializers.ModelSerializer):

    avatar = Base64ImageField(required=False, allow_null=True)

    class Meta:
        model = get_user_model()
        fields = (
            "first_name",
            "last_name",
            "avatar",
        )
class UserDetailSerializer(serializers.ModelSerializer):
    """
    User model w/o password
    """

    avatar = Base64ImageField(required=False)

    class Meta:
        model = UserModel
        fields = ('pk', 'username', 'email', 'avatar', 'first_name',
                  'last_name')
        read_only_fields = ('email', )
Exemple #10
0
class UserSerializer(serializers.ModelSerializer):
    profile_img = Base64ImageField(max_length=None,
                                   use_url=True,
                                   required=False,
                                   allow_null=True,
                                   allow_empty_file=True)

    class Meta:
        model = User
        fields = ('__all__')
        extra_kwargs = {
            'password': {
                'write_only': True,
                'style': {
                    'input_type': 'password'
                },
            },
        }

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)

        return user

    def update(self, instance, validated_data):
        print("User instance", instance)
        print("User validated_data", validated_data)
        if 'password' in validated_data:
            instance.set_password(validated_data['password'])
            del validated_data['password']
        for key in validated_data.keys():
            # print("User validated_data key", key)
            # print("User validated_data value", validated_data[key])
            if key in instance.__dict__.keys():
                setattr(instance, key, validated_data[key])

        instance.save()
        return instance

    def validate(self, data):
        print('validate User data', data)
        if 'password' in data:
            try:
                validate_password(data['password'])
            except ValidationError as error:
                print('The password does not meet the minimum requirements')
                raise serializers.ValidationError(
                    password_validators_help_texts())

        return data
class PichangaSerializer(serializers.ModelSerializer):
    pictures = ImageUrlField(many=True, read_only=True)
    members = MemberSerializer(many=True, read_only=True)
    sport = SportSerializer()
    logo = Base64ImageField(required=False, max_length=None, use_url=True)

    class Meta:
        model = models.Pichanga
        fields = '__all__'

    def create(self, validated_data):
        sport = models.Sport.objects.get(name=validated_data['sport']['name'])
        validated_data['sport'] = sport
        return super().create(validated_data)
Exemple #12
0
class ExpenseSerializer(serializers.ModelSerializer):

    created_by = UsernameSerializer(read_only=True)
    type = PrimaryKeyField(model=ExpenseType,
                           queryset=ExpenseType.objects.all(),
                           serializer=ExpenseTypeSerializer)
    parlor = PrimaryKeyField(model=Parlor,
                             queryset=Parlor.objects.all(),
                             serializer=ParlorSerializer)
    image = Base64ImageField(
        required=False,
        allow_null=True,
    )
    amount = MoneyField(max_digits=14,
                        decimal_places=2,
                        default_currency=settings.DEFAULT_CURRENCY)
    payed_amount = MoneyField(
        max_digits=14,
        decimal_places=2,
        default_currency=settings.DEFAULT_CURRENCY,
    )

    class Meta:
        model = Expense
        fields = (
            'id',
            'created_at',
            'created_by',
            'parlor',
            'type',
            'amount',
            'note',
            'image',
            'payed_amount',
        )

    def validate(self, attrs):

        if self.context['request'].method == "PATCH":
            if (payed_amount := attrs.get('payed_amount', None)) is not None:
                already_payed = Money(self.instance.payed_amount,
                                      settings.DEFAULT_CURRENCY)
                if payed_amount + already_payed > self.instance.amount:
                    raise serializers.ValidationError({
                        'payed_amount':
                        "Нельзя оплатить больше суммы платежа!"
                    })

        return attrs
class UserSerializer(serializers.ModelSerializer):
    profile_image = Base64ImageField(required=False)
    old_password = serializers.CharField(write_only=True, required=False)
    apple_id = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {'password': {'write_only': True}, 'old_password': {'write_only': True}}
        read_only_fields = ('id',)

    def validate_username(self, value):
        if User.objects.filter(username=value).count() > 0:
            raise UsernameAlreadyTaken

        if not re.match("^[A-Za-z0-9]*$", value) or len(value) > 20:
            raise InvalidUsername

        return value

    def validate_email(self, value):
        if User.objects.filter(email=value).count() > 0:
            raise EmailAlreadyTaken

        return value

    def create(self, validated_data):
        password = validated_data.pop('password')

        validated_data['allow_notification'] = True
        validated_data['allow_commercial_email'] = True
        validated_data['is_active'] = True
        # validated_data['allow_artist_email'] = True

        apple_id = validated_data.pop('apple_id', None)

        user = User.objects.create(**validated_data)
        user.set_password(password)
        user.save()

        if apple_id is not None:
            AppleAuth.objects.create(user=user, apple_id=apple_id)

        return user
Exemple #14
0
class LoggedUserSerializer(serializers.ModelSerializer):
    avatar = Base64ImageField(required=False, allow_null=True)

    class Meta:
        model = get_user_model()
        read_only_fields = (
            "id",
            "username",
            "is_staff",
        )
        fields = (
            "id",
            "email",
            "username",
            "first_name",
            "last_name",
            "avatar",
            "is_staff",
        )
Exemple #15
0
class FarmerFastSerializer(serializers.Serializer, FieldRetrievers):
    """
    Serializer to be used in retrieval actions. By bypassing
    the overhead of the ModelSerializer it is significantly
    faster : https://hakibenita.com/django-rest-framework-slow
    """
    id = serializers.UUIDField(read_only=True)
    sequence_number = serializers.IntegerField(read_only=True)
    external_id = serializers.CharField(read_only=True)
    approved = serializers.BooleanField()
    name = serializers.CharField()
    farm_name = serializers.CharField()
    production = serializers.ListField()
    groups = serializers.ListField()
    agriculture_types = serializers.ListField()
    profile_image = Base64ImageField()
    images = MediaListSerializer(child=FarmImageFastSerializer())
    postal_code = serializers.CharField()
    experiments = serializers.SerializerMethodField(read_only=True)
    lat = serializers.DecimalField(max_digits=9, decimal_places=6)
    lon = serializers.DecimalField(max_digits=9, decimal_places=6)
    installation_date = serializers.DateField()
    personnel = serializers.CharField()
    livestock_types = serializers.ListField()
    livestock_number = serializers.CharField()
    cultures = serializers.CharField()
    soil_type = serializers.CharField()
    description = serializers.CharField()
    specificities = serializers.CharField()
    contact_possible = serializers.BooleanField()
    email_for_messages_allowed = serializers.BooleanField()
    links = serializers.ListField()
    surface = serializers.CharField()
    surface_cultures = serializers.CharField()
    surface_meadows = serializers.CharField()
    output = serializers.CharField()
    onboarding_shown = get_writable_method_field(serializers.BooleanField)()
    phone_number = get_writable_method_field(serializers.CharField)()
    email = serializers.SerializerMethodField()
    url_slug = serializers.CharField(read_only=True)
Exemple #16
0
class FarmerSerializer(serializers.ModelSerializer, FieldRetrievers):
    experiments = serializers.SerializerMethodField()
    images = MediaListSerializer(required=False,
                                 child=FarmImageSerializer(required=False))
    profile_image = Base64ImageField(required=False, allow_null=True)

    onboarding_shown = get_writable_method_field(serializers.BooleanField)()
    phone_number = get_writable_method_field(serializers.CharField)()
    email = serializers.SerializerMethodField()

    class Meta:
        model = Farmer
        read_only_fields = [
            'id', 'external_id', 'experiments', 'sequence_number', 'url_slug'
        ]
        fields = ('id', 'sequence_number', 'external_id', 'approved', 'name',
                  'farm_name', 'production', 'groups', 'agriculture_types',
                  'profile_image', 'images', 'postal_code', 'experiments',
                  'lat', 'lon', 'installation_date', 'personnel',
                  'livestock_types', 'livestock_number', 'cultures',
                  'soil_type', 'description', 'specificities',
                  'contact_possible', 'email_for_messages_allowed', 'links',
                  'surface', 'surface_cultures', 'surface_meadows', 'output',
                  'onboarding_shown', 'phone_number', 'email', 'url_slug')

    def update(self, instance, validated_data):
        if 'images' not in validated_data:
            return super().update(instance, validated_data)

        image_validated_data = validated_data.pop('images', None)
        farmer = super().update(instance, validated_data)

        if image_validated_data is not None:
            farmer_image_serializer = self.fields['images']
            for item in image_validated_data:
                item['farmer'] = farmer
            farmer_image_serializer.update(farmer.images.all(),
                                           image_validated_data)

        return farmer
Exemple #17
0
class GuideWriteSerializer(GuideReadSerializer):
    guide_file = FoldFileField()
    name = serializers.CharField(required=False)
    thumbnail_file = Base64ImageField(required=False)

    @transaction.atomic
    def create(self, validated_data):
        fold = Fold.from_fold_file(validated_data['guide_file'])
        guide = Guide.objects.create(**validated_data,
                                     name=fold.title,
                                     steps=fold.steps)
        transaction.on_commit(lambda: process_guide.delay(guide.pk))
        return guide

    @transaction.atomic
    def update(self, instance, validated_data):
        if validated_data.get('guide_file') is not None:
            fold = Fold.from_fold_file(validated_data['guide_file'])
            validated_data['name'] = fold.title
            validated_data['steps'] = fold.steps
            transaction.on_commit(lambda: process_guide.delay(instance.pk))

        return super(GuideWriteSerializer,
                     self).update(instance, validated_data)
Exemple #18
0
class FarmerSerializer(serializers.ModelSerializer):
    experiments = serializers.SerializerMethodField()
    images = MediaListSerializer(required=False,
                                 child=FarmImageSerializer(required=False))
    profile_image = Base64ImageField(required=False, allow_null=True)

    onboarding_shown = get_writable_method_field(serializers.BooleanField)()
    phone_number = get_writable_method_field(serializers.CharField)()
    email = serializers.SerializerMethodField()

    def get_experiments(self, obj):
        request = self.context.get('request')
        user = request.user if request else None

        if user and hasattr(user, 'farmer') and user.farmer == obj:
            return ExperimentSerializer(obj.experiments,
                                        context=self.context,
                                        many=True).data
        return ExperimentSerializer(obj.approved_experiments,
                                    context=self.context,
                                    many=True).data

    def get_onboarding_shown(self, obj):
        return self._field_if_logged(obj, 'onboarding_shown')

    def get_phone_number(self, obj):
        return self._field_if_logged(obj, 'phone_number')

    def get_email(self, obj):
        return self._field_if_logged(obj, 'email')

    def _field_if_logged(self, obj, field_name):
        request = self.context.get('request')
        user = request.user if request else None

        if user and hasattr(user, 'farmer') and user.farmer == obj:
            return getattr(obj, field_name)
        return None

    class Meta:
        model = Farmer
        read_only_fields = [
            'id',
            'external_id',
            'experiments',
            'sequence_number',
        ]
        fields = (
            'id',
            'sequence_number',
            'external_id',
            'approved',
            'name',
            'farm_name',
            'production',
            'groups',
            'agriculture_types',
            'profile_image',
            'images',
            'postal_code',
            'experiments',
            'lat',
            'lon',
            'installation_date',
            'personnel',
            'livestock_types',
            'livestock_number',
            'cultures',
            'soil_type',
            'description',
            'specificities',
            'contact_possible',
            'email_for_messages_allowed',
            'links',
            'surface',
            'surface_cultures',
            'surface_meadows',
            'output',
            'onboarding_shown',
            'phone_number',
            'email',
        )

    def update(self, instance, validated_data):
        if 'images' not in validated_data:
            return super().update(instance, validated_data)

        image_validated_data = validated_data.pop('images', None)
        farmer = super().update(instance, validated_data)

        if image_validated_data is not None:
            farmer_image_serializer = self.fields['images']
            for item in image_validated_data:
                item['farmer'] = farmer
            farmer_image_serializer.update(farmer.images.all(),
                                           image_validated_data)

        return farmer
class RecognitionRequestSerializer(serializers.Serializer):

    picture = Base64ImageField(required=False)
    threshold = serializers.FloatField()
    boundingbox = BoundingBox()
Exemple #20
0
class UserSerializer(serializers.ModelSerializer):
    avatar = Base64ImageField(required=False, allow_null=True)
    phone_number = PhoneNumberField(
        required=False,
        allow_null=True,
        allow_blank=True,
    )
    profile = ProfileSerializer(many=True, read_only=True)
    full_name = serializers.CharField(source='get_full_name', read_only=True)
    new_password = serializers.CharField(write_only=True)
    confirm_new_password = serializers.CharField(write_only=True)

    class Meta:
        model = User
        fields = (
            'id',
            'username',
            'first_name',
            'middle_name',
            'last_name',
            'full_name',
            'is_active',
            'is_staff',
            'is_superuser',
            'banned',
            'phone_number',
            'birth_date',
            'avatar',
            'profile',
            'date_joined',
            'last_login',
            'new_password',
            'confirm_new_password',
        )
        read_only_fields = (
            'id',
            'is_active',
            'is_staff',
            'is_superuser',
            'banned',
            'profile',
            'date_joined',
            'last_login',
        )

    def validate(self, attrs):
        new_password = attrs.get('new_password', None)
        confirm_new_password = attrs.get('confirm_new_password', None)

        if new_password and confirm_new_password and new_password != confirm_new_password:
            raise serializers.ValidationError({
                "new_password":
                "******",
                "confirm_new_password":
                "******",
            })
        return attrs

    def create(self, validated_data):
        password, _p = validated_data.pop('new_password'), validated_data.pop(
            'confirm_new_password')
        validated_data['password'] = password
        return User.objects.create_user(**validated_data)
Exemple #21
0
class FullCanteenSerializer(serializers.ModelSerializer):

    sectors = serializers.PrimaryKeyRelatedField(many=True,
                                                 queryset=Sector.objects.all(),
                                                 required=False)
    diagnostics = FullDiagnosticSerializer(many=True,
                                           read_only=True,
                                           source="diagnostic_set")
    logo = Base64ImageField(required=False, allow_null=True)
    managers = CanteenManagerSerializer(many=True, read_only=True)
    manager_invitations = ManagerInvitationSerializer(
        many=True, read_only=True, source="managerinvitation_set")
    images = MediaListSerializer(child=CanteenImageSerializer(),
                                 required=False)

    class Meta:
        model = Canteen
        read_only_fields = (
            "id",
            "managers",
            "manager_invitations",
            "publication_status",
            "publication_comments",
            "quality_comments",
            "waste_comments",
            "diversification_comments",
            "plastics_comments",
            "information_comments",
        )
        fields = (
            "id",
            "name",
            "city",
            "city_insee_code",
            "postal_code",
            "sectors",
            "line_ministry",
            "daily_meal_count",
            "satellite_canteens_count",
            "siret",
            "central_producer_siret",
            "management_type",
            "production_type",
            "diagnostics",
            "department",
            "logo",
            "images",
            "managers",
            "manager_invitations",
            "publication_status",
            "publication_comments",
            "quality_comments",
            "waste_comments",
            "diversification_comments",
            "plastics_comments",
            "information_comments",
            "economic_model",
            "reservation_expe_participant",
            "vegetarian_expe_participant",
        )

    def update(self, instance, validated_data):
        if "images" not in validated_data:
            return super().update(instance, validated_data)

        image_validated_data = validated_data.pop("images", None)
        canteen = super().update(instance, validated_data)

        if image_validated_data is not None:
            canteen_image_serializer = self.fields["images"]
            for item in image_validated_data:
                item["canteen"] = canteen
            canteen_image_serializer.update(canteen.images.all(),
                                            image_validated_data)

        return canteen

    def create(self, validated_data):
        if "images" not in validated_data:
            return super().create(validated_data)

        image_validated_data = validated_data.pop("images", None)
        canteen = super().create(validated_data)

        if image_validated_data is not None:
            canteen_image_serializer = self.fields["images"]
            for item in image_validated_data:
                item["canteen"] = canteen
            canteen_image_serializer.update(canteen.images.all(),
                                            image_validated_data)

        return canteen
class RecognitionResultSerializer(serializers.Serializer):

    picture = Base64ImageField(required=False)
    similarity = serializers.FloatField(read_only=True, )
    flag = serializers.IntegerField()
Exemple #23
0
class RecordSerializer(serializers.ModelSerializer):
    status_display = serializers.CharField(source='get_status_display',
                                           read_only=True)
    parlor = PrimaryKeyField(
        serializer=ParlorSerializer,
        queryset=Parlor.objects.all(),
        model=Parlor,
    )
    created_by = PrimaryKeyField(
        serializer=ProfileSerializer,
        queryset=Profile.objects.all(),
        model=Profile,
    )
    customer = PrimaryKeyField(
        serializer=CustomerSerializer,
        queryset=Customer.objects.all(),
        model=Customer,
    )
    performer = PrimaryKeyField(
        serializer=ProfileSerializer,
        queryset=Profile.objects.all(),
        model=Profile,
    )
    type = PrimaryKeyField(
        serializer=SessionTypeSerializer,
        queryset=SessionType.objects.all(),
        model=SessionType,
    )
    sketch = Base64ImageField(required=False, allow_null=True)
    prepayments = PrepaymentSerializer(many=True, read_only=True)
    prepayment = MoneyField(write_only=True,
                            allow_null=True,
                            max_digits=14,
                            decimal_places=2,
                            default_currency=settings.DEFAULT_CURRENCY,
                            min_value=Money(
                                0, currency=settings.DEFAULT_CURRENCY))
    price = MoneyField(required=False,
                       max_digits=14,
                       decimal_places=2,
                       default_currency=settings.DEFAULT_CURRENCY,
                       min_value=Money(0, currency=settings.DEFAULT_CURRENCY))
    used_coupon = PrimaryKeyField(
        serializer=CouponSerializer,
        queryset=Coupon.objects.all(),
        model=Coupon,
        required=False,
        allow_null=True,
    )

    employee_payments = EmployeeRecordPaymentSerializer(many=True,
                                                        read_only=True)

    class Meta:
        model = Record
        fields = (
            'id',
            'status',
            'status_display',
            'status_changed',
            'created_at',
            'created_by',
            'parlor',
            'customer',
            'performer',
            'type',
            'datetime',
            'approximate_time',
            'comment',
            'sketch',
            'prepayments',
            'prepayment',
            'reason',
            'rollback_prepayment',
            'price',
            'used_coupon',
            'employee_payments',
        )
        extra_kwargs = {
            'status': {
                'required': False
            },
            'status_changed': {
                'read_only': True
            },
            'created_at': {
                'read_only': True
            },
            'rollback_prepayment': {
                'required': False
            },
            'reason': {
                'required': False
            },
        }

    def validate(self, attrs):

        if self.context['request'].method == "PATCH":
            if (status := attrs.get('status', None)) is not None:
                if status == Record.STATUS.canceled:
                    if attrs.get('reason', None) is None:
                        # Показать ошибку, если не указана причина отмены записи.
                        raise serializers.ValidationError(
                            {'reason': settings.STRINGS['REQUIRED']})
                    if attrs.get('rollback_prepayment', None) is None:
                        # Показать ошибку, если не указан тип возврата предоплаты.
                        raise serializers.ValidationError({
                            'rollback_prepayment':
                            settings.STRINGS['REQUIRED']
                        })
                elif status == Record.STATUS.in_work:
                    # Показать ошибку, если нет мастера и пытаемся начать сеанс.
                    if not self.instance.performer:
                        raise serializers.ValidationError(
                            "Перед началом сеанса выберите исполнителя!")
                elif status == Record.STATUS.finished:

                    if attrs.get('price', None) is None:
                        raise serializers.ValidationError(
                            {'price': settings.STRINGS['REQUIRED']})

            elif self.instance.status not in Record.EDIT_STATUSES:
                # Если статус записи не "Новый" и не "Ожидается" - запретить изменение данных.
                raise serializers.ValidationError(
                    f"Нельзя изменить запись в статусе: {self.instance.get_status_display()}"
                )

            if (_type := attrs.get('type', None)) is not None:
                if self.instance.performer:
                    if not self.instance.performer.session_motivations.filter(
                            session_type=_type).exists():
                        # Обнулить исполнителя, если у текущего нет мотивации за сеанс.
                        attrs['performer'] = None
class CategorySerializer(serializers.ModelSerializer):
    photo = Base64ImageField()
    class Meta:
        model = Category
        fields = ("id", "name", "photo",)
        # exclude = ("id",)
class RegisterSerializer(serializers.Serializer):

    picture = Base64ImageField(required=False)
    boundingbox = BoundingBox()
Exemple #26
0
class ImgSerializer(serializers.Serializer):
    source = Base64ImageField(required=True)
    sha256 = HashField(required=True)
    output = serializers.ChoiceField(['url', 'base64'], required=True)