• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python models.ContactGroup类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中temba.contacts.models.ContactGroup的典型用法代码示例。如果您正苦于以下问题:Python ContactGroup类的具体用法?Python ContactGroup怎么用?Python ContactGroup使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ContactGroup类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_groups

    def test_groups(self):
        url = reverse('api.v2.groups')

        self.assertEndpointAccess(url)

        customers = ContactGroup.get_or_create(self.org, self.admin, "Customers")
        developers = ContactGroup.get_or_create(self.org, self.admin, "Developers")
        ContactGroup.get_or_create(self.org2, self.admin2, "Spammers")

        developers.update_contacts(self.admin, [self.frank], add=True)

        # no filtering
        with self.assertNumQueries(NUM_BASE_REQUEST_QUERIES + 3):
            response = self.fetchJSON(url)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json['next'], None)
        self.assertEqual(response.json['results'], [
            {'uuid': developers.uuid, 'name': "Developers", 'count': 1},
            {'uuid': customers.uuid, 'name': "Customers", 'count': 0}
        ])

        # filter by UUID
        response = self.fetchJSON(url, 'uuid=%s' % customers.uuid)
        self.assertEqual(response.json['results'], [{'uuid': customers.uuid, 'name': "Customers", 'count': 0}])
开发者ID:churcho,项目名称:rapidpro,代码行数:25,代码来源:test_v2.py


示例2: test_groups

    def test_groups(self):
        url = reverse('api.v2.groups')

        self.assertEndpointAccess(url)

        customers = self.create_group("Customers", [self.frank])
        developers = self.create_group("Developers", query="isdeveloper = YES")

        # group belong to other org
        ContactGroup.get_or_create(self.org2, self.admin2, "Spammers")

        # no filtering
        with self.assertNumQueries(NUM_BASE_REQUEST_QUERIES + 3):
            response = self.fetchJSON(url)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json['next'], None)
        self.assertEqual(response.json['results'], [
            {'uuid': developers.uuid, 'name': "Developers", 'query': "isdeveloper = YES", 'count': 0},
            {'uuid': customers.uuid, 'name': "Customers", 'query': None, 'count': 1}
        ])

        # filter by UUID
        response = self.fetchJSON(url, 'uuid=%s' % customers.uuid)
        self.assertResultsByUUID(response, [customers])
开发者ID:JediKoder,项目名称:rapidpro,代码行数:25,代码来源:test_v2.py


示例3: validate_groups

    def validate_groups(self, value):
        if value is not None:
            self.group_objs = []
            for name in value:
                if not ContactGroup.is_valid_name(name):
                    raise serializers.ValidationError(_("Invalid group name: '%s'") % name)
                self.group_objs.append(ContactGroup.get_or_create(self.org, self.user, name))

        return value
开发者ID:teehamaral,项目名称:rapidpro,代码行数:9,代码来源:serializers.py


示例4: clean

        def clean(self, value):
            if value.startswith("[_NEW_]"):
                value = value[7:]

                # we must get groups for this org only
                group = ContactGroup.get_user_group(self.user.get_org(), value)
                if not group:
                    group = ContactGroup.create_static(self.user.get_org(), self.user, name=value)
                return group

            return super(RegisterTriggerForm.AddNewGroupChoiceField, self).clean(value)
开发者ID:Ilhasoft,项目名称:rapidpro,代码行数:11,代码来源:views.py


示例5: create_group

    def create_group(self, name, contacts=(), query=None):
        if contacts and query:
            raise ValueError("Can't provide contact list for a dynamic group")

        if query:
            return ContactGroup.create_dynamic(self.org, self.user, name, query=query)
        else:
            group = ContactGroup.create_static(self.org, self.user, name)
            if contacts:
                group.contacts.add(*contacts)
            return group
开发者ID:ianjuma,项目名称:rapidpro,代码行数:11,代码来源:tests.py


示例6: clean

        def clean(self, value):
            if value.startswith("[_NEW_]"):  # pragma: needs cover
                value = value[7:]

                # we must get groups for this org only
                group = ContactGroup.get_user_group(self.user.get_org(), value)
                if not group:
                    group = ContactGroup.create_static(self.user.get_org(), self.user, name=value)
                return group

            return super().clean(value)
