コード例 #1
0
class BaseProduct():
    category = serializers.PrimaryKeyRelatedField(queryset=Category.objects)
    title = serializers.CharField(required=True)
    slug = serializers.SlugField(required=True)
コード例 #2
0
class ArticleSerializer(serializers.ModelSerializer):
    author = ProfileSerializer(read_only=True)
    description = serializers.CharField(required=False)
    slug = serializers.SlugField(required=False)

    favorited = serializers.SerializerMethodField()
    favoritesCount = serializers.SerializerMethodField(
        method_name='get_favorites_count')

    tagList = TagRelatedField(many=True, required=False, source='tags')

    # Django REST Framework makes it possible to create a read-only field that
    # gets it's value by calling a function. In this case, the client expects
    # `created_at` to be called `createdAt` and `updated_at` to be `updatedAt`.
    # `serializers.SerializerMethodField` is a good way to avoid having the
    # requirements of the client leak into our API.
    createdAt = serializers.SerializerMethodField(method_name='get_created_at')
    updatedAt = serializers.SerializerMethodField(method_name='get_updated_at')

    class Meta:
        model = Article
        fields = (
            'author',
            'body',
            'createdAt',
            'description',
            'favorited',
            'favoritesCount',
            'slug',
            'tagList',
            'title',
            'updatedAt',
        )

    def create(self, validated_data):
        author = self.context.get('author', None)

        tags = validated_data.pop('tags', [])

        article = Article.objects.create(author=author, **validated_data)

        for tag in tags:
            article.tags.add(tag)

        return article

    def get_created_at(self, instance):
        return instance.created_at.isoformat()

    def get_favorited(self, instance):
        request = self.context.get('request', None)

        if request is None:
            return False

        if not request.user.is_authenticated():
            return False

        return request.user.profile.has_favorited(instance)

    def get_favorites_count(self, instance):
        return instance.favorited_by.count()

    def get_updated_at(self, instance):
        return instance.updated_at.isoformat()
コード例 #3
0
ファイル: project_details.py プロジェクト: mastacheata/sentry
class ProjectAdminSerializer(serializers.Serializer):
    isBookmarked = serializers.BooleanField()
    isSubscribed = serializers.BooleanField()
    name = serializers.CharField(max_length=200)
    slug = serializers.SlugField(max_length=200)
コード例 #4
0
class ShortCompanySerializer(serializers.ModelSerializer):
    slug = serializers.SlugField(source='link', read_only=True)
    square_logo = serializers.Field(source='get_square_logo')
    class Meta:
        model = Organization
        fields = ('name', 'codename', 'slug', 'square_logo')
コード例 #5
0
class StreamsSerializer(serializers.Serializer):
    topic = serializers.SlugField(required=False)
    limit = serializers.IntegerField(required=False)
    regex = serializers.CharField(required=False)

    def save(self):
        topic = None
        if 'topic' in self.validated_data:
            topic = self.validated_data['topic']

        limit = None
        if 'limit' in self.validated_data:
            limit = self.validated_data['limit']

        regex = None
        if 'regex' in self.validated_data:
            regex = self.validated_data['regex']

        if not topic and not regex:
            regex = '.*'

        # Get the authenticated user, if it exists.
        userId = 'unknown'
        request = self.context.get("request")
        if request and hasattr(request, "user"):
            userId = request.user
            record_user(userId, 'streams')

        if topic:
            try:
                datafile = open(
                    lasair.settings.BLOB_STORE_ROOT + '/streams/%s' % topic,
                    'r').read()
                data = json.loads(datafile)['digest']
                if limit:
                    data = data[:limit]
                return data
            except:
                error = 'Cannot open digest file for topic %s' % topic
                return {"error": error}

        if regex:
            try:
                r = re.compile(regex)
            except:
                replyMessage = '%s is not a regular expression' % regex
                return {"topics": [], "info": replyMessage}

            msl = connect_db()
            cursor = msl.cursor(buffered=True, dictionary=True)
            result = []
            query = 'SELECT mq_id, user, name, topic_name FROM myqueries WHERE active>0'
            cursor.execute(query)
            for row in cursor:
                tn = row['topic_name']
                if r.match(tn):
                    td = {
                        'topic':
                        tn,
                        'more_info':
                        'https://lasair-iris.roe.ac.uk/query/%d/' %
                        row['mq_id']
                    }
                    result.append(td)
            info = result
            return info

        return {"error": 'Must supply either topic or regex'}
コード例 #6
0
class AnswerInSerializer(serializers.ModelSerializer):
    create_user = serializers.SlugField('nickname')

    class Meta:
        model = Message
        fields = ('id', 'content', 'create_user')
