class ChangePasswordSerializer(serializers.Serializer):
    """
    Serializer for password change endpoint.
    """
    old_password = serializers.CharField(required=True)
    new_password = serializers.CharField(required=True)
Beispiel #2
0
class UserSerializer(serializers.ModelSerializer):
    movie = MovieMainSerializer( many=True, required=False)
    username = serializers.CharField(
       # 이런식으로 기존의 validator가져다가 쓸 수 도 있다.
       # 여기서 이렇게 지정시 알아서 어떤 애러이고 왜 일어났는지 error에 같이 보내준다.
       validators=[UniqueValidator(queryset=User.objects.all())]
    )

    password = serializers.CharField()
    password2 = serializers.CharField()
    email = serializers.EmailField(
        required=True,
        validators=[UniqueValidator(queryset=User.objects.all())]
    )

    class Meta:
        model = User
        fields = "__all__"

    def to_internal_value(self, data):
        """
        POST/PUT과 같이 데이터 변경이 있을 때
        데이터를 저장하기 전에 핸들링 할수 있는 함수.
        """
        ret = super(UserSerializer, self).to_internal_value(data)

        return ret

    def to_representation(self, obj):
        """
        GET/POST/PUT과 같이 데이터 변경이 있고난 후
        serializer.data로 접근할 때 값을 변하여 보여줍니다.
        """
        ret = super(UserSerializer,self).to_representation(obj)
        return ret

    # 한 filed에 대해서 유효성 검사시
    #  validate_field명
    def validate_password(self, value):
        if len(value) < 8:
            raise serializers.ValidationError('패스워드 최소 8자 이상이어야 합니다.')


        errors = dict()

        try:
            # 이걸로 규칙 유효한지 검사해보는듯. 1234등 부적절한거 거르는듯.
            validate_password(password=value)

        except serializers.ValidationError as e:
            errors['password'] = list(e.messages)
            print(errors)

        if errors:
            raise serializers.ValidationError(errors)
        return value

    def validate_email(self,value):
        if User.objects.filter(email=value).exists():
            raise serializers.ValidationError('이메일이 이미 존재합니다')

        errors = dict()
        validator = EmailValidator()
        try:
            validator(value)
        except Validoation_Core_Error as e :
            errors['email'] = list(e.message)
            print(errors)

        if errors:
            raise serializers.ValidationError(errors)

        return value

    def validate_phone_number(self,phone_number):
        if User.objects.filter(phone_number=phone_number).exists():
            raise serializers.ValidationError('휴대전화번호가 이미 존재합니다')

        for index,number in enumerate(phone_number):
            # 해당 자리수에서 데이터 타입이 숫자가 아니면
            if number.isdigit() == False :
                raise serializers.ValidationError('- 없이 숫자만 입력해 주세요')

        # 자리수가 10~11자 아니면
        if len(phone_number)!=10 and len(phone_number)!=11:
            raise serializers.ValidationError('010aaaabbbb 형식에 맞게 번호를 입력해주세요')

        return phone_number

    # 여러 필드에 걸처서 유효성 검사시
    # validate(attrs)
    def validate(self,attrs):
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('패스워드가 일치하지 않습니다.')
        return attrs

    def create(self,validated_data):
        """
        데 이터를 저장할 때 필요한 과정을 구현한다.
        """
        user = User.objects.create_user(
        username=validated_data['username'],
        password=validated_data['password'],
        email=validated_data['email'],
        phone_number=validated_data['phone_number'],
        )

        user.is_active = False
        user.save()

        # 그냥 유저 전달하면 에러떠서 민규님 따라해봄
        send_email.delay(user.pk)


        return user
class UnparkCarSerializer(serializers.Serializer):
    slot = serializers.CharField()
class ProxyUserListSerializer(serializers.Serializer):
    company = serializers.CharField(required=True)
    filter = serializers.CharField(required=True)
        class ExampleSerializer(serializers.ModelSerializer):
            text = serializers.CharField()

            class Meta:
                model = MetaClassTestModel
                exclude = ('text',)
Beispiel #6
0
class ResourceBaseTypesSerializer(DynamicEphemeralSerializer):
    name = serializers.CharField()
    count = serializers.IntegerField()

    class Meta:
        name = 'resource-types'
