Esempio n. 1
0
class CitySerializer(serializers.ModelSerializer):
    def to_representation(self, value):
        return {"id": value.id, "name": value.name}

    id = serializers.IntegerField(required=True)
    name = serializers.CharField(required=False)
    uf = serializers.RelatedField(required=False, read_only=True)

    class Meta:
        model = City
        fields = '__all__'
    def test_missing_many_to_many_related_field(self):
        '''
        Regression test for #632

        https://github.com/tomchristie/django-rest-framework/pull/632
        '''
        field = serializers.RelatedField(many=True, read_only=False)

        into = {}
        field.field_from_native({}, None, 'field_name', into)
        self.assertEqual(into['field_name'], [])
Esempio n. 3
0
class BoardSerializer(serializers.ModelSerializer):
    """Serializes a Note object"""
    isSpecial = serializers.Field(source='board.isAdminBoard')
    user = serializers.Field(source='board.user.username')
    tags = TagListSerializer(required=False)
    board_pic = serializers.RelatedField(many=True)
    board_pic_cover = serializers.RelatedField(many=True)

    class Meta:
        model = Board
        fields = (
            'id',
            'name',
            'user',
            'isShared',
            'color',
            'isArchived',
            'viewCount',
            'tags',
        )
class UserSerializer(serializers.ModelSerializer):
    """
    Default Model Serializer for Users with all made and accepted Bets as well as Friends.

    To-Do: 
    add First and Last Names for Users (when making bets Users should be able to search by first, last, and username)
    (possibly also add email and phone number, but usually friends search for each other by name)
    """
    user = serializers.RelatedField(read_only=True)
    user_id = serializers.RelatedField(read_only=True)
    made = serializers.RelatedField(read_only=True, many=True)
    accepted = serializers.RelatedField(read_only=True, many=True)
    friends = serializers.SerializerMethodField('getfriends')

    class Meta:
        model = BetUser
        fields = ('user', 'user_id', 'venmoid', 'made', 'accepted', 'friends')

    # Use getfriends method defined for BetUsers to get a list of friend venmonames
    def getfriends(self, obj):
        return obj.getfriends()
Esempio n. 5
0
class ContextSerializer(serializers.HyperlinkedModelSerializer):
    api_url = serializers.HyperlinkedIdentityField(view_name='context-detail',
                                                   lookup_field='pk')
    agent_type = serializers.RelatedField()
    contributors = PlainPeopleSerializer(source='contributors',
                                         many=True,
                                         read_only=True)

    class Meta:
        model = EconomicAgent
        fields = ('api_url', 'url', 'name', 'slug', 'agent_type', 'address',
                  'contributors')
Esempio n. 6
0
class EconomicAgentSerializer(serializers.HyperlinkedModelSerializer):
    api_url = serializers.HyperlinkedIdentityField(
        view_name='economicagent-detail', lookup_field='pk')
    agent_type = serializers.RelatedField()
    projects = PlainContextSerializer(source='contexts_participated_in',
                                      many=True,
                                      read_only=True)

    class Meta:
        model = EconomicAgent
        fields = ('api_url', 'url', 'name', 'nick', 'slug', 'agent_type',
                  'address', 'email', 'projects')
Esempio n. 7
0
class VipPortToPoolSerializer(serializers.ModelSerializer):

    environment_vip_ipv4 = serializers.RelatedField(
        source='requisicao_vip.ip.networkipv4.ambient_vip.name'
    )

    environment_vip_ipv6 = serializers.RelatedField(
        source='requisicao_vip.ipv6.networkipv6.ambient_vip.name'
    )

    class Meta:
        model = VipPortToPool
        depth = 2
        fields = (
            'id',
            'requisicao_vip',
            'server_pool',
            'port_vip',
            'environment_vip_ipv4',
            'environment_vip_ipv6'
        )
Esempio n. 8
0
class loggingSerializer(serializers.ModelSerializer):
    logicaluid = serializers.RelatedField(source='logical_uid', read_only=True)
    qty = serializers.IntegerField()
    time = serializers.CharField(max_length=144)
    warehouse = serializers.CharField(max_length=144)

    class Meta:
        model = logging
        fields = "__all__"

    def create(self, validated_data):
        return logging.objects.create(**validated_data)