コード例 #7
0
class MemberCreateSerializer(serializers.Serializer):
    # ------ MEMBER ------ #

    type_of = serializers.IntegerField()

    # ------ MEMBER CONTACT ------ #

    is_ok_to_email = serializers.BooleanField()
    is_ok_to_text = serializers.BooleanField()
    organization_name = serializers.CharField(
        required=False,
        allow_blank=True,
        allow_null=True,
        validators=[
            UniqueValidator(queryset=MemberContact.objects.all()),
        ],
    )
    organization_type_of = serializers.ChoiceField(
        required=False,
        allow_null=True,
        choices=MemberContact.MEMBER_ORGANIZATION_TYPE_OF_CHOICES,
    )
    first_name = serializers.CharField()
    last_name = serializers.CharField()
    email = serializers.EmailField(validators=[
        UniqueValidator(queryset=SharedUser.objects.all()),
    ], )
    primary_phone = E164PhoneNumberField()
    secondary_phone = E164PhoneNumberField(allow_null=True, required=False)

    # ------ MEMBER ADDRESS ------ #

    country = serializers.CharField()
    province = serializers.CharField()
    city = serializers.CharField()
    street_number = serializers.CharField()
    street_name = serializers.CharField()
    apartment_unit = serializers.CharField(
        required=False,
        allow_null=True,
        allow_blank=True,
    )
    street_type = serializers.ChoiceField(
        choices=MemberAddress.STREET_TYPE_CHOICES, )
    street_type_other = serializers.CharField(
        required=False,
        allow_null=True,
        allow_blank=True,
    )
    street_direction = serializers.ChoiceField(
        choices=MemberAddress.STREET_DIRECTION_CHOICES, )
    postal_code = serializers.CharField()

    # ------ MEMBER WATCH ------ #

    watch = serializers.SlugField(
        allow_null=False,
        allow_blank=False,
    )

    # ------ MEMBER METRICS ------ #

    tags = serializers.PrimaryKeyRelatedField(
        many=True,
        queryset=Tag.objects.all(),
        allow_null=True,
        required=False,
    )
    how_did_you_hear = serializers.PrimaryKeyRelatedField(
        many=False,
        required=True,
        allow_null=False,
        queryset=HowHearAboutUsItem.objects.all())
    how_did_you_hear_other = serializers.CharField(
        required=False,
        allow_null=True,
        allow_blank=True,
    )
    expectation = serializers.PrimaryKeyRelatedField(
        many=False,
        required=True,
        allow_null=False,
        queryset=ExpectationItem.objects.all())
    expectation_other = serializers.CharField(
        required=False,
        allow_null=True,
        allow_blank=True,
    )
    meaning = serializers.PrimaryKeyRelatedField(
        many=False,
        required=True,
        allow_null=False,
        queryset=MeaningItem.objects.all())
    meaning_other = serializers.CharField(
        required=False,
        allow_null=True,
        allow_blank=True,
    )
    gender = serializers.CharField(
        required=True,
        allow_blank=False,
        allow_null=False,
    )
    willing_to_volunteer = serializers.IntegerField()
    another_household_member_registered = serializers.BooleanField()
    year_of_birth = serializers.IntegerField(
        required=False,
        allow_null=True,
    )
    total_household_count = serializers.IntegerField(required=False, )
    over_18_years_household_count = serializers.IntegerField(required=False, )
    organization_employee_count = serializers.IntegerField(required=False, )
    organization_founding_year = serializers.IntegerField(required=False, )
    organization_type_of = serializers.IntegerField(required=False, )
    is_aboriginal = serializers.BooleanField(required=False, )
    is_transgender = serializers.BooleanField(required=False, )
    is_visible_minority = serializers.BooleanField(required=False, )
    is_disabled_or_has_barriers = serializers.BooleanField(required=False, )
    is_over_fifty_five = serializers.BooleanField(required=False, )

    def validate_organization_name(self, value):
        """
        Custom validation to handle case of user selecting an organization type
        of member but then forgetting to fill in the `organization_name` field.
        """
        request = self.context.get('request')
        type_of = request.data.get('type_of')
        if type_of == Member.MEMBER_TYPE_OF.BUSINESS:
            if value == None or value == "":
                raise serializers.ValidationError(
                    _('Please fill this field in.'))
        return value

    def validate_watch(self, value):
        #TODO: ADD SECURITY SO NON-EXECUTIVES CANNOT ATTACH TO OTHER USERS.
        if not Watch.objects.filter(slug=value).exists():
            raise serializers.ValidationError("Watch does not exist")
        return value

    def create(self, validated_data):
        """
        Override the `create` function to add extra functinality.
        """
        request = self.context.get('request')

        # ------ MEMBER ------ #

        type_of = validated_data.get('type_of')
        first_name = validated_data.get('first_name')
        last_name = validated_data.get('last_name')
        email = validated_data.get('email')
        watch_slug = validated_data.get('watch')
        watch = Watch.objects.filter(slug=watch_slug).first()

        user = SharedUser.objects.create(
            tenant=request.tenant,
            first_name=first_name,
            last_name=last_name,
            email=email,
            was_email_activated=True,
            is_active=True,
        )
        logger.info("Created shared user.")

        # Attach the user to the `Member` group.
        user.groups.add(SharedGroup.GROUP_MEMBERSHIP.MEMBER)
        logger.info("Shared user assigned as member.")

        member = Member.objects.create(
            user=user,
            type_of=type_of,
            watch=watch,
            created_by=request.user,
            created_from=request.client_ip,
            created_from_is_public=request.client_ip_is_routable,
            last_modified_by=request.user,
            last_modified_from=request.client_ip,
            last_modified_from_is_public=request.client_ip_is_routable,
        )
        logger.info("Created member.")

        # ------ MEMBER CONTACT ------ #

        is_ok_to_email = validated_data.get('is_ok_to_email')
        is_ok_to_text = validated_data.get('is_ok_to_text')
        organization_name = validated_data.get('organization_name')
        organization_type_of = validated_data.get('organization_type_of')
        primary_phone = validated_data.get('primary_phone', None)
        secondary_phone = validated_data.get('secondary_phone', None)

        # DEVELOPERS NOTE:
        # (1) Non-business members cannot have the following fields set,
        #     therefore we need to remove the data if the user submits them.
        if type_of != Member.MEMBER_TYPE_OF.BUSINESS:
            organization_name = None
            organization_type_of = MemberContact.MEMBER_ORGANIZATION_TYPE_OF.UNSPECIFIED

        member_contact = MemberContact.objects.create(
            member=member,
            is_ok_to_email=is_ok_to_email,
            is_ok_to_text=is_ok_to_text,
            organization_name=organization_name,
            organization_type_of=organization_type_of,
            first_name=first_name,
            last_name=last_name,
            email=email,
            primary_phone=primary_phone,
            secondary_phone=secondary_phone,
            created_by=request.user,
            created_from=request.client_ip,
            created_from_is_public=request.client_ip_is_routable,
            last_modified_by=request.user,
            last_modified_from=request.client_ip,
            last_modified_from_is_public=request.client_ip_is_routable,
        )
        logger.info("Created member contact.")

        # ------ MEMBER ADDRESS ------ #

        country = validated_data.get('country', None)
        province = validated_data.get('province', None)
        city = validated_data.get('city', None)
        street_number = validated_data.get('street_number', None)
        street_name = validated_data.get('street_name', None)
        apartment_unit = validated_data.get('apartment_unit', None)
        street_type = validated_data.get('street_type', None)
        street_type_other = validated_data.get('street_type_other', None)
        street_direction = validated_data.get(
            'street_direction', MemberAddress.STREET_DIRECTION.NONE)
        postal_code = validated_data.get('postal_code', None)
        member_address = MemberAddress.objects.create(
            member=member,
            country=country,
            province=province,
            city=city,
            street_number=street_number,
            street_name=street_name,
            apartment_unit=apartment_unit,
            street_type=street_type,
            street_type_other=street_type_other,
            street_direction=street_direction,
            postal_code=postal_code,
            created_by=request.user,
            created_from=request.client_ip,
            created_from_is_public=request.client_ip_is_routable,
            last_modified_by=request.user,
            last_modified_from=request.client_ip,
            last_modified_from_is_public=request.client_ip_is_routable,
        )
        logger.info("Created member address.")

        # ------ MEMBER METRICS ------ #

        how_did_you_hear = validated_data.get('how_did_you_hear')
        how_did_you_hear_other = validated_data.get('how_did_you_hear_other',
                                                    None)
        expectation = validated_data.get('expectation')
        expectation_other = validated_data.get('expectation_other', None)
        meaning = validated_data.get('meaning')
        meaning_other = validated_data.get('meaning_other', None)
        gender = validated_data.get('gender')
        willing_to_volunteer = validated_data.get('willing_to_volunteer')
        another_household_member_registered = validated_data.get(
            'another_household_member_registered')
        year_of_birth = validated_data.get('year_of_birth')
        total_household_count = validated_data.get('total_household_count')
        over_18_years_household_count = validated_data.get(
            'over_18_years_household_count')
        organization_employee_count = validated_data.get(
            'organization_employee_count')
        organization_founding_year = validated_data.get(
            'organization_founding_year')
        is_aboriginal = validated_data.get('is_aboriginal', False)
        is_transgender = validated_data.get('is_transgender', False)
        is_visible_minority = validated_data.get('is_visible_minority', False)
        is_disabled_or_has_barriers = validated_data.get(
            'is_disabled_or_has_barriers', False)
        is_over_fifty_five = validated_data.get('is_over_fifty_five', False)

        # DEVELOPERS NOTE:
        # (1) Non-business members cannot have the following fields set,
        #     therefore we need to remove the data if the user submits them.
        if type_of != Member.MEMBER_TYPE_OF.BUSINESS:
            organization_employee_count = None
            organization_founding_year = None

        member_metric = MemberMetric.objects.create(
            member=member,
            how_did_you_hear=how_did_you_hear,
            how_did_you_hear_other=how_did_you_hear_other,
            expectation=expectation,
            expectation_other=expectation_other,
            meaning=meaning,
            meaning_other=meaning_other,
            gender=gender,
            willing_to_volunteer=willing_to_volunteer,
            another_household_member_registered=
            another_household_member_registered,
            year_of_birth=year_of_birth,
            total_household_count=total_household_count,
            over_18_years_household_count=over_18_years_household_count,
            organization_employee_count=organization_employee_count,
            organization_founding_year=organization_founding_year,
            is_aboriginal=is_aboriginal,
            is_transgender=is_transgender,
            is_visible_minority=is_visible_minority,
            is_disabled_or_has_barriers=is_disabled_or_has_barriers,
            is_over_fifty_five=is_over_fifty_five,
        )
        logger.info("Created member metric.")

        # Attached our tags.
        tags = validated_data.get('tags', None)
        if tags is not None:
            if len(tags) > 0:
                member_metric.tags.set(tags)
                logger.info("Attached tag to member metric.")

        # Run the following which will save our searchable content.
        indexed_text = Member.get_searchable_content(member)
        member.indexed_text = Truncator(indexed_text).chars(1023)
        member.save()

        # raise serializers.ValidationError({ # Uncomment when not using this code but do not delete!
        #     "error": "Terminating for debugging purposes only."
        # })

        return member
コード例 #8
0
class DistrictUpdateSerializer(serializers.Serializer):
    slug = serializers.SlugField(write_only=True, )
    type_of = serializers.IntegerField(
        write_only=True,
        required=True,
    )
    name = serializers.CharField(
        write_only=True,
        required=True,
    )
    description = serializers.CharField(
        write_only=True,
        required=False,
    )
    counselor_name = serializers.CharField(
        write_only=True,
        required=False,
    )
    counselor_email = serializers.EmailField(
        write_only=True,
        required=False,
    )
    counselor_phone = serializers.CharField(
        write_only=True,
        required=False,
    )
    website_url = serializers.URLField(
        write_only=True,
        required=False,
        allow_blank=True,
        allow_null=True,
    )
    is_archived = serializers.BooleanField(
        write_only=True,
        required=False,
    )
    facebook_url = serializers.URLField(
        required=False,
        allow_blank=True,
        allow_null=True,
    )

    # REACT-DJANGO UPLOAD | STEP 1 OF 4: We define two string fields required (write-only)
    # for accepting our file uploads.
    upload_content = serializers.CharField(
        write_only=True,
        allow_null=True,
        allow_blank=True,
        required=False,
    )
    upload_filename = serializers.CharField(
        write_only=True,
        allow_null=True,
        allow_blank=True,
        required=False,
    )

    def update(self, instance, validated_data):
        request = self.context.get("request")
        instance.type_of = validated_data.get('type_of')
        instance.description = validated_data.get('description')
        instance.name = validated_data.get('name')
        instance.counselor_name = validated_data.get('counselor_name', None)
        instance.counselor_email = validated_data.get('counselor_email', None)
        instance.counselor_phone = validated_data.get('counselor_phone', None)
        instance.website_url = validated_data.get('website_url', None)
        instance.facebook_url = validated_data.get('facebook_url', None)
        instance.created_by = request.user
        instance.created_from = request.client_ip
        instance.created_from_is_public = request.client_ip_is_routable
        instance.last_modified_by = request.user
        instance.last_modified_from = request.client_ip
        instance.last_modified_from_is_public = request.client_ip_is_routable
        instance.save()
        logger.info("New district was been updated.")

        try:
            # Extract our upload file data
            content = validated_data.get('upload_content', None)
            filename = validated_data.get('upload_filename', None)

            if content and filename:
                if settings.DEBUG:
                    filename = "QA_" + filename  # NOTE: Attach `QA_` prefix if server running in QA mode.
                content_file = get_content_file_from_base64_string(
                    content, filename
                )  # REACT-DJANGO UPLOAD | STEP 3 OF 4: Convert to `ContentFile` type.

                # Create our file.
                private_file = PrivateImageUpload.objects.create(
                    is_archived=False,
                    user=request.user,
                    image_file=
                    content_file,  # REACT-DJANGO UPLOAD | STEP 4 OF 4: When you attack a `ContentImage`, Django handles all file uploading.
                    created_by=request.user,
                    created_from=request.client_ip,
                    created_from_is_public=request.client_ip_is_routable,
                    last_modified_by=request.user,
                    last_modified_from=request.client_ip,
                    last_modified_from_is_public=request.client_ip_is_routable,
                )
                logger.info("Private file was been created.")
                instance.logo_image = private_file
                instance.save()
        except Exception as e:
            print(e)
            private_file = None

        # raise serializers.ValidationError({ # Uncomment when not using this code but do not delete!
        #     "error": "Terminating for debugging purposes only."
        # })

        return instance