Beispiel #7
0
class UserAuthenticationSerializer(serializers.Serializer):
    username = serializers.CharField(max_length=100)
    password = serializers.CharField(max_length=100)
class SafeBalanceResponseSerializer(serializers.Serializer):
    token_address = serializers.CharField()
    token = Erc20InfoSerializer()
    balance = serializers.CharField()
class SafeMultisigTransactionSerializer(SafeMultisigTxSerializerV1):
    contract_transaction_hash = Sha3HashField()
    sender = EthereumAddressField()
    # TODO Make signature mandatory
    signature = HexadecimalField(required=False, min_length=130)  # Signatures must be at least 65 bytes
    origin = serializers.CharField(max_length=100, allow_null=True, default=None)

    def validate(self, data):
        super().validate(data)

        ethereum_client = EthereumClientProvider()
        safe = Safe(data['safe'], ethereum_client)
        safe_tx = safe.build_multisig_tx(data['to'], data['value'], data['data'], data['operation'],
                                         data['safe_tx_gas'], data['base_gas'], data['gas_price'],
                                         data['gas_token'],
                                         data['refund_receiver'], safe_nonce=data['nonce'])
        contract_transaction_hash = safe_tx.safe_tx_hash

        # Check safe tx hash matches
        if contract_transaction_hash != data['contract_transaction_hash']:
            raise ValidationError(f'Contract-transaction-hash={contract_transaction_hash.hex()} '
                                  f'does not match provided contract-tx-hash={data["contract_transaction_hash"].hex()}')

        # Check there's not duplicated tx with same `nonce` or same `safeTxHash` for the same Safe.
        # We allow duplicated if existing tx is not executed
        multisig_transactions = MultisigTransaction.objects.filter(
            safe=safe.address,
            nonce=data['nonce']
        ).executed()
        if multisig_transactions:
            for multisig_transaction in multisig_transactions:
                if multisig_transaction.safe_tx_hash == contract_transaction_hash.hex():
                    raise ValidationError(f'Tx with safe-tx-hash={contract_transaction_hash.hex()} '
                                          f'for safe={safe.address} was already executed in '
                                          f'tx-hash={multisig_transaction.ethereum_tx_id}')

            raise ValidationError(f'Tx with nonce={safe_tx.safe_nonce} for safe={safe.address} '
                                  f'already executed in tx-hash={multisig_transactions[0].ethereum_tx_id}')

        # Check owners and pending owners
        try:
            safe_owners = safe.retrieve_owners(block_identifier='pending')
        except BadFunctionCallOutput:  # Error using pending block identifier
            safe_owners = safe.retrieve_owners(block_identifier='latest')

        data['safe_owners'] = safe_owners

        delegates = SafeContractDelegate.objects.get_delegates_for_safe(safe.address)
        allowed_senders = safe_owners + delegates
        if not data['sender'] in allowed_senders:
            raise ValidationError(f'Sender={data["sender"]} is not an owner or delegate. '
                                  f'Current owners={safe_owners}. Delegates={delegates}')

        signature_owners = []
        # TODO Make signature mandatory
        signature = data.get('signature', b'')
        parsed_signatures = SafeSignature.parse_signature(signature, contract_transaction_hash)
        data['parsed_signatures'] = parsed_signatures
        data['trusted'] = bool(parsed_signatures)  # If signatures, transaction is trusted (until signatures are mandatory)
        for safe_signature in parsed_signatures:
            owner = safe_signature.owner
            if not safe_signature.is_valid(ethereum_client, safe.address):
                raise ValidationError(f'Signature={safe_signature.signature.hex()} for owner={owner} is not valid')

            if owner in delegates and len(parsed_signatures) > 1:
                raise ValidationError(f'Just one signature is expected if using delegates')
            if owner not in allowed_senders:
                raise ValidationError(f'Signer={owner} is not an owner or delegate. '
                                      f'Current owners={safe_owners}. Delegates={delegates}')
            if owner in signature_owners:
                raise ValidationError(f'Signature for owner={owner} is duplicated')

            signature_owners.append(owner)

        # TODO Make signature mandatory. len(signature_owners) must be >= 1
        if signature_owners and data['sender'] not in signature_owners:
            raise ValidationError(f'Signature does not match sender={data["sender"]}. '
                                  f'Calculated owners={signature_owners}')

        return data

    def save(self, **kwargs):
        safe_tx_hash = self.validated_data['contract_transaction_hash']
        origin = self.validated_data['origin']
        trusted = self.validated_data['trusted']
        multisig_transaction, created = MultisigTransaction.objects.get_or_create(
            safe_tx_hash=safe_tx_hash,
            defaults={
                'safe': self.validated_data['safe'],
                'to': self.validated_data['to'],
                'value': self.validated_data['value'],
                'data': self.validated_data['data'] if self.validated_data['data'] else None,
                'operation': self.validated_data['operation'],
                'safe_tx_gas': self.validated_data['safe_tx_gas'],
                'base_gas': self.validated_data['base_gas'],
                'gas_price': self.validated_data['gas_price'],
                'gas_token': self.validated_data['gas_token'],
                'refund_receiver': self.validated_data['refund_receiver'],
                'nonce': self.validated_data['nonce'],
                'origin': origin,
                'trusted': trusted,
            }
        )

        if not created and trusted and not multisig_transaction.trusted:
            multisig_transaction.origin = origin
            multisig_transaction.trusted = trusted
            multisig_transaction.save(update_fields=['origin', 'trusted'])

        for safe_signature in self.validated_data.get('parsed_signatures'):
            if safe_signature.owner in self.validated_data['safe_owners']:
                multisig_confirmation, _ = MultisigConfirmation.objects.get_or_create(
                    multisig_transaction_hash=safe_tx_hash,
                    owner=safe_signature.owner,
                    defaults={
                        'multisig_transaction': multisig_transaction,
                        'signature': safe_signature.export_signature(),
                        'signature_type': safe_signature.signature_type.value,
                    }
                )
        return multisig_transaction