Esempio n. 9
0
class PageSerial(serializers.ModelSerializer):
    container = serializers.RelatedField(required=False)

    class Meta:
        model = webmodels.Page

    def validate_container(self,attr,source):
        ## The container, if not supplied will be supplied by the view
        ## based on url kwargs. 
        if 'container' in self.context:
            attr['container'] = self.context['container']
        return attr
Esempio n. 10
0
class DatasetSerializer(serializers.HyperlinkedModelSerializer):
    keyword = serializers.RelatedField(many=True, source='tags')
    modified = serializers.DateField(source='last_update')
    publisher = serializers.RelatedField(source='publisher')
    identifier = serializers.CharField(source='unique_identifer')
    accessLevel = serializers.CharField(source='public_access_level')
    accessLevelComment = serializers.CharField(source='access_level_comment')
    bureauCode = serializers.RelatedField(source='bureau_code')
    programCode = serializers.RelatedField(source='program_code')
    accessURL = serializers.CharField(source='download_url')
    webService = serializers.CharField(source='endpoint')
    license = serializers.RelatedField(source='license')
    temporal = serializers.SerializerMethodField('temporal_calc')
    dataDictionary = serializers.CharField(source='data_dictionary')
    accuralPeriodicity = serializers.CharField(source='frequency')
    landingPage = serializers.CharField(source='landing_page')
    references = serializers.RelatedField(many=True)
    issued = serializers.DateField(source='release_date')

    def temporal_calc(self, obj):
        return "%s/%s" % (obj.temporal_start, obj.temporal_end)

    class Meta:
        model = Dataset
        fields = ('title', 'description', 'keyword', 'modified', 'publisher',
                  'identifier', 'accessLevel', 'accessLevelComment',
                  'bureauCode', 'programCode', 'accessURL', 'webService',
                  'license', 'temporal', 'dataDictionary',
                  'accuralPeriodicity', 'landingPage', 'references', 'issued')
Esempio n. 11
0
class NoticeSerializer(serializers.ModelSerializer):
    subject = serializers.Field(source='get_subject')
    body = serializers.Field(source='get_body')
    type = serializers.Field(source='get_type_display')
    sender = UserSerializer()
    age = serializers.Field(source='get_age')
    official = serializers.BooleanField(source='is_official')
    replies = serializers.PrimaryKeyRelatedField(source='get_replies', many=True, read_only=True)
    spaces = serializers.RelatedField(source='space_set', many=True, read_only=True)

    class Meta:
        model = Notice
        fields = ('id', 'subject', 'body', 'created', 'date', 'age', 'sender', 'type', 'official', 'spaces', 'is_reply', 'replies')
Esempio n. 12
0
class InterestsSerializer(serializers.ModelSerializer):
    person = serializers.RelatedField(default=CurrentPersonDefault(),
                                      write_only=True,
                                      queryset=Person.objects.all(),
                                      allow_null=False)

    class Meta:
        model = Interests
        fields = "__all__"
        validators = [
            UniqueTogetherValidator(queryset=Interests.objects.all(),
                                    fields=['person', 'interest'])
        ]
class RackSerializer(serializers.ModelSerializer):


    id_sw1 = serializers.RelatedField(source='id_sw1.nome')
    id_sw2 = serializers.RelatedField(source='id_sw2.nome')
    id_ilo = serializers.RelatedField(source='id_ilo.nome')

    class Meta:
        model = Rack
        fields = ('id',
                  'nome',
                  'numero',
                  'mac_sw1',
                  'mac_sw2',
                  'mac_ilo',
                  'id_sw1',
                  'id_sw2',
                  'id_ilo',
                  'config',
                  'create_vlan_amb',
                  'dcroom'
                  )
Esempio n. 14
0
class AuctionBidderModelSerializer(serializers.ModelSerializer):
    aucs = AuctionSerializer()
    current_price = serializers.Field(source='current_price')
    end_time = serializers.Field(source='end_time')
    seller = serializers.RelatedField(source='product.seller')
    product_name = serializers.RelatedField(source='product.name')
    initial_price = serializers.RelatedField(source='product.initial_price')
    product_category = serializers.RelatedField(
        source='product.product_category')
    title = serializers.Field(source='title')

    class Meta:
        model = AuctionBidder
        fields = (
            'title',
            'product_name',
            'initial_price',
            'current_price',
            'end_time',
            'product_category',
            'seller',
        )