コード例 #9
0
class DataMartCommonSerializer(UpdateOrCreateSerializerMixin,
                               CheckPermissionsSerializerMixin,
                               BulkSerializerMixin,
                               serializers.ModelSerializer):
    """
    A simple serializer to convert the data mart items for rendering.
    """
    name = serializers.CharField()
    parent_id = serializers.IntegerField(allow_null=True, required=False)
    slug = serializers.SlugField(max_length=50,
                                 min_length=None,
                                 allow_blank=False)
    path = serializers.CharField(max_length=255,
                                 allow_blank=False,
                                 read_only=True)
    active = serializers.BooleanField(required=False, default=True)
    description = serializers.CharField(required=False,
                                        allow_null=True,
                                        allow_blank=True)
    data_mart_model = serializers.CharField(read_only=True)
    data_mart_url = serializers.SerializerMethodField()
    is_leaf = serializers.SerializerMethodField()
    short_description = serializers.SerializerMethodField()
    parent__slug = serializers.SlugField(max_length=50,
                                         min_length=None,
                                         allow_null=True,
                                         allow_blank=True,
                                         write_only=True,
                                         required=False)

    class Meta:
        fields = '__all__'
        model = DataMartModel
        extra_kwargs = {
            'url': {
                'view_name': 'edw:{}-detail'.format(model._meta.model_name)
            }
        }
        list_serializer_class = DataMartBulkListSerializer
        validators = [DataMartValidator()]
        need_add_lookup_fields_request_methods = True

    def __prepare_validated_data(self, validated_data):
        parent__slug = validated_data.pop('parent__slug', empty)
        if parent__slug != empty:
            if parent__slug is not None:
                try:
                    parent = DataMartModel.objects.get(slug=parent__slug)
                except (ObjectDoesNotExist, MultipleObjectsReturned) as e:
                    raise serializers.ValidationError({'parent__slug': str(e)})
                else:
                    validated_data['parent_id'] = parent.id
            else:
                validated_data['parent_id'] = None
        return validated_data

    def create(self, validated_data):
        validated_data = self.__prepare_validated_data(validated_data)
        instance, is_created = self._update_or_create_instance(
            DataMartModel, self.get_id_attrs(), validated_data)
        return instance

    def update(self, instance, validated_data):
        validated_data = self.__prepare_validated_data(validated_data)
        return super(DataMartCommonSerializer,
                     self).update(instance, validated_data)

    HTML_SNIPPET_CACHE_KEY_PATTERN = 'data_mart:{0}|{1}-{2}-{3}-{4}-{5}'

    def render_html(self, data_mart, postfix):
        """
        Return a HTML snippet containing a rendered summary for this data mart.
        Build a template search path with `postfix` distinction.
        """
        if not self.label:
            msg = "The DataMart Serializer must be configured using a `label` field."
            raise ImproperlyConfigured(msg)
        app_label = data_mart._meta.app_label.lower()
        request = self.context['request']
        cache_key = self.HTML_SNIPPET_CACHE_KEY_PATTERN.format(
            data_mart.id, app_label, self.label, data_mart.data_mart_model,
            postfix, get_language_from_request(request))
        content = cache.get(cache_key)
        if content:
            return mark_safe(content)
        params = [
            (app_label, self.label, data_mart.data_mart_model, postfix),
            (app_label, self.label, 'data_mart', postfix),
            ('edw', self.label, 'data_mart', postfix),
        ]
        try:
            template = select_template(
                ['{0}/data_marts/{1}-{2}-{3}.html'.format(*p) for p in params])
        except TemplateDoesNotExist:
            return SafeText(
                "<!-- no such template: `{0}/data_marts/{1}-{2}-{3}.html` -->".
                format(*params[0]))
        # when rendering emails, we require an absolute URI, so that media can be accessed from
        # the mail client
        absolute_base_uri = request.build_absolute_uri('/').rstrip('/')
        context = {
            'data_mart': data_mart,
            'ABSOLUTE_BASE_URI': absolute_base_uri
        }
        content = strip_spaces_between_tags(
            template.render(context, request).strip())
        cache.set(cache_key, content,
                  edw_settings.CACHE_DURATIONS['data_mart_html_snippet'])
        return mark_safe(content)

    def get_data_mart_url(self, instance):
        return instance.get_absolute_url(request=self.context.get('request'),
                                         format=self.context.get('format'))

    def get_is_leaf(self, instance):
        return instance.is_leaf_node()

    def get_short_description(self, instance):
        if not instance.description:
            return ''
        return mark_safe(
            Truncator(
                Truncator(instance.description).words(
                    10, truncate=" ...")).chars(80, truncate="..."))

    @cached_property
    def request_method(self):
        return getattr(getattr(self.context.get('view'), 'request'), 'method',
                       '')
コード例 #10
0
class RelationShipSerializer(serializers.Serializer):  #pylint: disable=abstract-method
    orig_elements = serializers.ListField(child=serializers.SlugField(),
                                          required=False)
    dest_elements = serializers.ListField(child=serializers.SlugField(),
                                          required=False)
コード例 #11
0
class PrivateFileUploadUpdateSerializer(serializers.ModelSerializer):
    user = serializers.SlugField(required=True,)
    title = serializers.CharField(required=True, allow_null=False,)
    description = serializers.CharField(required=True, allow_null=False,)
    tags = serializers.PrimaryKeyRelatedField(many=True, queryset=Tag.objects.all(), allow_null=True)
    is_archived = serializers.BooleanField(required=True,)
    created_at = serializers.DateTimeField(read_only=True, allow_null=False,)

    # REACT-DJANGO UPLOAD | STEP 1 OF 4: We define two string fields required (write-only)
    # for accepting our file uploads.
    upload_content = serializers.CharField(
        write_only=True,
        allow_null=False,
        required=True,
    )
    upload_filename = serializers.CharField(
        write_only=True,
        allow_null=False,
        required=True,
    )

    # Meta Information.
    class Meta:
        model = PrivateFileUpload
        fields = (
            'user',
            'title',
            'description',
            'tags',
            'is_archived',

            # REACT-DJANGO UPLOAD | STEP 2 OF 4: Define required fields.
            'upload_content',
            'upload_filename',
        )

    @transaction.atomic
    def update(self, instance, validated_data):
        """
        Override the `create` function to add extra functinality.
        """
        user = validated_data.get('user')

        #-----------------------------
        # Create our file.
        #-----------------------------

        # # Extract our upload file data
        # content = validated_data.get('upload_content')
        # filename = validated_data.get('upload_filename')
        # if settings.DEBUG:
        #     filename = "QA_"+filename # NOTE: Attach `QA_` prefix if server running in QA mode.
        # content_file = get_content_file_from_base64_string(content, filename) # REACT-DJANGO UPLOAD | STEP 3 OF 4: Convert to `ContentFile` type.
        #
        # # Create our file.
        # private_file = PrivateFileUpload.objects.create(
        #     title = validated_data.get('title'),
        #     description = validated_data.get('description'),
        #     is_archived = validated_data.get('is_archived'),
        #     associate = associate,
        #     data_file = content_file, # REACT-DJANGO UPLOAD | STEP 4 OF 4: When you attack a `ContentFile`, Django handles all file uploading.
        #     created_by = self.context['created_by'],
        #     created_from = self.context['created_from'],
        #     created_from_is_public = self.context['created_from_is_public'],
        #     last_modified_by = self.context['created_by'],
        #     last_modified_from = self.context['created_from'],
        #     last_modified_from_is_public = self.context['created_from_is_public'],
        # )
        #
        # tags = validated_data.get('tags', None)
        # if tags is not None:
        #     if len(tags) > 0:
        #         private_file.tags.set(tags)
        #
        # # For debugging purposes only.
        # print("Created private file #", private_file)
        #
        # #-----------------------------
        # # Create our `Comment` object.
        # #-----------------------------
        # text = _("A file named \"%(filename)s\" has been uploaded to this associate's record by %(name)s.") % {
        #     'filename': str(filename),
        #     'name': str(self.context['created_by']),
        # }
        # comment = Comment.objects.create(
        #     created_by = self.context['created_by'],
        #     created_from = self.context['created_from'],
        #     created_from_is_public = self.context['created_from_is_public'],
        #     last_modified_by = self.context['created_by'],
        #     last_modified_from = self.context['created_from'],
        #     last_modified_from_is_public = self.context['created_from_is_public'],
        #     text=text
        # )
        # AssociateComment.objects.create(
        #     about=associate,
        #     comment=comment,
        # )
        # print("Created comment #", comment)
        #
        # # Return our validated data.
        # return private_file

        raise serializers.ValidationError({ # Uncomment when not using this code but do not delete!
            "error": "Terminating for debugging purposes only."
        })

        return None