class UserRegSerializer(serializers.ModelSerializer):
    code = serializers.CharField(required=True,
                                 write_only=True,
                                 max_length=4,
                                 min_length=4,
                                 label="验证码",
                                 error_messages={
                                     "blank": "请输入验证码",
                                     "required": "请输入验证码",
                                     "max_length": "验证码格式错误",
                                     "min_length": "验证码格式错误"
                                 },
                                 help_text="验证码")
    username = serializers.CharField(label="用户名",
                                     help_text="用户名",
                                     required=True,
                                     allow_blank=False,
                                     validators=[
                                         UniqueValidator(
                                             queryset=User.objects.all(),
                                             message="用户已经存在")
                                     ])

    password = serializers.CharField(
        style={'input_type': 'password'},
        help_text="密码",
        label="密码",
        write_only=True,
    )

    # def create(self, validated_data):
    #     users = super(UserRegSerializer, self).create(validated_data=validated_data)
    #     users.set_password(validated_data["password"])
    #     users.save()
    #     return users

    def validate_code(self, code):
        # try:
        #     verify_records = VerifyCode.objects.get(mobile=self.initial_data["username"], code=code)
        # except VerifyCode.DoesNotExist as e:
        #     pass
        # except VerifyCode.MultipleObjectsReturned as e:
        #     pass
        verify_records = VerifyCode.objects.filter(
            mobile=self.initial_data["username"]).order_by("-add_time")
        if verify_records:
            last_record = verify_records[0]

            five_mintes_ago = datetime.now() - timedelta(
                hours=0, minutes=5, seconds=0)
            if five_mintes_ago > last_record.add_time:
                raise serializers.ValidationError("验证码过期")

            if last_record.code != code:
                raise serializers.ValidationError("验证码错误")

        else:
            raise serializers.ValidationError("验证码错误")

    def validate(self, attrs):
        attrs["mobile"] = attrs["username"]
        del attrs["code"]
        return attrs

    class Meta:
        model = User
        fields = ("username", "code", "mobile", "password")
class Erc20InfoSerializer(serializers.Serializer):
    name = serializers.CharField()
    symbol = serializers.CharField()
    decimals = serializers.IntegerField()
    logo_uri = serializers.CharField()
class HelloSerializer(serializers.Serializer):
    """Serializes a name field for testing our APIView (extract or inout selected data"""

    name = serializers.CharField(max_length=10)