开发者ID:mxabierto,项目名称:rapidpro,代码行数:11,代码来源:views.py


示例7: __init__

    def __init__(self, *args, **kwargs):
        self.user = kwargs["user"]
        del kwargs["user"]

        super().__init__(*args, **kwargs)
        self.fields["group"].initial = self.instance.group
        self.fields["group"].queryset = ContactGroup.get_user_groups(self.user.get_org(), ready_only=False)
开发者ID:mxabierto,项目名称:rapidpro,代码行数:7,代码来源:views.py


示例8: clean_name

    def clean_name(self):
        data = self.cleaned_data['name'].strip()

        if not ContactGroup.is_valid_name(data):
            raise forms.ValidationError("Group name must not be blank or begin with + or -")

        return data
开发者ID:austiine04,项目名称:rapidpro,代码行数:7,代码来源:views.py


示例9: test_campaigns

    def test_campaigns(self):
        url = reverse('api.v2.campaigns')

        self.assertEndpointAccess(url)

        reporters = self.create_group("Reporters", [self.joe, self.frank])
        campaign1 = Campaign.create(self.org, self.admin, "Reminders #1", reporters)
        campaign2 = Campaign.create(self.org, self.admin, "Reminders #2", reporters)

        # create campaign for other org
        spammers = ContactGroup.get_or_create(self.org2, self.admin2, "Spammers")
        Campaign.create(self.org2, self.admin2, "Cool stuff", spammers)

        # no filtering
        with self.assertNumQueries(NUM_BASE_REQUEST_QUERIES + 2):
            response = self.fetchJSON(url)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json['next'], None)
        self.assertResultsByUUID(response, [campaign2, campaign1])
        self.assertEqual(response.json['results'][0], {
            'uuid': campaign2.uuid,
            'name': "Reminders #2",
            'group': {'uuid': reporters.uuid, 'name': "Reporters"},
            'created_on': format_datetime(campaign2.created_on)
        })

        # filter by UUID
        response = self.fetchJSON(url, 'uuid=%s' % campaign1.uuid)
        self.assertResultsByUUID(response, [campaign1])
开发者ID:JediKoder,项目名称:rapidpro,代码行数:30,代码来源:test_v2.py


示例10: import_triggers

    def import_triggers(cls, exported_json, org, user, same_site=False):
        """
        Import triggers from our export file
        """
        from temba.orgs.models import EARLIEST_IMPORT_VERSION
        if exported_json.get('version', 0) < EARLIEST_IMPORT_VERSION:
            raise ValueError(_("Unknown version (%s)" % exported_json.get('version', 0)))

        # first things first, let's create our groups if necesary and map their ids accordingly
        if 'triggers' in exported_json:
            for trigger_spec in exported_json['triggers']:

                # resolve our groups
                groups = []
                for group_spec in trigger_spec['groups']:

                    group = None

                    if same_site:
                        group = ContactGroup.user_groups.filter(org=org, pk=group_spec['id']).first()

                    if not group:
                        group = ContactGroup.user_groups.filter(org=org, name=group_spec['name']).first()

                    if not group:
                        group = ContactGroup.create(org, user, group_spec['name'])

                    if not group.is_active:
                        group.is_active = True
                        group.save()

                    groups.append(group)

                flow = Flow.objects.get(org=org, pk=trigger_spec['flow']['id'])

                # see if that trigger already exists
                trigger = Trigger.objects.filter(org=org, trigger_type=trigger_spec['trigger_type'])

                if trigger_spec['keyword']:
                    trigger = trigger.filter(keyword__iexact=trigger_spec['keyword'])

                if groups:
                    trigger = trigger.filter(groups__in=groups)

                trigger = trigger.first()

                channel = trigger_spec.get('channel', None)  # older exports won't have a channel

                if trigger:
                    trigger.is_archived = False
                    trigger.flow = flow
                    trigger.save()
                else:
                    trigger = Trigger.objects.create(org=org, trigger_type=trigger_spec['trigger_type'],
                                                     keyword=trigger_spec['keyword'], flow=flow,
                                                     created_by=user, modified_by=user,
                                                     channel=channel)

                    for group in groups:
                        trigger.groups.add(group)