コード例 #12
0
ファイル: serializers.py プロジェクト: ahrav/Edumacation
class ArticleSerializer(serializers.ModelSerializer):
    """serializer for article model"""

    author = ProfileSerializer(read_only=True)
    description = serializers.CharField(required=False, allow_blank=True)
    title = serializers.CharField(
        error_messages={
            "required": "Title is required and can not be left blank",
            "blank": "Title can not be left blank",
        })
    body = serializers.CharField(required=False, allow_blank=True)
    slug = serializers.SlugField(required=False)
    favorited = serializers.SerializerMethodField()
    favoritesCount = serializers.SerializerMethodField(
        method_name="get_favorites_count")
    commentsCount = serializers.SerializerMethodField(
        method_name="get_comments_count")
    tagList = TagRelatedField(many=True, required=False, source="tags")
    createdAt = serializers.SerializerMethodField(method_name="get_created_at")
    updatedAt = serializers.SerializerMethodField(method_name="get_updated_at")

    class Meta:
        model = Article
        fields = (
            "author",
            "body",
            "createdAt",
            "description",
            "favorited",
            "favoritesCount",
            "commentsCount",
            "slug",
            "tagList",
            "title",
            "updatedAt",
            "image",
        )

    def create(self, validated_data):
        author = self.context.get("author", None)
        tags = validated_data.pop("tags", [])

        article = Article.objects.create(author=author, **validated_data)

        for tag in tags:
            article.tags.add(tag)

        return article

    def validate_image(self, image):
        """ensure image extension is valid type"""

        ext = image.name.split(".")[-1].upper()
        if ext not in ["JPG", "JPEG", "PNG"]:
            raise serializers.ValidationError(
                "Please upload correct filetype (JPG, JPEG, PNG)")
        img = image.file
        resized_image = Image.open(img)
        resized_image = resized_image.resize((675, 285), Image.ANTIALIAS)
        output = BytesIO()
        resized_image.save(output, format="JPEG", quality=90)
        output.seek(0)

        return InMemoryUploadedFile(
            output,
            "ImageField",
            image.name,
            "image/jpeg",
            sys.getsizeof(output),
            None,
        )

    def get_created_at(self, instance):
        return instance.created_at.isoformat()

    def get_updated_at(self, instance):
        return instance.updated_at.isoformat()

    def get_favorited(self, instance):
        """return True if article is favorited by user"""
        request = self.context.get("request", None)

        if not request:
            return False

        if not request.user.is_authenticated:
            return False

        return request.user.profile.has_favorited(instance)

    def get_favorites_count(self, instance):
        """return number of times an article has been favorited"""

        return instance.favorited_by.count()

    def get_comments_count(self, instance):
        """return number of comments for an article"""

        return instance.comments.count()
コード例 #13
0
class StaffPromoteOperationSerializer(serializers.Serializer):
    staff = serializers.SlugField(write_only=True, required=True)
    role_id = serializers.IntegerField(
        write_only=True,
        required=True,
    )
    conflict_of_interest_agreement = serializers.BooleanField(
        write_only=True,
        required=True,
    )
    code_of_conduct_agreement = serializers.BooleanField(
        write_only=True,
        required=True,
    )
    confidentiality_agreement = serializers.BooleanField(
        write_only=True,
        required=True,
    )
    police_check_date = serializers.DateField(
        write_only=True,
        required=True,
    )

    @transaction.atomic
    def create(self, validated_data):
        """
        Override the `create` function to add extra functinality.
        """
        slug = validated_data.get('staff')
        staff = Staff.objects.select_for_update().get(user__slug=slug)
        request = self.context.get('request')
        role_id = validated_data.get('role_id')
        conflict_of_interest_agreement = validated_data.get(
            'conflict_of_interest_agreement')
        code_of_conduct_agreement = validated_data.get(
            'code_of_conduct_agreement')
        confidentiality_agreement = validated_data.get(
            'confidentiality_agreement')
        # staff_agreement = validated_data.get('staff_agreement')
        police_check_date = validated_data.get('police_check_date')

        logger.info("Beginning promotion...")

        # Get the text agreement which will be signed.
        conflict_of_interest_agreement = render_to_string(
            'account/conflict_of_interest_agreement/2019_05_01.txt', {})
        code_of_conduct_agreement = render_to_string(
            'account/code_of_conduct_agreement/2019_05_01.txt', {})
        confidentiality_agreement = render_to_string(
            'account/confidentiality_agreement/2019_05_01.txt', {})
        # staff_agreement = render_to_string('account/staff_agreement/2019_05_01.txt', {})

        # Create or update our model.
        staff, created = Staff.objects.update_or_create(
            user=staff.user,
            defaults={
                'user': staff.user,
                'has_signed_conflict_of_interest_agreement': True,
                'conflict_of_interest_agreement':
                conflict_of_interest_agreement,
                'conflict_of_interest_agreement_signed_on': timezone.now(),
                'has_signed_code_of_conduct_agreement': True,
                'code_of_conduct_agreement': code_of_conduct_agreement,
                'code_of_conduct_agreement_signed_on': timezone.now(),
                'has_signed_confidentiality_agreement': True,
                'confidentiality_agreement': confidentiality_agreement,
                'confidentiality_agreement_signed_on': timezone.now(),
                # 'has_signed_staff_agreement': True,
                # 'staff_agreement': staff_agreement,
                # 'staff_agreement_signed_on': timezone.now(),
                'police_check_date': police_check_date,
            })

        # Set the user's role to be a area coordinator after clearing the
        # previous group memberships.
        staff.user.groups.clear()
        staff.user.groups.add(role_id)

        # raise serializers.ValidationError({ # Uncomment when not using this code but do not delete!
        #     "error": "Terminating for debugging purposes only."
        # })

        logger.info("Promoted staff")

        return staff
コード例 #14
0
ファイル: teams.py プロジェクト: nwmoon/unisubs
class TeamUpdateSerializer(TeamSerializer):
    name = serializers.CharField(required=False)
    slug = serializers.SlugField(required=False)
コード例 #15
0
class AlertItemListSerializer(serializers.ModelSerializer):
    device_name = serializers.CharField(read_only=True,
                                        source="instrument.device.name")
    device_slug = serializers.SlugField(read_only=True,
                                        source="instrument.device.slug")
    device_timezone = serializers.SlugField(
        read_only=True, source="instrument.device.timezone")
    device_absolute_url = serializers.SlugField(
        read_only=True, source="instrument.device.get_absolute_url")
    instrument_type = serializers.CharField(
        read_only=True, source="instrument.get_pretty_instrument_type_of")
    instrument_slug = serializers.SlugField(read_only=True,
                                            source="instrument.slug")
    instrument_absolute_url = serializers.SlugField(
        read_only=True, source="instrument.get_absolute_url")
    instrument_unit_of_measure = serializers.CharField(
        read_only=True,
        source="instrument.get_unit_of_measure",
        allow_null=True)
    icon = serializers.CharField(read_only=True, source="get_icon")
    absolute_url = serializers.CharField(read_only=True,
                                         source="get_absolute_url")

    pretty_type_of = serializers.CharField(read_only=True,
                                           source="get_pretty_type_of")
    pretty_state = serializers.CharField(read_only=True,
                                         source="get_pretty_state")
    pretty_condition = serializers.CharField(read_only=True,
                                             source="get_pretty_condition")

    class Meta:
        model = AlertItem
        fields = (
            'type_of',
            'state',
            'condition',
            'pretty_type_of',
            'pretty_state',
            'pretty_condition',
            'device_name',
            'device_slug',
            'device_timezone',
            'device_absolute_url',
            'instrument_type',
            'instrument_slug',
            'instrument_absolute_url',
            'instrument_unit_of_measure',
            'timestamp',
            'value',
            'created_at',
            'icon',
            'slug',
            'absolute_url',
        )

    def setup_eager_loading(cls, queryset):
        """ Perform necessary eager loading of data. """
        queryset = queryset.prefetch_related(
            'instrument',
            'instrument__device',
        )
        return queryset