class UserTransactionSerializer(serializers.ModelSerializer):
    email = serializers.CharField(max_length=200)
    password = serializers.CharField(max_length=200)
    User = serializers.IntegerField()

    class Meta:
        model = DrawerCash
        fields = ('id',
                  'email',
                  'password',
                  'amount',
                  'terminal',
                  'User',
                  'manager',
                  'trans_type',
                  'note')

    def validate_terminal(self,value):
        data = self.get_initial()
        try:
            terminal = Terminal.objects.get(pk=int(data.get('terminal')))
            if terminal:
                self.terminal = terminal
                return value
            else:
                logger.error('Terminal specified does not exist')
                raise ValidationError('Terminal specified does not exist')
        except:
            logger.error('Terminal specified does not exist')
            raise ValidationError('Terminal specified does not exist')
        return value

    def validate_note(self, value):
        data = self.get_initial()
        try:
            if data.get('note'):
                return value
            else:
                logger.error('Add a note!')
                raise ValidationError('Add a note!')
        except:
            logger.error('Add a note!')
            raise ValidationError('Add a note!')


    def validate_email(self, value):
        data = self.get_initial()
        username = data.get('email')
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'name': username}
        try:
            user = get_user_model().objects.get(**kwargs)
            if not user:
                logger.error('Username/email error Authentication Failed!')
                raise PermissionDenied('Username/email error Authentication Failed!')
            else:
                return value
        except Exception as e:
            logger.error(e)
            raise PermissionDenied('Username/email Failed!')
        return value

    def validate_password(self,value):
        data = self.get_initial()
        password = data.get('password')
        username = data.get('email')
        if '@' in username:
            kwargs = {'email': username}
        else:
            kwargs = {'name': username}
        try:
            user = get_user_model().objects.get(**kwargs)
            if user.check_password(password) and user.has_perm('sale.add_drawercash') and user.has_perm('sale.change_drawercash'):
                self.manager = user
                return value
            else:
                raise PermissionDenied('Authentication Failed!')
        except:
            raise PermissionDenied('Authentication Failed!')
        return value

    def validate_User(self,value):
        data = self.get_initial()
        try:
            user = User.objects.get(pk=int(data.get('User')))
            if not user:
                raise PermissionDenied('Cashier Authentication Failed!')
            else:
                return value
        except:
            raise ValidationError('Cashier does not extist')
        return value



    def validate_trans_type(self,value):
        data = self.get_initial()
        trans_type = str(data.get('trans_type'))
        if trans_type != 'deposit' and self.type != 'withdraw':
            raise ValidationError('Transaction type error!')
        return value

    def validate_amount(self,value):
        data = self.get_initial()
        try:
            terminal_id = int(data.get('terminal'))
        except:
            raise ValidationError('Terminal id required!')
        self.amount = Decimal(data.get('amount'))
        self.type = str(data.get('trans_type'))
        if self.type != 'deposit' and self.type != 'withdraw':
            raise ValidationError('Transaction type error!')
        if self.type == 'withdraw':
            self.terminal = Terminal.objects.get(pk=terminal_id)
            if self.terminal.amount < self.amount:
                raise ValidationError('Insufficient cash in drawer!')
        return value


    def create(self, validated_data):
        """ authenticate user and transact
        """
        trans_type = str(validated_data['trans_type'])
        amount = validated_data['amount']
        manager = self.manager
        terminal = validated_data['terminal']
        user = validated_data['User']
        note = validated_data['note']

        trail = str(manager)+' '+trans_type+' '+str(amount)+\
                    ' from TERMINAL:'+str(terminal)
        print trail
        if trans_type == 'deposit':
            self.terminal.amount += Decimal(amount)
            self.terminal.save()
            TerminalHistoryEntry.objects.create(
                            terminal=terminal,
                            comment=trail,
                            crud=trans_type,
                            user=manager
                        )
        elif trans_type == 'withdraw':
            self.terminal.amount -= Decimal(amount)
            self.terminal.save()
            TerminalHistoryEntry.objects.create(
                            terminal=terminal,
                            comment=trail,
                            crud=trans_type,
                            user=manager
                        )


        drawer = DrawerCash.objects.create(manager=manager,
                                           user = User.objects.get(pk=int(user)),
                                           terminal=terminal,
                                           amount=amount,
                                           trans_type=trans_type,
                                           note=note)
        print drawer

        return validated_data
class UploadParamSerializer(serializers.Serializer):
    object_name = serializers.CharField()