开发者ID:thierhost,项目名称:rapidpro,代码行数:60,代码来源:models.py


示例11: get_context_data

    def get_context_data(self, **kwargs):
        org = self.request.user.get_org()
        counts = ContactGroup.get_system_group_counts(org)

        # if there isn't a search filtering the queryset, we can replace the count function with a quick cache lookup to
        # speed up paging
        if hasattr(self, 'system_group') and 'search' not in self.request.REQUEST:
            self.object_list.count = lambda: counts[self.system_group]

        context = super(ContactListView, self).get_context_data(**kwargs)

        folders = [dict(count=counts[ContactGroup.TYPE_ALL], label=_("All Contacts"), url=reverse('contacts.contact_list')),
                   dict(count=counts[ContactGroup.TYPE_FAILED], label=_("Failed"), url=reverse('contacts.contact_failed')),
                   dict(count=counts[ContactGroup.TYPE_BLOCKED], label=_("Blocked"), url=reverse('contacts.contact_blocked'))]

        groups_qs = ContactGroup.user_groups.filter(org=org, is_active=True).select_related('org')
        groups_qs = groups_qs.extra(select={'lower_group_name': 'lower(contacts_contactgroup.name)'}).order_by('lower_group_name')
        groups = [dict(pk=g.pk, label=g.name, count=g.get_member_count(), is_dynamic=g.is_dynamic) for g in groups_qs]

        # resolve the paginated object list so we can initialize a cache of URNs and fields
        contacts = list(context['object_list'])
        Contact.bulk_cache_initialize(org, contacts, for_show_only=True)

        context['contacts'] = contacts
        context['groups'] = groups
        context['folders'] = folders
        context['has_contacts'] = contacts or org.has_contacts()
        context['send_form'] = SendMessageForm(self.request.user)
        return context
开发者ID:thierhost,项目名称:rapidpro,代码行数:29,代码来源:views.py


示例12: test_campaign_events

    def test_campaign_events(self):
        url = reverse('api.v2.campaign_events')

        self.assertEndpointAccess(url)

        flow = self.create_flow()
        reporters = self.create_group("Reporters", [self.joe, self.frank])
        registration = ContactField.get_or_create(self.org, self.admin, 'registration', "Registration")

        campaign1 = Campaign.create(self.org, self.admin, "Reminders", reporters)
        event1 = CampaignEvent.create_message_event(self.org, self.admin, campaign1, registration,
                                                    1, CampaignEvent.UNIT_DAYS, "Don't forget to brush your teeth")

        campaign2 = Campaign.create(self.org, self.admin, "Notifications", reporters)
        event2 = CampaignEvent.create_flow_event(self.org, self.admin, campaign2, registration,
                                                 6, CampaignEvent.UNIT_HOURS, flow, delivery_hour=12)

        # create event for another org
        joined = ContactField.get_or_create(self.org2, self.admin2, 'joined', "Joined On")
        spammers = ContactGroup.get_or_create(self.org2, self.admin2, "Spammers")
        spam = Campaign.create(self.org2, self.admin2, "Cool stuff", spammers)
        CampaignEvent.create_flow_event(self.org2, self.admin2, spam, joined,
                                        6, CampaignEvent.UNIT_HOURS, flow, delivery_hour=12)

        # no filtering
        with self.assertNumQueries(NUM_BASE_REQUEST_QUERIES + 4):
            response = self.fetchJSON(url)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json['next'], None)
        self.assertResultsByUUID(response, [event2, event1])
        self.assertEqual(response.json['results'][0], {
            'uuid': event2.uuid,
            'campaign': {'uuid': campaign2.uuid, 'name': "Notifications"},
            'relative_to': {'key': "registration", 'label': "Registration"},
            'offset': 6,
            'unit': 'hours',
            'delivery_hour': 12,
            'flow': {'uuid': flow.uuid, 'name': "Color Flow"},
            'message': None,
            'created_on': format_datetime(event2.created_on)
        })

        # filter by UUID
        response = self.fetchJSON(url, 'uuid=%s' % event1.uuid)
        self.assertResultsByUUID(response, [event1])

        # filter by campaign name
        response = self.fetchJSON(url, 'campaign=Reminders')
        self.assertResultsByUUID(response, [event1])

        # filter by campaign UUID
        response = self.fetchJSON(url, 'campaign=%s' % campaign1.uuid)
        self.assertResultsByUUID(response, [event1])

        # filter by invalid campaign
        response = self.fetchJSON(url, 'campaign=invalid')
        self.assertResultsByUUID(response, [])