class InvoiceRetrieveUpdateSerializer(serializers.Serializer):
    state = serializers.CharField(read_only=True, source="get_pretty_state")
    slug = serializers.SlugField(read_only=True)
    absolute_url = serializers.ReadOnlyField(source="get_absolute_url")
    purchased_at = serializers.DateTimeField(read_only=True)
    created_at = serializers.DateTimeField(read_only=True)
    last_modified_at = serializers.DateTimeField(read_only=True)
    due_at = serializers.DateTimeField(read_only=True)
    number = serializers.IntegerField(read_only=True)
    total_before_tax = serializers.FloatField(read_only=True)
    tax = serializers.FloatField(read_only=True)
    tax_percent = serializers.FloatField(read_only=True)
    total_after_tax = serializers.FloatField(read_only=True)
    shipping = serializers.FloatField(read_only=True)
    credit = serializers.FloatField(read_only=True)
    grand_total = serializers.FloatField(read_only=True)

    billing_given_name = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    billing_last_name = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    billing_country = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    billing_region = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    billing_locality = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    billing_postal_code = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    billing_street_address = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    billing_postal_code = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    billing_post_office_box_number = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    billing_email = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    billing_telephone = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    shipping_given_name = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    shipping_last_name = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    shipping_country = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    shipping_region = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    shipping_locality = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    shipping_postal_code = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    shipping_street_address = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    shipping_street_address_extra = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    shipping_postal_code = serializers.CharField(required=False,
                                                 allow_blank=True,
                                                 allow_null=True)
    shipping_post_office_box_number = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    shipping_email = serializers.CharField(
        required=False,
        allow_blank=True,
    )
    shipping_telephone = serializers.CharField(
        required=False,
        allow_blank=True,
    )

    items = InvoiceItemRetrieveUpdateDestroySerializer(read_only=True,
                                                       many=True,
                                                       source="invoice_items")

    # Meta Information.
    class Meta:
        fields = (
            'state',
            'slug',
            'absolute_url',
            'purchased_at',
            'due_at',
            'created_at',
            'last_modified_at',
            'number',
            'total_before_tax',
            'tax',
            'tax_percent',
            'total_after_tax',
            'shipping',
            'credit',
            'grand_total',
            'billing_given_name',
            'billing_last_name',
            'billing_country',
            'billing_region',
            'billing_locality',
            'billing_postal_code',
            'billing_street_address',
            'billing_postal_code',
            'billing_post_office_box_number',
            'billing_email',
            'billing_telephone',
            'shipping_given_name',
            'shipping_last_name',
            'shipping_country',
            'shipping_region',
            'shipping_locality',
            'shipping_postal_code',
            'shipping_street_address',
            'shipping_street_address_extra',
            'shipping_postal_code',
            'shipping_post_office_box_number',
            'shipping_email',
            'shipping_telephone',
            'items',
        )

    def update(self, instance, validated_data):
        """
        Override this function to include extra functionality.
        """
        instance.billing_given_name = validated_data.get(
            'billing_given_name', instance.billing_given_name)
        instance.billing_last_name = validated_data.get(
            'billing_last_name', instance.billing_last_name)
        instance.billing_country = validated_data.get('billing_country',
                                                      instance.billing_country)
        instance.billing_region = validated_data.get('billing_region',
                                                     instance.billing_region)
        instance.billing_locality = validated_data.get(
            'billing_locality', instance.billing_locality)
        instance.billing_postal_code = validated_data.get(
            'billing_postal_code', instance.billing_postal_code)
        instance.billing_street_address = validated_data.get(
            'billing_street_address', instance.billing_street_address)
        instance.billing_postal_code = validated_data.get(
            'billing_postal_code', instance.billing_postal_code)
        instance.billing_post_office_box_number = validated_data.get(
            'billing_post_office_box_number',
            instance.billing_post_office_box_number)
        instance.billing_email = validated_data.get('billing_email',
                                                    instance.billing_email)
        instance.billing_telephone = validated_data.get(
            'billing_telephone', instance.billing_telephone)
        instance.shipping_given_name = validated_data.get(
            'shipping_given_name', instance.shipping_given_name)
        instance.shipping_last_name = validated_data.get(
            'shipping_last_name', instance.shipping_last_name)
        instance.shipping_country = validated_data.get(
            'shipping_country', instance.shipping_country)
        instance.shipping_region = validated_data.get('shipping_region',
                                                      instance.shipping_region)
        instance.shipping_locality = validated_data.get(
            'shipping_locality', instance.shipping_locality)
        instance.shipping_postal_code = validated_data.get(
            'shipping_postal_code', instance.shipping_postal_code)
        instance.shipping_street_address = validated_data.get(
            'shipping_street_address', instance.shipping_street_address)
        instance.shipping_postal_code = validated_data.get(
            'shipping_postal_code', instance.shipping_postal_code)
        instance.shipping_post_office_box_number = validated_data.get(
            'shipping_post_office_box_number',
            instance.shipping_post_office_box_number)
        instance.shipping_email = validated_data.get('shipping_email',
                                                     instance.shipping_email)
        instance.shipping_telephone = validated_data.get(
            'shipping_telephone', instance.shipping_telephone)
        instance.save()
        return validated_data
コード例 #17
0
class AreaCoordinatorRetrieveSerializer(serializers.Serializer):
    # ------ MEMBER ------ #

    slug = serializers.SlugField(
        source="user.slug",
        read_only=True,
    )
    type_of = serializers.IntegerField(
        source="user.member.type_of",
        read_only=True,
    )
    type_of_label = serializers.CharField(
        source="user.member.get_pretty_type_of",
        read_only=True,
        allow_null=True,
    )
    avatar_url = serializers.SerializerMethodField()
    state = serializers.CharField(
        source="user.member.state",
        read_only=True,
    )

    # ------ MEMBER CONTACT ------ #

    is_ok_to_email = serializers.IntegerField(
        source="user.member.contact.is_ok_to_email",
        read_only=True,
    )
    is_ok_to_text = serializers.IntegerField(
        source="user.member.contact.is_ok_to_text",
        read_only=True,
    )
    organization_name = serializers.CharField(
        source="user.member.contact.organization_name",
        read_only=True,
        allow_null=True,
    )
    organization_type_of = serializers.IntegerField(
        source="user.member.contact.organization_type_of",
        read_only=True,
    )
    first_name = serializers.CharField(
        source="user.member.contact.first_name",
        read_only=True,
        allow_null=True,
    )
    last_name = serializers.CharField(
        source="user.member.contact.last_name",
        read_only=True,
        allow_null=True,
    )
    full_name = serializers.SerializerMethodField()
    email = serializers.EmailField(
        source="user.member.contact.email",
        read_only=True,
    )
    primary_phone_e164 = E164PhoneNumberField(
        source="user.member.contact.primary_phone",
        read_only=True,
    )
    primary_phone_national = NationalPhoneNumberField(
        source="user.member.contact.primary_phone",
        read_only=True,
    )
    secondary_phone_e164 = E164PhoneNumberField(
        source="user.member.contact.secondary_phone",
        read_only=True,
    )
    secondary_phone_national = NationalPhoneNumberField(
        source="user.member.contact.secondary_phone",
        read_only=True,
    )

    # ------ MEMBER ADDRESS ------ #

    country = serializers.CharField(
        source="user.member.address.country",
        read_only=True,
    )
    province = serializers.CharField(
        source="user.member.address.province",
        read_only=True,
    )
    city = serializers.CharField(
        source="user.member.address.city",
        read_only=True,
    )
    street_number = serializers.CharField(
        source="user.member.address.street_number",
        read_only=True,
    )
    street_name = serializers.CharField(
        source="user.member.address.street_name",
        read_only=True,
    )
    apartment_unit = serializers.CharField(
        source="user.member.address.apartment_unit",
        read_only=True,
    )
    street_type = serializers.IntegerField(
        source="user.member.address.street_type",
        read_only=True,
    )
    street_type_other = serializers.CharField(
        source="user.member.address.street_type_other",
        read_only=True,
    )
    street_direction = serializers.IntegerField(
        source="user.member.address.street_direction",
        read_only=True,
    )
    postal_code = serializers.CharField(
        source="user.member.address.postal_code",
        read_only=True,
    )
    address = serializers.CharField(
        source="user.member.address.street_address",
        read_only=True,
    )
    google_maps_url = serializers.URLField(
        source="user.member.address.google_maps_url",
        read_only=True,
    )
    position = serializers.SerializerMethodField()

    # ------ MEMBER WATCH ------ #

    #TODO: IMPLEMENT FIELDS.

    # ------ MEMBER METRICS ------ #

    tags = TagListCreateSerializer(
        source="user.member.metric.tags",
        many=True,
        read_only=True,
    )
    how_did_you_hear = serializers.PrimaryKeyRelatedField(
        source="user.member.metric.how_did_you_hear",
        many=False,
        read_only=True,
        allow_null=False,
    )
    how_did_you_hear_other = serializers.CharField(
        source="user.member.metric.how_did_you_hear_other",
        allow_null=True,
        allow_blank=True,
        read_only=True,
    )
    how_did_you_hear_label = serializers.CharField(
        source="user.member.metric.how_did_you_hear.text",
        read_only=True,
        allow_null=True,
    )
    expectation = serializers.PrimaryKeyRelatedField(
        source="user.member.metric.expectation",
        many=False,
        read_only=True,
        allow_null=False,
    )
    expectation_other = serializers.CharField(
        source="user.member.metric.expectation_other",
        allow_null=True,
        allow_blank=True,
        read_only=True,
    )
    expectation_label = serializers.CharField(
        source="user.member.metric.expectation.text",
        read_only=True,
        allow_null=True,
    )
    meaning = serializers.PrimaryKeyRelatedField(
        source="user.member.metric.meaning",
        many=False,
        read_only=True,
        allow_null=False,
    )
    meaning_other = serializers.CharField(
        source="user.member.metric.meaning_other",
        allow_null=True,
        allow_blank=True,
        read_only=True,
    )
    meaning_label = serializers.CharField(
        source="user.member.metric.meaning.text",
        read_only=True,
        allow_null=True,
    )
    gender = serializers.IntegerField(
        source="user.member.metric.gender",
        read_only=True,
    )
    gender_label = serializers.CharField(
        source="user.member.metric.get_pretty_gender",
        read_only=True,
        allow_null=True,
    )
    willing_to_volunteer = serializers.IntegerField(
        source="user.member.metric.willing_to_volunteer",
        read_only=True,
    )
    willing_to_volunteer_label = serializers.CharField(
        source="user.member.metric.get_pretty_willing_to_volunteer",
        read_only=True,
        allow_null=True,
    )
    another_household_member_registered = serializers.BooleanField(
        source="user.member.metric.another_household_member_registered",
        read_only=True,
    )
    year_of_birth = serializers.IntegerField(
        source="user.member.metric.year_of_birth",
        read_only=True,
    )
    total_household_count = serializers.IntegerField(
        source="user.member.metric.total_household_count",
        read_only=True,
    )
    over_18_years_household_count = serializers.IntegerField(
        source="user.member.metric.over_18_years_household_count",
        read_only=True,
    )
    organization_employee_count = serializers.IntegerField(
        source="user.member.metric.organization_employee_count",
        read_only=True,
    )
    organization_founding_year = serializers.IntegerField(
        source="user.member.metric.organization_founding_year",
        read_only=True,
    )

    # ------ AUDITING ------ #

    created_by = serializers.CharField(
        source="created_by.get_full_name",
        allow_null=True,
        read_only=True,
    )
    last_modified_by = serializers.CharField(
        source="last_modified_by.get_full_name",
        allow_null=True,
        read_only=True,
    )

    # ------ FUNCTIONS ------ #

    def get_full_name(self, obj):
        try:
            return obj.user.member.contact.first_name + " " + obj.user.member.contact.last_name
        except Exception as e:
            print(e)
            return None

    def get_avatar_url(self, obj):
        try:
            return obj.user.member.avatar_image.image_file.url
        except Exception as e:
            return None

    def get_position(self, obj):
        return get_arr_from_point(obj.user.member.address.position)