Beispiel #15
0
class PatientDetailsSerializers(serializers.ModelSerializer):
    last_edited_by_email=serializers.CharField(read_only=True,source="last_edited_by.username")
    class Meta:
        model=PatientDetails
        fields=['id','patient_name','patient_photo','patient_phone_number','patient_adress','patient_phone_number','patient_DOB','gender','pregnantStat','months','email','slug','patient_adress','patient_desc','severity','assigned_doctor','last_edited_by_email']
class SafeBalanceUsdResponseSerializer(SafeBalanceResponseSerializer):
    balance_usd = serializers.CharField()
Beispiel #17
0
    def __init__(self, *args, **kwargs):
        # Instantiate the superclass normally
        super().__init__(*args, **kwargs)

        self.fields['pk'] = serializers.CharField(read_only=True)
        self.fields['uuid'] = serializers.CharField(read_only=True)
        self.fields['resource_type'] = serializers.CharField(read_only=True)
        self.fields['polymorphic_ctype_id'] = serializers.CharField(read_only=True)
        self.fields['owner'] = DynamicRelationField(UserSerializer, embed=True, many=False, read_only=True)
        self.fields['poc'] = ContactRoleField('poc', read_only=True)
        self.fields['metadata_author'] = ContactRoleField('metadata_author', read_only=True)
        self.fields['title'] = serializers.CharField()
        self.fields['abstract'] = serializers.CharField()
        self.fields['attribution'] = serializers.CharField()
        self.fields['doi'] = serializers.CharField()
        self.fields['alternate'] = serializers.CharField(read_only=True)
        self.fields['date'] = serializers.DateTimeField()
        self.fields['date_type'] = serializers.CharField()
        self.fields['temporal_extent_start'] = serializers.DateTimeField()
        self.fields['temporal_extent_end'] = serializers.DateTimeField()
        self.fields['edition'] = serializers.CharField()
        self.fields['purpose'] = serializers.CharField()
        self.fields['maintenance_frequency'] = serializers.CharField()
        self.fields['constraints_other'] = serializers.CharField()
        self.fields['language'] = serializers.CharField()
        self.fields['supplemental_information'] = serializers.CharField()
        self.fields['data_quality_statement'] = serializers.CharField()
        self.fields['bbox_polygon'] = fields.GeometryField()
        self.fields['ll_bbox_polygon'] = fields.GeometryField()
        self.fields['srid'] = serializers.CharField()
        self.fields['group'] = DynamicRelationField(GroupSerializer, embed=True, many=False)
        self.fields['popular_count'] = serializers.CharField()
        self.fields['share_count'] = serializers.CharField()
        self.fields['rating'] = serializers.CharField()
        self.fields['featured'] = serializers.BooleanField()
        self.fields['is_published'] = serializers.BooleanField()
        self.fields['is_approved'] = serializers.BooleanField()
        self.fields['detail_url'] = DetailUrlField(read_only=True)
        self.fields['created'] = serializers.DateTimeField(read_only=True)
        self.fields['last_updated'] = serializers.DateTimeField(read_only=True)
        self.fields['raw_abstract'] = serializers.CharField(read_only=True)
        self.fields['raw_purpose'] = serializers.CharField(read_only=True)
        self.fields['raw_constraints_other'] = serializers.CharField(read_only=True)
        self.fields['raw_supplemental_information'] = serializers.CharField(read_only=True)
        self.fields['raw_data_quality_statement'] = serializers.CharField(read_only=True)
        self.fields['metadata_only'] = serializers.BooleanField()
        self.fields['processed'] = serializers.BooleanField(read_only=True)
        self.fields['state'] = serializers.CharField(read_only=True)
        self.fields['sourcetype'] = serializers.CharField(read_only=True)

        self.fields['embed_url'] = EmbedUrlField()
        self.fields['thumbnail_url'] = ThumbnailUrlField()
        self.fields['keywords'] = DynamicRelationField(
            SimpleHierarchicalKeywordSerializer, embed=False, many=True)
        self.fields['regions'] = DynamicRelationField(
            SimpleRegionSerializer, embed=True, many=True, read_only=True)
        self.fields['category'] = DynamicRelationField(
            SimpleTopicCategorySerializer, embed=True, many=False)
        self.fields['restriction_code_type'] = DynamicRelationField(
            RestrictionCodeTypeSerializer, embed=True, many=False)
        self.fields['license'] = DynamicRelationField(
            LicenseSerializer, embed=True, many=False)
        self.fields['spatial_representation_type'] = DynamicRelationField(
            SpatialRepresentationTypeSerializer, embed=True, many=False)