Esempio n. 15
0
    def test_dotted_source(self):
        """
        Source argument should support dotted.source notation.
        """
        BlogPost.objects.create(title='blah')
        field = serializers.RelatedField(many=True, source='a.b.c')

        class ClassWithQuerysetMethod(object):
            a = {'b': {'c': BlogPost.objects.all()}}

        obj = ClassWithQuerysetMethod()
        value = field.field_to_native(obj, 'field_name')
        self.assertEqual(value, ['BlogPost object'])
Esempio n. 16
0
class UserSerializer(serializers.HyperlinkedModelSerializer):
    hashtags = serializers.RelatedField(many=True)
    events = serializers.RelatedField(many=True)
    users_password = serializers.CharField(required=True, write_only=True)
    users_email = serializers.CharField(required=True, write_only=True)
    users_name_id = serializers.CharField(max_length=255, required=True)
    users_path_web_avatar = serializers.SerializerMethodField('image')

    def image(self, obj):
        if obj.users_path_web_avatar == None:
            return 'https://festive-ally-585.appspot.com/static/images/default.jpg'
        return obj.users_path_web_avatar

    class Meta:
        model = Users
        fields = ('users_id', 'users_name', 'users_name_id', 'users_firstname',
                  'users_lastname', 'users_email', 'users_password',
                  'users_path_local_avatar', 'users_path_web_avatar',
                  'users_time_zone', 'fk_users_type', 'users_delete',
                  'users_birthday', 'users_sex', 'hashtags', 'events',
                  'users_hashtags', 'users_is_location_enable')
        read_only_fields = ('users_id', 'users_delete', 'fk_users_type')
Esempio n. 17
0
class HistorySerializer(serializers.ModelSerializer):
    # description = DescriptionSerializer(source = 'product')
    package = PackageSerializer(source='product')
    brand = DallizBrandField(source='product.brand')
    reference = serializers.CharField(source='product.reference')
    unit = serializers.RelatedField(source='product.unit')
    osm_url = serializers.URLField(source='product.url')
    image_url = serializers.URLField(source='product.image_url')
    name = serializers.CharField(source='product.name')

    class Meta:
        model = History
        exclude = ('html', 'id', 'product')
Esempio n. 18
0
class ProductSerializer(OscarModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name='product-detail')
    stockrecords = serializers.HyperlinkedIdentityField(
        view_name='product-stockrecord-list')
    attributes = ProductAttributeValueSerializer(many=True,
                                                 required=False,
                                                 source="attribute_values")
    categories = serializers.RelatedField(many=True)
    product_class = serializers.RelatedField()
    images = ProductImageSerializer(many=True)
    price = serializers.HyperlinkedIdentityField(view_name='product-price')
    availability = serializers.HyperlinkedIdentityField(
        view_name='product-availability')

    class Meta:
        model = Product
        fields = overridable(
            'OSCARAPI_PRODUCTDETAIL_FIELDS',
            default=('url', 'id', 'title', 'description',
                     'date_created', 'date_updated', 'recommended_products',
                     'attributes', 'stockrecords', 'images', 'price',
                     'availability'))
Esempio n. 19
0
class UserSignUpSerializer(serializers.Serializer):
    username = serializers.CharField(
        min_length=4,
        max_length=20,
        validators = [UniqueValidator(queryset=User.objects.all())]
    )
    email = serializers.EmailField(
        validators = [UniqueValidator(queryset=User.objects.all())]
    )
    celular_regex = RegexValidator(
        regex= r'\+?1?\d{9,15}$',
        message = 'El numero celular debe ser ingresado en el formato: +999999999. de 9 a 15 digitos'
    )
    numero_celular = serializers.CharField(validators=[celular_regex], max_length=17)

    #password
    password = serializers.CharField(
        min_length=4,
        max_length=64
    )
    password_confirmation = serializers.CharField(
        min_length=4,
        max_length=64
    )
    #nombres
    first_name = serializers.CharField(min_length=2,max_length=30 )
    last_name = serializers.CharField(min_length=2,max_length=30 )

    #ubicacion
    direccion = serializers.CharField(min_length=2,max_length=30 )
    #municipio =  serializers.RelatedField(source='Municipio', queryset=Municipio.objects.all())
    municipio =  serializers.RelatedField(read_only=True,source='Municipio')
    foto = serializers.ImageField(max_length=None, use_url=True, allow_null=True, required=True)

    
    def validate(self,data):
        passwd = data['password']
        passwd_conf= data['password_confirmation']

        if passwd != passwd_conf:
            raise serializers.ValidationError("Las contraseñas no coinciden")
        
        password_validation.validate_password(passwd) 
        return data

    def create(self,data):
        data.pop('password_confirmation')
        user = User.objects.create_user(**data)
        profile = Profile.objects.create(user=user)# aux model for user
                
        return user
    def test_related_queryset_source(self):
        """
        Relational fields should be able to use queryset-returning methods as their source.
        """
        BlogPost.objects.create(title='blah')
        field = serializers.RelatedField(many=True, source='get_blogposts_queryset')

        class ClassWithQuerysetMethod(object):
            def get_blogposts_queryset(self):
                return BlogPost.objects.all()

        obj = ClassWithQuerysetMethod()
        value = field.field_to_native(obj, 'field_name')
        self.assertEqual(value, ['BlogPost object'])
Esempio n. 21
0
class PTaskSerializer(serializers.ModelSerializer):

    assignments = PTaskAssignmentListingField(many=True, required=False)
    children = serializers.RelatedField(many=True, required=False)
    creator = serializers.SlugRelatedField(slug_field="username")
    start_date = serializers.DateField()
    due_date = serializers.DateField(required=False)
    parent = serializers.SlugRelatedField(slug_field="spec", required=False)
    ptask_type = serializers.SlugRelatedField(slug_field="name")
    versions = serializers.RelatedField(many=True, required=False)
    status = PTaskStatusField(choices=PTask.STATUS_CHOICES)

    class Meta:
        model = PTask

        exclude = (

            # mptt fields
            "lft",
            "rght",
            "tree_id",
            "level",
        )
Esempio n. 22
0
class FruitSerializer(serializers.ModelSerializer):
    fruit_name = serializers.RelatedField(source='fruit_type')

    class Meta:
        model = FruitLocation
        fields = (
            'id',
            'address',
            'comment',
            'fruit_type',
            'fruit_name',
            'latitude',
            'longitude',
        )
Esempio n. 23
0
class RaiseSerializer(serializers.Serializer):

    scale_id = serializers.RelatedField(source='Scale', read_only=True)
    #	scale 		= serializers.IntegerField()
    quantity = serializers.IntegerField()
    amount = serializers.DecimalField(max_digits=30, decimal_places=15)
    base64 = serializers.CharField()
    codigo = serializers.CharField()

    #	timestamp	= serializers.TimeField()

    def create(self, validated_data):

        return Raise.objects.create(**validated_data)
Esempio n. 24
0
class Consumable_orderSerializer(serializers.ModelSerializer):
    # consumable_id = serializers.RelatedField(source='service', read_only=True)
    Operation_record_id = serializers.RelatedField(source='Operation_record',
                                                   read_only=True)

    class Meta:
        model = Service_list
        fields = [
            'Operation_record_id',
            # 'consumable_id',
            'qty',
            'description',
            'id'
        ]
Esempio n. 25
0
class GradeSerializer(serializers.ModelSerializer):
    """
    serializing the Grade Model for use with the API
    """
    id = serializers.Field()
    student = serializers.RelatedField(read_only=True)
    student_id = serializers.PrimaryKeyRelatedField(source='student')
    marking_period = serializers.RelatedField(read_only=True)
    marking_period_id = serializers.PrimaryKeyRelatedField(
        source='marking_period', required=False)
    course_section = serializers.RelatedField(source='course_section',
                                              read_only=True)
    course_section_id = serializers.PrimaryKeyRelatedField(
        source='course_section', required=False)
    grade = serializers.WritableField(source='api_grade', required=False)

    class Meta:
        model = Grade

    def validate_grade(self, attrs, source):
        value = attrs[source]
        Grade.validate_grade(value)
        return attrs