コード例 #18
0
class GetTokenSerializer(serializers.Serializer):
    email = serializers.EmailField()
    confirmation_code = serializers.SlugField()
コード例 #19
0
class StaffDemoteOperationSerializer(serializers.Serializer):
    staff = serializers.SlugField(write_only=True, required=True)
    role_id = serializers.IntegerField(write_only=True, required=True,)
    reason = serializers.ChoiceField(
        write_only=True,
        required=True,
        choices=Staff.DEMOTION_REASON_CHOICES
    )
    reason_other = serializers.CharField(
        write_only=True,
        required=True,
        allow_null=True,
        allow_blank=True,
    )
    role_id = serializers.ChoiceField(
        write_only=True,
        required=True,
        choices=(
            # (SharedGroup.GROUP_MEMBERSHIP., _('Management')),
            (SharedGroup.GROUP_MEMBERSHIP.FRONTLINE_STAFF, _('Frontline')),
            (SharedGroup.GROUP_MEMBERSHIP.ASSOCIATE, _('Associate')),
            (SharedGroup.GROUP_MEMBERSHIP.AREA_COORDINATOR, _('Area Coordinator')),
            (SharedGroup.GROUP_MEMBERSHIP.MEMBER, _('Member')),
        )
    )
    area_coordinator_agreement = serializers.BooleanField(write_only=True, required=True,)
    conflict_of_interest_agreement = serializers.BooleanField(write_only=True, required=True,)
    code_of_conduct_agreement = serializers.BooleanField(write_only=True, required=True,)
    confidentiality_agreement = serializers.BooleanField(write_only=True, required=True,)
    associate_agreement = serializers.BooleanField(write_only=True, required=True,)
    staff_agreement = serializers.BooleanField(write_only=True, required=True,)
    police_check_date = serializers.DateField(write_only=True, required=True,)

    def validate(self, dirty_data):
        """
        Override the validation code to add additional functionionality.
        """
        slug = dirty_data.get('staff')
        staff = Staff.objects.select_for_update().get(user__slug=slug)
        if staff.user.role_id != SharedGroup.GROUP_MEMBERSHIP.MANAGER and staff.user.role_id != SharedGroup.GROUP_MEMBERSHIP.FRONTLINE_STAFF:
            raise serializers.ValidationError(_("You cannot demote because this user is not staff!"))
        return dirty_data


    @transaction.atomic
    def create(self, validated_data):
        """
        Override the `create` function to add extra functinality.
        """
        slug = validated_data.get('staff')
        staff = Staff.objects.select_for_update().get(user__slug=slug)
        request = self.context.get('request')
        role_id = int(validated_data.get('role_id'))
        reason = int(validated_data.get('reason'))
        reason_other = validated_data.get('reason_other')
        area_coordinator_agreement = validated_data.get('area_coordinator_agreement')
        conflict_of_interest_agreement = validated_data.get('conflict_of_interest_agreement')
        code_of_conduct_agreement = validated_data.get('code_of_conduct_agreement')
        confidentiality_agreement = validated_data.get('confidentiality_agreement')
        police_check_date = validated_data.get('police_check_date')

        #---------------------------
        # Reason for demotion.
        #---------------------------

        # Update demotion reason.
        staff.demotion_reason = reason
        staff.demotion_reason_other = reason_other
        staff.last_modified_by = request.user
        staff.last_modified_from = request.client_ip
        staff.last_modified_from_is_public = request.client_ip_is_routable
        staff.save()

        #---------------------------
        # Adjust group membership.
        #---------------------------

        # Set the user's role to be a area coordinator after clearing the
        # previous group memberships.
        staff.user.groups.clear()
        staff.user.groups.add(role_id)

        #---------------------------
        # Attach our comment.
        #---------------------------
        text = _("Demoted staff by %(name)s.") % {
            'name': str(request.user),
        }
        comment = Comment.objects.create(
            created_by=request.user,
            last_modified_by=request.user,
            text=text,
            created_from = request.client_ip,
            created_from_is_public = request.client_ip_is_routable
        )
        StaffComment.objects.create(
            staff=staff,
            comment=comment,
        )

        #---------------------------
        # Adjust our profile.
        #---------------------------
        conflict_of_interest_agreement = render_to_string('account/conflict_of_interest_agreement/2019_05_01.txt', {})
        code_of_conduct_agreement = render_to_string('account/code_of_conduct_agreement/2019_05_01.txt', {})
        confidentiality_agreement = render_to_string('account/confidentiality_agreement/2019_05_01.txt', {})
        if role_id == SharedGroup.GROUP_MEMBERSHIP.AREA_COORDINATOR:
            area_coordinator_agreement = render_to_string('account/area_coordinator_agreement/2019_05_01.txt', {})
            AreaCoordinator.objects.update_or_create(
                user=staff.user,
                defaults={
                    'user': staff.user,
                    'has_signed_area_coordinator_agreement': True,
                    'area_coordinator_agreement': area_coordinator_agreement,
                    'area_coordinator_agreement_signed_on': timezone.now(),
                    'has_signed_conflict_of_interest_agreement': True,
                    'conflict_of_interest_agreement': conflict_of_interest_agreement,
                    'conflict_of_interest_agreement_signed_on': timezone.now(),
                    'has_signed_code_of_conduct_agreement': True,
                    'code_of_conduct_agreement': code_of_conduct_agreement,
                    'code_of_conduct_agreement_signed_on': timezone.now(),
                    'has_signed_confidentiality_agreement': True,
                    'confidentiality_agreement': confidentiality_agreement,
                    'confidentiality_agreement_signed_on': timezone.now(),
                    'police_check_date': police_check_date,
                    'created_by': request.user,
                    'created_from': request.client_ip,
                    'created_from_is_public': request.client_ip_is_routable,
                    'last_modified_by': request.user,
                    'last_modified_from': request.client_ip,
                    'last_modified_from_is_public': request.client_ip_is_routable,
                }
            )
        elif role_id == SharedGroup.GROUP_MEMBERSHIP.ASSOCIATE:
            associate_agreement = render_to_string('account/associate_agreement/2019_05_01.txt', {})
            Associate.objects.update_or_create(
                user=staff.user,
                defaults={
                    'user': staff.user,
                    'has_signed_conflict_of_interest_agreement': True,
                    'conflict_of_interest_agreement': conflict_of_interest_agreement,
                    'conflict_of_interest_agreement_signed_on': timezone.now(),
                    'has_signed_code_of_conduct_agreement': True,
                    'code_of_conduct_agreement': code_of_conduct_agreement,
                    'code_of_conduct_agreement_signed_on': timezone.now(),
                    'has_signed_confidentiality_agreement': True,
                    'confidentiality_agreement': confidentiality_agreement,
                    'confidentiality_agreement_signed_on': timezone.now(),
                    'has_signed_associate_agreement': True,
                    'associate_agreement': associate_agreement,
                    'associate_agreement_signed_on': timezone.now(),
                    'police_check_date': police_check_date,
                }
            )
        elif role_id == SharedGroup.GROUP_MEMBERSHIP.MEMBER:
            pass


        # raise serializers.ValidationError({ # Uncomment when not using this code but do not delete!
        #     "error": "Terminating for debugging purposes only."
        # })

        logger.info("Demoted staff")

        return staff