class SafeDelegateResponseSerializer(serializers.Serializer):
    delegate = EthereumAddressField()
    delegator = EthereumAddressField()
    label = serializers.CharField(max_length=50)
class SearchCity(serializers.Serializer):
    city_name=serializers.CharField(max_length=200)
class AuthSerializer(serializers.Serializer):
    username = serializers.CharField(required=True)
    password = serializers.CharField(required=True)
Beispiel #21
0
class UserAuthenticationResponseSerializer(serializers.Serializer):
    token = serializers.CharField(max_length=100)
    user_id = serializers.IntegerField()
    is_inspector = serializers.BooleanField()
    is_from_insurance = serializers.BooleanField()
    is_from_auto_repair_shop = serializers.BooleanField()
Beispiel #22
0
class UserProfileSerializer(serializers.ModelSerializer):
	team_name = serializers.CharField(source='team.name', read_only=True)
	team = serializers.CharField(source='team.id', read_only=True)
	profile_id = serializers.CharField(source='id', read_only=True)
	user_id = serializers.CharField(source='user.id', read_only=True)
	username = serializers.CharField(source='user.username', read_only=True)
	first_name = serializers.CharField(source='user.first_name')
	last_name = serializers.CharField(source='user.last_name')
	shopify_access_token = serializers.CharField(source='team.shopify_access_token')
	squarespace_access_token = serializers.CharField(source='team.squarespace_access_token')
	shopify_store_name = serializers.CharField(source='team.shopify_store_name')
	username_display = serializers.CharField(source='get_username_display', read_only=True)

	class Meta:
		model = UserProfile
		fields = ('user_id', 'id', 'profile_id', 'username', 'username_display', 'first_name', 'last_name', 'team', 'account_type', 'team_name', 'email', 'shopify_access_token', 'shopify_store_name', 'squarespace_access_token', 'username_display', 'finished_onboarding')
        class TestSerializer(serializers.ModelSerializer):
            non_model_field = serializers.CharField()

            class Meta:
                model = OneFieldModel
                fields = ('char_field', 'non_model_field')
Beispiel #24
0
class ArticleSerializer(DispatchModelSerializer,
                        DispatchPublishableSerializer):
    """Serializes the Article model."""

    id = serializers.ReadOnlyField(source='parent_id')
    slug = serializers.SlugField(validators=[SlugValidator()])

    section = SectionSerializer(read_only=True)
    section_id = serializers.IntegerField(write_only=True)

    subsection = SubsectionSerializer(source='get_subsection', read_only=True)
    subsection_id = serializers.IntegerField(write_only=True,
                                             required=False,
                                             allow_null=True)

    featured_image = ImageAttachmentSerializer(required=False, allow_null=True)
    featured_video = VideoAttachmentSerializer(required=False, allow_null=True)

    content = ContentSerializer()

    authors = AuthorSerializer(many=True, read_only=True)
    author_ids = serializers.ListField(write_only=True,
                                       child=serializers.JSONField(),
                                       validators=[AuthorValidator])
    authors_string = serializers.CharField(source='get_author_string',
                                           read_only=True)

    tags = TagSerializer(many=True, read_only=True)
    tag_ids = serializers.ListField(write_only=True,
                                    required=False,
                                    child=serializers.IntegerField())

    topic = TopicSerializer(read_only=True)
    topic_id = serializers.IntegerField(write_only=True,
                                        allow_null=True,
                                        required=False)

    url = serializers.CharField(source='get_absolute_url', read_only=True)

    current_version = serializers.IntegerField(read_only=True,
                                               source='revision_id')

    template = TemplateSerializer(required=False, source='get_template')
    template_id = serializers.CharField(required=False, write_only=True)
    template_data = JSONField(required=False)

    integrations = JSONField(required=False)

    currently_breaking = serializers.BooleanField(
        source='is_currently_breaking', read_only=True)

    class Meta:
        model = Article
        fields = ('id', 'slug', 'url', 'headline', 'featured_image',
                  'featured_video', 'snippet', 'content', 'authors',
                  'author_ids', 'tags', 'tag_ids', 'topic', 'topic_id',
                  'authors_string', 'section', 'section_id', 'subsection',
                  'subsection_id', 'published_at', 'is_published',
                  'is_breaking', 'breaking_timeout', 'currently_breaking',
                  'published_version', 'current_version', 'latest_version',
                  'preview_id', 'importance', 'reading_time', 'template',
                  'template_id', 'template_data', 'seo_keyword',
                  'seo_description', 'integrations')
        authenticated_fields = ('template', 'integrations', 'preview_id')

    def create(self, validated_data):
        instance = Article()
        return self.update(instance, validated_data)

    def update(self, instance, validated_data):
        template = validated_data.get('template_id', instance.template)
        template_data = validated_data.get('template_data',
                                           instance.template_data)
        tag_ids = validated_data.get('tag_ids', False)

        tags = []
        if tag_ids != False:
            for tag_id in tag_ids:
                try:
                    tags.append(Tag.objects.get(id=int(tag_id)))
                except Tag.DoesNotExist:
                    pass

        TemplateValidator(template, template_data, tags)

        # Update basic fields
        instance.headline = validated_data.get('headline', instance.headline)
        instance.section_id = validated_data.get('section_id',
                                                 instance.section_id)
        instance.slug = validated_data.get('slug', instance.slug)
        instance.snippet = validated_data.get('snippet', instance.snippet)
        instance.reading_time = validated_data.get('reading_time',
                                                   instance.reading_time)
        instance.importance = validated_data.get('importance',
                                                 instance.importance)
        instance.is_breaking = validated_data.get('is_breaking',
                                                  instance.is_breaking)
        instance.breaking_timeout = validated_data.get(
            'breaking_timeout', instance.breaking_timeout)
        instance.seo_keyword = validated_data.get('seo_keyword',
                                                  instance.seo_keyword)
        instance.seo_description = validated_data.get('seo_description',
                                                      instance.seo_description)
        instance.integrations = validated_data.get('integrations',
                                                   instance.integrations)
        instance.template = template
        instance.template_data = template_data

        instance.save()

        instance.content = validated_data.get('content', instance.content)

        featured_image = validated_data.get('featured_image', False)
        if featured_image != False:
            instance.save_featured_image(featured_image)

        featured_video = validated_data.get('featured_video', False)
        if featured_video != False:
            instance.save_featured_video(featured_video)

        authors = validated_data.get('author_ids')

        if authors:
            instance.save_authors(authors, is_publishable=True)

        if tag_ids != False:
            instance.save_tags(tag_ids)

        topic_id = validated_data.get('topic_id', False)
        if topic_id != False:
            instance.save_topic(topic_id)

        subsection_id = validated_data.get('subsection_id', None)
        instance.save_subsection(subsection_id)

        # Perform a final save (without revision), update content and featured image
        instance.save(update_fields=[
            'content', 'featured_image', 'featured_video', 'topic'
        ],
                      revision=False)

        return instance
        class TestSerializer(serializers.ModelSerializer):
            additional_attr = serializers.CharField()

            class Meta:
                model = OneFieldModel
                fields = ('char_field', 'additional_attr')
Beispiel #26
0
class PageSerializer(DispatchModelSerializer, DispatchPublishableSerializer):
    """Serializes the Page model."""

    id = serializers.ReadOnlyField(source='parent_id')
    slug = serializers.SlugField(validators=[SlugValidator()])

    featured_image = ImageAttachmentSerializer(required=False, allow_null=True)
    featured_video = VideoAttachmentSerializer(required=False, allow_null=True)

    content = ContentSerializer()

    url = serializers.CharField(source='get_absolute_url', read_only=True)

    current_version = serializers.IntegerField(read_only=True,
                                               source='revision_id')

    template = TemplateSerializer(required=False, source='get_template')
    template_id = serializers.CharField(required=False, write_only=True)
    template_data = JSONField(required=False)
    updated_at = serializers.DateTimeField(read_only=True)

    class Meta:
        model = Page
        fields = ('id', 'slug', 'url', 'title', 'featured_image',
                  'featured_video', 'snippet', 'content', 'published_at',
                  'updated_at', 'is_published', 'published_version',
                  'current_version', 'latest_version', 'preview_id',
                  'template', 'template_id', 'template_data', 'seo_keyword',
                  'seo_description')
        authenticated_fields = ('template', 'preview_id')

    def create(self, validated_data):
        instance = Page()
        return self.update(instance, validated_data)

    def update(self, instance, validated_data):

        # Update all the basic fields
        instance.title = validated_data.get('title', instance.title)
        instance.slug = validated_data.get('slug', instance.slug)
        instance.snippet = validated_data.get('snippet', instance.snippet)
        instance.seo_keyword = validated_data.get('seo_keyword',
                                                  instance.seo_keyword)
        instance.seo_description = validated_data.get('seo_description',
                                                      instance.seo_description)
        instance.template = validated_data.get('template_id',
                                               instance.template)
        instance.template_data = validated_data.get('template_data',
                                                    instance.template_data)

        # Save instance before processing/saving content in order to save associations to correct ID
        instance.save()

        instance.content = validated_data.get('content', instance.content)

        featured_image = validated_data.get('featured_image', False)
        if featured_image != False:
            instance.save_featured_image(featured_image)

        featured_video = validated_data.get('featured_video', False)
        if featured_video != False:
            instance.save_featured_video(featured_video)

        # Perform a final save (without revision), update content and featured image
        instance.save(
            update_fields=['content', 'featured_image', 'featured_video'],
            revision=False)

        return instance
class CarParkSerializer(serializers.Serializer):
    car_number = serializers.CharField()
Beispiel #28
0
class WidgetSerializer(serializers.Serializer):
    id = serializers.SlugField()
    name = serializers.CharField(read_only=True)
    fields = serializers.ListField(read_only=True, child=FieldSerializer())
class RoleInfoSerializer(serializers.Serializer):
    role_name = serializers.CharField(max_length=32, required=True, help_text=u"角色名称")
    role_id = serializers.IntegerField(help_text=u"角色ID")
Beispiel #30
0
class CourseDetailModelSerializers(serializers.ModelSerializer
                                   ):  #序列化组件怎样个运行的过程
    # one2one,forenkey,choice   自定义serialezer字段实现跨表
    title = serializers.CharField(
        source='course.name')  #即使不取这里面的字段,也不能写错,定义了必须要取这些值
    img = serializers.CharField(source='course.course_img')
    level = serializers.CharField(source='course.get_level_display')
    brief = serializers.CharField(source='course.brief')
    # many2many
    recommends = serializers.SerializerMethodField()  #获取多个值的字段
    comment = serializers.SerializerMethodField()
    chapter = serializers.SerializerMethodField()
    asked_question = serializers.SerializerMethodField()
    pricepolicy = serializers.SerializerMethodField()
    teachers = serializers.SerializerMethodField()

    class Meta:
        model = CourseDetail
        fields = [
            'course_slogan', 'why_study', 'title', 'img', 'level',
            'recommends', 'chapter', 'what_to_study_brief',
            'career_improvement', 'comment', 'asked_question', 'brief',
            'pricepolicy', 'prerequisite', 'teachers'
        ]
        # depth = 0

    #内置的获取字段的方法
    def get_recommends(self, obj):
        queryset = obj.recommend_courses.all()
        print(queryset)
        return [{'id': row.id, 'title': row.name} for row in queryset]

    def get_chapter(self, obj):

        queryset = obj.course.coursechapters.all()
        return [{'id': row.id, 'name': row.name} for row in queryset]

    def get_comment(self, obj):

        queryset = obj.course.comment.all()
        return [{
            'id': row.id,
            'account': row.account.username,
            'content': row.content
        } for row in queryset]

    def get_asked_question(self, obj):

        queryset = obj.course.asked_question.all()
        return [{
            'id': row.id,
            'account': row.question,
            'content': row.answer
        } for row in queryset]

    def get_pricepolicy(self, obj):

        queryset = obj.course.price_policy.all()
        return [{
            'id': row.id,
            'account': row.valid_period,
            'content': row.price
        } for row in queryset]

    def get_teachers(self, obj):

        queryset = obj.teachers.all()
        return [{
            'id': row.id,
            'name': row.name,
            'title': row.title,
            'signature': row.signature,
            'brief': row.brief
        } for row in queryset]