开发者ID:JediKoder,项目名称:rapidpro,代码行数:58,代码来源:test_v2.py


示例13: create_groups

    def create_groups(self, orgs):
        """
        Creates the contact groups for each org
        """
        self._log("Creating %d groups... " % (len(orgs) * len(GROUPS)))

        for org in orgs:
            user = org.cache["users"][0]
            for g in GROUPS:
                if g["query"]:
                    group = ContactGroup.create_dynamic(org, user, g["name"], g["query"], evaluate=False)
                else:
                    group = ContactGroup.create_static(org, user, g["name"])
                group.member = g["member"]
                group.count = 0
                org.cache["groups"].append(group)

        self._log(self.style.SUCCESS("OK") + "\n")
开发者ID:teehamaral,项目名称:rapidpro,代码行数:18,代码来源:test_db.py


示例14: save

    def save(self):
        name = self.validated_data.get("name")

        if self.instance:
            self.instance.name = name
            self.instance.save(update_fields=("name",))
            return self.instance
        else:
            return ContactGroup.get_or_create(self.context["org"], self.context["user"], name)
开发者ID:teehamaral,项目名称:rapidpro,代码行数:9,代码来源:serializers.py


示例15: _create_groups

 def _create_groups(self, count, base_names, contacts):
     """
     Creates the given number of groups and fills them with contacts
     """
     groups = []
     num_bases = len(base_names)
     for g in range(0, count):
         name = '%s %d' % (base_names[g % num_bases], g + 1)
         group = ContactGroup.create_static(self.org, self.user, name)
         group.contacts.add(*contacts[(g % num_bases)::num_bases])
         groups.append(ContactGroup.user_groups.get(pk=group.pk))
     return groups
开发者ID:Ilhasoft,项目名称:rapidpro,代码行数:12,代码来源:perf_tests.py


示例16: restore_object

    def restore_object(self, attrs, instance=None):
        """
        Create or update our campaign
        """
        if instance: # pragma: no cover
            raise ValidationError("Invalid operation")

        org = self.user.get_org()

        if 'campaign' in attrs:
            campaign = Campaign.objects.get(pk=attrs['campaign'], is_active=True, is_archived=False, org=org)
            campaign.name = attrs['name']
            campaign.group = ContactGroup.get_or_create(org, self.user, attrs['group'])
            campaign.save()

        else:
            group = ContactGroup.get_or_create(org, self.user, attrs['group'])
            campaign = Campaign.objects.create(name=attrs['name'], group=group, org=org,
                                               created_by=self.user, modified_by=self.user)

        return campaign
开发者ID:AxisOfEval,项目名称:rapidpro,代码行数:21,代码来源:serializers.py


示例17: clean

        def clean(self, value):
            if value.startswith("[_NEW_]"):
                value = value[7:]

                # we must get groups for this org only
                groups = ContactGroup.user_groups.filter(name=value, org=self.user.get_org())
                if groups:
                    group = groups[0]
                else:
                    group = ContactGroup.create(self.user.get_org(), self.user, name=value)
                return group

            return super(RegisterTriggerForm.AddNewGroupChoiceField, self).clean(value)
开发者ID:ramotlubis,项目名称:rapidpro,代码行数:13,代码来源:views.py


示例18: create_group

 def create_group(self, name, contacts):
     group = ContactGroup.create(self.org, self.user, name)
     group.contacts.add(*contacts)
     return group