コード例 #20
0
class ProductionCreateSerializer(serializers.Serializer):
    name = serializers.CharField(required=True, allow_blank=False, allow_null=False)
    description = serializers.CharField(required=True, allow_blank=False, allow_null=False)
    is_commercial = serializers.BooleanField(required=False)
    device_slug = serializers.SlugField(required=True, allow_blank=False, allow_null=False)
    environment = serializers.IntegerField(required=True)
    type_of = serializers.IntegerField(required=True)
    type_of_other = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    grow_system = serializers.IntegerField(required=True)
    grow_system_other = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    has_day_and_night_cycle = serializers.BooleanField(required=False)
    day_starts_at = serializers.TimeField(required=False, allow_null=True,)
    day_finishes_at = serializers.TimeField(required=False, allow_null=True,)
    plants_array = serializers.JSONField(required=True)
    fish_array = serializers.JSONField(required=True)
    inspections_start_at = serializers.DateTimeField(required=True, allow_null=False,)
    inspection_frequency = serializers.IntegerField(required=True, allow_null=False)
    yellow_below_value = serializers.FloatField(required=False, allow_null=True)
    orange_below_value = serializers.FloatField(required=False, allow_null=True)
    red_below_value = serializers.FloatField(required=True, allow_null=False)
    red_alert_delay_in_seconds = serializers.IntegerField(required=True, allow_null=False)
    orange_alert_delay_in_seconds = serializers.IntegerField(required=False, allow_null=False)
    yellow_alert_delay_in_seconds = serializers.IntegerField(required=False, allow_null=False)

    class Meta:
        model = Production
        fields = (
            'name',
            'description',
            'is_commercial',
            'device_slug',
            'environment',
            'type_of',
            'type_of_other',
            'grow_system',
            'grow_system_other',
            'has_day_and_night_cycle',
            'day_starts_at',
            'day_finishes_at',
            'plants_array',
            'fish_array',
            'inspections_start_at',
            'inspection_frequency',
            'yellow_below_value',
            'orange_below_value',
            'red_below_value',
            'red_alert_delay_in_seconds',
            'orange_alert_delay_in_seconds',
            'yellow_alert_delay_in_seconds'
        )

    def validate_device_slug(self, value):
        if not Device.objects.filter(slug=value, user=self.context['authenticated_by']).exists():
            raise exceptions.ValidationError(_('Device does not exist for this device.'))
        return value

    def validate_grow_system_other(self, value):
        if self.context['grow_system'] == Production.GROW_SYSTEM.OTHER_SYSTEM:
            if value == None or value == '':
                raise exceptions.ValidationError(_('Please fill in this field.'))
        return value

    def validate_type_of_other(self, value):
        if self.context['type_of'] == Production.TYPE_OF.OTHER:
            if value == None or value == '':
                raise exceptions.ValidationError(_('Please fill in this field.'))
        return value

    def create(self, validated_data):
        # Get our validated data and context data.
        name = validated_data.get('name', None)
        description = validated_data.get('description', None)
        is_commercial = validated_data.get('is_commercial', False)
        device_slug = validated_data.get('device_slug', None)
        authenticated_by = self.context['authenticated_by']
        authenticated_from = self.context['authenticated_from']
        authenticated_from_is_public = self.context['authenticated_from_is_public']
        environment = validated_data.get('environment', None)
        type_of = validated_data.get('type_of', None)
        type_of_other = validated_data.get('type_of_other', None)
        grow_system = validated_data.get('grow_system', None)
        grow_system_other = validated_data.get('grow_system_other', None)
        has_day_and_night_cycle = validated_data.get('has_day_and_night_cycle', None)
        day_starts_at = validated_data.get('day_starts_at', None)
        day_finishes_at = validated_data.get('day_finishes_at', None)
        plants_array = validated_data.get('plants_array', [])
        fish_array = validated_data.get('fish_array', [])

        device = Device.objects.get(slug=device_slug)

        inspections_start_at = validated_data.get('inspections_start_at', None)
        inspection_frequency = validated_data.get('inspection_frequency', None)
        yellow_below_value = validated_data.get('yellow_below_value', None)
        orange_below_value = validated_data.get('orange_below_value', None)
        red_below_value = validated_data.get('red_below_value', None)
        red_alert_delay_in_seconds = validated_data.get('red_alert_delay_in_seconds', None)
        orange_alert_delay_in_seconds = validated_data.get('orange_alert_delay_in_seconds', None)
        yellow_alert_delay_in_seconds = validated_data.get('yellow_alert_delay_in_seconds', None)

        production = Production.objects.create(
            user=authenticated_by,
            device=device,
            name=name,
            description=description,
            is_commercial=is_commercial,
            environment=environment,
            type_of=type_of,
            type_of_other=type_of_other,
            grow_system=grow_system,
            grow_system_other=grow_system_other,
            started_at=timezone.now(),
            state=Production.PRODUCTION_STATE.OPERATING,
            has_day_and_night_cycle=has_day_and_night_cycle,
            day_starts_at=day_starts_at,
            day_finishes_at=day_finishes_at,
            created_by=authenticated_by,
            created_from=authenticated_from,
            created_from_is_public=authenticated_from_is_public,
            last_modified_by=authenticated_by,
            last_modified_from=authenticated_from,
            last_modified_from_is_public=authenticated_from_is_public,
            inspections_start_at=inspections_start_at,
            inspection_frequency=inspection_frequency,
            yellow_below_value=yellow_below_value,
            orange_below_value=orange_below_value,
            red_below_value=red_below_value,
            red_alert_delay_in_seconds=red_alert_delay_in_seconds,
            orange_alert_delay_in_seconds=orange_alert_delay_in_seconds,
            yellow_alert_delay_in_seconds=yellow_alert_delay_in_seconds,
        )

        # Generate the next inspection date and attach it to the production.
        production.next_inspection_at = production.generate_next_inspection_datetime()
        production.save()

        # Save our plants.
        for plant in plants_array:
            data_sheet = CropDataSheet.objects.filter(slug=plant['plant_slug']).first()
            substrate = CropSubstrate.objects.filter(slug=plant['substrate_slug']).first()
            stage = CropLifeCycleStage.objects.filter(slug=plant['stage_slug']).first()
            production_crop = ProductionCrop.objects.create(
                production=production,
                stage=stage,
                data_sheet=data_sheet,
                data_sheet_other=plant.get('plant_other', None),
                variety=plant.get('variety', None),
                quantity=plant['quantity'],
                substrate=substrate,
                substrate_other=plant.get('substrate_other', None),
                type_of=ProductionCrop.TYPE_OF.PLANT
            )

        # Save our fish.
        for fish in fish_array:
            data_sheet = CropDataSheet.objects.filter(slug=fish['fish_slug']).first()
            substrate = CropSubstrate.objects.filter(slug=fish['substrate_slug']).first()
            stage = CropLifeCycleStage.objects.filter(slug=fish['stage_slug']).first()
            production_crop = ProductionCrop.objects.create(
                production=production,
                stage=stage,
                data_sheet=data_sheet,
                data_sheet_other=fish.get('fish_other', None),
                quantity=fish['quantity'],
                substrate=substrate,
                substrate_other=fish.get('substrate_other', None),
                type_of=ProductionCrop.TYPE_OF.FISHSTOCK
            )

        # DEVELOPERS NOTES:
        # (1) This is  a "Serializer" and not "ModelSerializer" as a result we
        #     will attach the object we created in this serializer.
        # (2) In the output, you can get the object we created.
        validated_data['slug'] = production.slug
        validated_data['production'] = production # ATTACH OBJECT WE CREATED IN THIS SERIALIZER.
        return validated_data
コード例 #21
0
class ItemTypeListCreateSerializer(serializers.Serializer):
    slug = serializers.SlugField(read_only=True, )
    category = serializers.IntegerField(
        required=True,
        allow_null=False,
    )
    category_label = serializers.CharField(
        read_only=True,
        source='get_category_label',
    )
    text = serializers.CharField(
        required=True,
        allow_blank=False,
        allow_null=False,
        validators=[UniqueValidator(queryset=ItemType.objects.all(), )],
    )
    description = serializers.CharField(
        required=True,
        allow_blank=False,
        allow_null=False,
    )
    is_archived = serializers.BooleanField(read_only=True)

    # ------ AUDITING ------ #
    created_at = serializers.DateTimeField(
        read_only=True,
        allow_null=False,
    )
    last_modified_at = serializers.DateTimeField(
        read_only=True,
        allow_null=False,
    )

    def create(self, validated_data):
        """
        Override the `create` function to add extra functinality.
        """
        request = self.context.get("request")
        category = validated_data.get('category')
        text = validated_data.get('text')
        description = validated_data.get('description')

        # Create the district.
        item_type = ItemType.objects.create(
            description=description,
            text=text,
            category=category,
            created_by=request.user,
            created_from=request.client_ip,
            created_from_is_public=request.client_ip_is_routable,
            last_modified_by=request.user,
            last_modified_from=request.client_ip,
            last_modified_from_is_public=request.client_ip_is_routable,
        )

        logger.info("New item_type was been created.")

        # print(private_file)
        # print("\n")

        # raise serializers.ValidationError({ # Uncomment when not using this code but do not delete!
        #     "error": "Terminating for debugging purposes only."
        # })

        return item_type
コード例 #22
0
class CheckoutRequestSerializer(serializers.Serializer):
    bike = serializers.SlugField()
コード例 #23
0
class ProblemSetSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField()  # defined explicitly to make it writable
    section = serializers.CharField(required=False) # defined explicitly to make it writable
    name = serializers.SlugField(validators=[])
    parent = serializers.SlugRelatedField(
        slug_field='name',
        many=False,
        required=False,
        queryset=ProblemSet.objects.all())
    #content = ContentSerializer(read_only=True, required=False)
    setting = SettingSerializer(required=False)
    parts = serializers.SlugRelatedField(
        slug_field='name',
        many=True,
        queryset=ProblemSet.objects.all(),
        default=list)
    tasks = serializers.SlugRelatedField(
        slug_field='name',
        many=True,
        queryset=Task.objects.all(),
        default=list)

    class Meta:
        model = ProblemSet
        fields = (
            'id', 'name', 'granularity', 'section', 'level', 'order',
            'setting', 'parent', 'parts', 'tasks')
        list_serializer_class = ProblemSetListSerializer

    def create(self, validated_data):
        # After validation, tasks and parts are already DB entities, not names.
        tasks = validated_data.pop('tasks', None)
        parts = validated_data.pop('parts', None)
        ps = ProblemSet.objects.create(**validated_data)
        if tasks:
            ps.set_tasks(tasks)
        if parts:
            ps.set_parts(parts)
        return ps
        #task_names = validated_data.pop('tasks', None)
        #part_names = validated_data.pop('parts', None)
        #ps = ProblemSet.objects.create(**validated_data)
        #if task_names:
        #    tasks = [Task.objects.get(name=name) for name in task_names]
        #    ps.tasks.set(tasks)
        #if part_names:
        #    parts = [ProblemSet.objects.get(name=name) for name in part_names]
        #    ps.parts.set(parts)
        #return ps

    def update(self, instance, validated_data):
        instance.refresh_from_db()
        instance.name = validated_data.get('name', instance.name)
        instance.section = validated_data.get('section', instance.section)
        instance.granularity = validated_data.get(
            'granularity', instance.granularity)
        instance.setting = validated_data.get('setting', instance.setting)
        task_names = validated_data.pop('tasks', None)
        part_names = validated_data.pop('parts', None)
        instance.save()
        if task_names:
            tasks = [Task.objects.get(name=name) for name in task_names]
            instance.set_tasks(tasks)
        if part_names:
            parts = [ProblemSet.objects.get(name=name) for name in part_names]
            # TODO: Only squeeze sections once after the complete list
            # of PS is serialized.
            instance.set_parts(parts, squeeze_sections=True)
        return instance
コード例 #24
0
class ReportDamageRequestSerializer(serializers.Serializer):
    bike = serializers.SlugField()
    damage_type = serializers.SlugField()
    comments = serializers.CharField()
    critical = serializers.BooleanField()
コード例 #25
0
class TeamUpdateSerializer(TeamSerializer):
    name = serializers.CharField(required=False)
    slug = serializers.SlugField(required=False)
    type = MappedChoiceField(source='workflow_type',
                             read_only=True,
                             choices=TeamWorkflow.get_api_choices())
コード例 #26
0
class LockControlSerializer(serializers.Serializer):
    bike = serializers.SlugField()
    command = serializers.ChoiceField(['lock', 'unlock'])
コード例 #27
0
class BookSerializer(PageSerializer):
    slug = serializers.SlugField(source='get_slug')

    class Meta:
        model = Book
        fields = Book.api_fields
コード例 #28
0
class ArticleSerializer(serializers.ModelSerializer):

    author = ProfileSerializer(read_only=True)
    description = serializers.CharField(required=False)
    slug = serializers.SlugField(required=False)

    favorited = serializers.SerializerMethodField()
    favoritesCount = serializers.SerializerMethodField(
        method_name='get_favorites_count')

    image = serializers.SerializerMethodField()

    tagList = TagRelatedField(many=True, required=False, source='tags')

    createdAt = serializers.SerializerMethodField(method_name='get_created_at')
    updatedAt = serializers.SerializerMethodField(method_name='get_updated_at')

    class Meta:
        model = Article
        fields = (
            'author',
            'body',
            'image',
            'createdAt',
            'description',
            'favorited',
            'favoritesCount',
            'tagList',
            'slug',
            'title',
            'updatedAt',
        )

    def create(self, validated_data):
        author = self.context.get('author', None)
        tags = validated_data.pop('tags', [])

        article = Article.objects.create(author=author, **validated_data)
        for tag in tags:
            article.tags.add(tag)

        return article

    def get_created_at(self, instance):
        return instance.created_at.isoformat()

    def get_favorited(self, instance):
        request = self.context.get('request', None)

        if request is None:
            return False

        if not request.user.is_authenticated:
            return False

        return request.user.profile.has_favorited(instance)

    def get_favorites_count(self, instance):
        return instance.favorited_by.count()

    def get_updated_at(self, instance):
        return instance.updated_at.isoformat()

    def get_image(self, obj):
        print(obj)
        if obj.image:
            return obj.image

        return 'https://static.productionready.io/images/smiley-cyrus.jpg'
コード例 #29
0
ファイル: serializers.py プロジェクト: teppi210/rengorum
class UserCreateSerializer(serializers.ModelSerializer):
    # A field from the user's profile:
    username = serializers.SlugField(
        min_length=4,
        max_length=32,
        help_text=_(
            'Required. 4-32 characters. Letters, numbers, underscores or hyphens only.'
        ),
        validators=[UniqueValidator(
            queryset=User.objects.all(),
            message='has already been taken by other user'
        )],
        required=True
    )
    password = serializers.CharField(
        min_length=4,
        max_length=32,
        write_only=True,
        help_text=_(
            'Required. 4-32 characters.'
        ),
        required=True
    )
    email = serializers.EmailField(
        required=True,
        validators=[UniqueValidator(
            queryset=User.objects.all(),
            message='has already been taken by other user'
        )]
    )
    bio = serializers.CharField(source='profile.bio', allow_blank=True, default='')
    name = serializers.CharField(
        source='profile.name',
        allow_blank=True,
        default='',
        max_length=32
    )
    avatar = serializers.URLField(source='profile.avatar', allow_blank=True, default='')
    status = serializers.CharField(
    	source='profile.status',
    	allow_blank=True,
    	max_length=16,
        min_length=0,
        default=''
    )

    class Meta:
        model = User
        fields = (
            'username',
            'name',
            'email',
            'password',
            'bio',
            'avatar',
            'status'
        )

    def create(self, validated_data):
        profile_data = validated_data.pop('profile', None)
        username = validated_data['username']
        email = validated_data['email']
        password = validated_data['password']
        user = User(
                username = username,
                email = email
        )
        user.set_password(password)
        user.save()

        avatar = profile_data.get('avatar') or None
        if not avatar:
            avatar = 'http://api.adorable.io/avatar/200/' + username
        profile = UserProfile(
            user = user,
            bio = profile_data.get('bio', ''),
            avatar = avatar,
            name = profile_data.get('name', ''),
            status = profile_data.get('status', 'Member')
        )
        profile.save()
        return user
コード例 #30
0
class AssociateListSerializer(serializers.Serializer):
    type_of = serializers.IntegerField(
        source="user.member.type_of",
        read_only=True,
    )
    organization_name = serializers.CharField(
        allow_blank=False,
        validators=[],
        source="user.member.contact.organization_name",
        read_only=True,
    )
    organization_type_of = serializers.IntegerField(
        read_only=True,
        allow_null=True,
        source="user.member.contact.organization_type_of",
    )
    first_name = serializers.CharField(
        read_only=True,
        allow_blank=False,
        validators=[],
        source="user.member.contact.first_name",
    )
    last_name = serializers.CharField(
        read_only=True,
        allow_blank=False,
        validators=[],
        source="user.member.contact.last_name",
    )
    primary_phone_e164 = E164PhoneNumberField(
        allow_null=False,
        read_only=True,
        source="user.member.contact.primary_phone",
    )
    primary_phone_national = NationalPhoneNumberField(
        allow_null=False,
        read_only=True,
        source="user.member.contact.primary_phone",
    )
    email = serializers.EmailField(
        read_only=True,
        allow_blank=False,
        validators=[],
        source="user.member.contact.email",
    )
    slug = serializers.SlugField(
        read_only=True,
        allow_blank=False,
        validators=[],
        source="user.slug",
    )
    street_address = serializers.CharField(
        read_only=True,
        allow_blank=False,
        validators=[],
        source="user.member.address.street_address",
    )
    country = serializers.CharField(
        read_only=True,
        allow_blank=False,
        validators=[],
        source="user.member.address.country",
    )
    province = serializers.CharField(
        read_only=True,
        allow_blank=False,
        validators=[],
        source="user.member.address.province",
    )
    city = serializers.CharField(
        read_only=True,
        allow_blank=False,
        validators=[],
        source="user.member.address.city",
    )
    postal_code = serializers.CharField(
        read_only=True,
        allow_blank=False,
        validators=[],
        source="user.member.address.postal_code",
    )
    state = serializers.CharField(
        read_only=True,
        source="user.member.state",
    )

    def setup_eager_loading(cls, queryset):
        """ Perform necessary eager loading of data. """
        queryset = queryset.prefetch_related('user', 'user__groups',
                                             'user__member__contact',
                                             'user__member__address',
                                             'user__member__metric',
                                             'created_by', 'last_modified_by')
        return queryset