Esempio n. 26
0
class PostSerializer(serializers.ModelSerializer):
    topic = serializers.HyperlinkedRelatedField(many=False,
                                                view_name='topic-detail')
    author = serializers.RelatedField(many=False)  #ForumUserSerializer()

    def get_validation_exclusions(self):
        exclusions = super(PostSerializer, self).get_validation_exclusions()
        return exclusions + [
            'author',
            'modified_at',
        ]

    class Meta:
        model = Post
Esempio n. 27
0
class CompanyProfileSerializer(serializers.ModelSerializer):
    """
    Display Space details in Organization serializer.

    """
    name = serializers.Field(source='space.name')
    codename = serializers.Field(source='space.codename')
    slug = serializers.Field(source='space.link')
    status = serializers.Field(source='get_status')
    floor_tag = serializers.RelatedField()

    class Meta:
        model = CompanyProfile
        fields = ('name', 'codename', 'slug', 'status', 'building', 'floor', 'floor_tag')
    def test_blank_option_is_added_to_choice_if_required_equals_false(self):
        """

        """
        post = BlogPost(title="Checking blank option is added")
        post.save()

        queryset = BlogPost.objects.all()
        field = serializers.RelatedField(required=False, queryset=queryset)

        choice_count = BlogPost.objects.count()
        widget_count = len(field.widget.choices)

        self.assertEqual(widget_count, choice_count + 1, 'BLANK_CHOICE_DASH option should have been added')
Esempio n. 29
0
class SharingProposalSerializer(serializers.ModelSerializer):
    share_id = serializers.RelatedField(source='key')
    permission = serializers.CharField(source='get_permission', read_only=True)
    folder_name = serializers.RelatedField(source='folder.name')
    owner_name = serializers.RelatedField(source='owner.name')
    owner_email = serializers.RelatedField(source='owner.email')
    protocol_version = serializers.CharField(required=False)

    def restore_object(self, attrs, instance=None):
        """
        Given a dictionary of deserialized field values, either update
        an existing model instance, or create a new model instance.
        """
        if instance is not None:
            return instance

        proposal = SharingProposal(**attrs)

        proposal.key = self.context['request'].DATA['share_id']
        owner = User()
        owner.name = self.context['request'].DATA['owner_name']
        owner.email = self.context['request'].DATA['owner_email']
        proposal.owner = owner
        folder = Folder()
        folder.name = self.context['request'].DATA['folder_name']
        proposal.folder = folder
        write_access = True if self.context['request'].DATA['permission'].lower() is 'read-write' else False
        proposal.write_access = write_access
        proposal.status = 'PENDING'
        return proposal

    class Meta:
        model = SharingProposal
        fields = (
            'share_id', 'recipient', 'resource_url', 'owner_name', 'owner_email', 'folder_name', 'permission',
            'callback', 'protocol_version',
            'status', 'created_at')
Esempio n. 30
0
class TargetBeaconsSerializer(serializers.ModelSerializer):
    """
        serializer for target beacons
    """
    id = serializers.RelatedField(source="beacon")
    name = serializers.RelatedField(source="beacon")
    file_path = serializers.RelatedField(source="beacon")
    description = serializers.RelatedField(source="beacon")
    created_by = serializers.RelatedField(source="beacon")
    created_at = serializers.RelatedField(source="beacon")

    class Meta:
        model = MinionBeacon
        fields = ("id", "name", "description", "file_path", "created_by",
                  "created_at")

    def transform_id(self, obj, value):
        """
            Transform the beacon id
        """
        return obj.beacon.id

    def transform_hostname(self, obj, value):
        """
            Transform the beacon name
        """
        return obj.beacon.name

    def transform_description(self, obj, value):
        """
            Transform the beacon description
        """
        return obj.beacon.description

    def transform_created_by(self, obj, value):
        """
            Transform the beacon created by
        """
        return obj.beacon.created_by.username

    def transform_created_at(self, obj, value):
        """
            Transform the beacon created at
        """
        return obj.beacon.created_at

    def transform_file_path(self, obj, value):
        """
            Transform the file field to send rel and abs path with other metadata
        """
        file_path = obj.beacon.file_path
        if os.path.exists(file_path) and os.path.isfile(file_path):
            size = os.stat(file_path).st_size
            filename = os.path.basename(file_path)
            content = open(file_path, "r").read()
            return dict(size=size, filename=filename, content=content)
        return None