开发者ID:MOconcepts,项目名称:rapidpro,代码行数:4,代码来源:tests.py


示例19: import_campaigns

    def import_campaigns(cls, exported_json, org, user, same_site=False):
        """
        Import campaigns from our export file
        """
        from temba.orgs.models import EARLIEST_IMPORT_VERSION

        if Flow.is_before_version(exported_json.get("version", "0"), EARLIEST_IMPORT_VERSION):  # pragma: needs cover
            raise ValueError(_("Unknown version (%s)" % exported_json.get("version", 0)))

        if "campaigns" in exported_json:
            for campaign_spec in exported_json["campaigns"]:
                name = campaign_spec["name"]
                campaign = None
                group = None

                # first check if we have the objects by id
                if same_site:
                    group = ContactGroup.user_groups.filter(uuid=campaign_spec["group"]["uuid"], org=org).first()
                    if group:  # pragma: needs cover
                        group.name = campaign_spec["group"]["name"]
                        group.save()

                    campaign = Campaign.objects.filter(org=org, uuid=campaign_spec["uuid"]).first()
                    if campaign:  # pragma: needs cover
                        campaign.name = Campaign.get_unique_name(org, name, ignore=campaign)
                        campaign.save()

                # fall back to lookups by name
                if not group:
                    group = ContactGroup.get_user_group(org, campaign_spec["group"]["name"])

                if not campaign:
                    campaign = Campaign.objects.filter(org=org, name=name).first()

                # all else fails, create the objects from scratch
                if not group:
                    group = ContactGroup.create_static(org, user, campaign_spec["group"]["name"])

                if not campaign:
                    campaign_name = Campaign.get_unique_name(org, name)
                    campaign = Campaign.create(org, user, campaign_name, group)
                else:
                    campaign.group = group
                    campaign.save()

                # deactivate all of our events, we'll recreate these
                for event in campaign.events.all():
                    event.release()

                # fill our campaign with events
                for event_spec in campaign_spec["events"]:
                    field_key = event_spec["relative_to"]["key"]

                    if field_key == "created_on":
                        relative_to = ContactField.system_fields.filter(org=org, key=field_key).first()
                    else:
                        relative_to = ContactField.get_or_create(
                            org, user, key=field_key, label=event_spec["relative_to"]["label"], value_type="D"
                        )

                    start_mode = event_spec.get("start_mode", CampaignEvent.MODE_INTERRUPT)

                    # create our message flow for message events
                    if event_spec["event_type"] == CampaignEvent.TYPE_MESSAGE:

                        message = event_spec["message"]
                        base_language = event_spec.get("base_language")

                        if not isinstance(message, dict):
                            try:
                                message = json.loads(message)
                            except ValueError:
                                # if it's not a language dict, turn it into one
                                message = dict(base=message)
                                base_language = "base"

                        event = CampaignEvent.create_message_event(
                            org,
                            user,
                            campaign,
                            relative_to,
                            event_spec["offset"],
                            event_spec["unit"],
                            message,
                            event_spec["delivery_hour"],
                            base_language=base_language,
                            start_mode=start_mode,
                        )
                        event.update_flow_name()
                    else:
                        flow = Flow.objects.filter(
                            org=org, is_active=True, is_system=False, uuid=event_spec["flow"]["uuid"]
                        ).first()
                        if flow:
                            CampaignEvent.create_flow_event(
                                org,
                                user,
                                campaign,
                                relative_to,
                                event_spec["offset"],
#.........这里部分代码省略.........
开发者ID:teehamaral,项目名称:rapidpro,代码行数:101,代码来源:models.py


示例20: pre_process

 def pre_process(self, request, *args, **kwargs):
     if hasattr(self, 'system_group'):
         org = request.user.get_org()
         self.queryset = ContactGroup.get_system_group_queryset(org, self.system_group)
开发者ID:thierhost,项目名称:rapidpro,代码行数:4,代码来源:views.py



注:本文中的temba.contacts.models.ContactGroup类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python models.URN类代码示例发布时间:2022-05-27
下一篇:
Python tdasm.Tdasm类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap