本文整理汇总了Python中temba.contacts.models.ContactField类的典型用法代码示例。如果您正苦于以下问题:Python ContactField类的具体用法?Python ContactField怎么用?Python ContactField使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ContactField类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setUp
def setUp(self):
self.clear_cache()
self.user = self.create_user("tito")
self.admin = self.create_user("Administrator")
self.org = Org.objects.create(name="Nyaruka Ltd.", timezone="Africa/Kigali",
created_by=self.user, modified_by=self.user)
self.org.initialize()
self.org.administrators.add(self.admin)
self.admin.set_org(self.org)
self.org.administrators.add(self.user)
self.user.set_org(self.org)
self.tel_mtn = Channel.objects.create(org=self.org, name="MTN", channel_type="A", role="SR",
address="+250780000000", secret="12345", gcm_id="123",
created_by=self.user, modified_by=self.user)
self.tel_tigo = Channel.objects.create(org=self.org, name="Tigo", channel_type="A", role="SR",
address="+250720000000", secret="23456", gcm_id="234",
created_by=self.user, modified_by=self.user)
self.tel_bulk = Channel.objects.create(org=self.org, name="Nexmo", channel_type="NX", role="S",
parent=self.tel_tigo, secret="34567",
created_by=self.user, modified_by=self.user)
self.twitter = Channel.objects.create(org=self.org, name="Twitter", channel_type="TT", role="SR",
created_by=self.user, modified_by=self.user)
# for generating tuples of scheme, path and channel
generate_tel_mtn = lambda num: (TEL_SCHEME, "+25078%07d" % (num + 1), self.tel_mtn)
generate_tel_tigo = lambda num: (TEL_SCHEME, "+25072%07d" % (num + 1), self.tel_tigo)
generate_twitter = lambda num: (TWITTER_SCHEME, "tweep_%d" % (num + 1), self.twitter)
self.urn_generators = (generate_tel_mtn, generate_tel_tigo, generate_twitter)
self.field_nick = ContactField.get_or_create(self.org, 'nick', 'Nickname', show_in_table=True, value_type=TEXT)
self.field_age = ContactField.get_or_create(self.org, 'age', 'Age', show_in_table=True, value_type=DECIMAL)
示例2: setUp
def setUp(self):
self.clear_cache()
self.user = self.create_user("tito")
self.admin = self.create_user("Administrator")
self.org = Org.objects.create(name="Nyaruka Ltd.", timezone="Africa/Kigali",
created_by=self.user, modified_by=self.user)
self.org.initialize()
self.org.administrators.add(self.admin)
self.admin.set_org(self.org)
self.org.administrators.add(self.user)
self.user.set_org(self.org)
self.tel_mtn = Channel.create(self.org, self.user, 'RW', 'A', name="MTN", address="+250780000000",
secret="12345", gcm_id="123")
self.tel_tigo = Channel.create(self.org, self.user, 'RW', 'A', name="Tigo", address="+250720000000",
secret="23456", gcm_id="234")
self.tel_bulk = Channel.create(self.org, self.user, 'RW', 'NX', name="Nexmo", parent=self.tel_tigo)
self.twitter = Channel.create(self.org, self.user, None, 'TT', name="Twitter", address="billy_bob")
# for generating tuples of scheme, path and channel
def generate_tel_mtn(num):
return TEL_SCHEME, "+25078%07d" % (num + 1), self.tel_mtn
def generate_tel_tigo(num):
return TEL_SCHEME, "+25072%07d" % (num + 1), self.tel_tigo
def generate_twitter(num):
return TWITTER_SCHEME, "tweep_%d" % (num + 1), self.twitter
self.urn_generators = (generate_tel_mtn, generate_tel_tigo, generate_twitter)
self.field_nick = ContactField.get_or_create(self.org, self.admin, 'nick', 'Nickname', show_in_table=True, value_type=Value.TYPE_TEXT)
self.field_age = ContactField.get_or_create(self.org, self.admin, 'age', 'Age', show_in_table=True, value_type=Value.TYPE_DECIMAL)
示例3: test_field_results
def test_field_results(self):
(c1, c2, c3, c4) = (self.create_contact("Contact1", '0788111111'),
self.create_contact("Contact2", '0788222222'),
self.create_contact("Contact3", '0788333333'),
self.create_contact("Contact4", '0788444444'))
# create a gender field that uses strings
gender = ContactField.get_or_create(self.org, 'gender', label="Gender", value_type=TEXT)
c1.set_field('gender', "Male")
c2.set_field('gender', "Female")
c3.set_field('gender', "Female")
result = Value.get_value_summary(contact_field=gender)[0]
self.assertEquals(2, len(result['categories']))
self.assertEquals(3, result['set'])
self.assertEquals(2, result['unset']) # this is two as we have the default contact created by our unit tests
self.assertFalse(result['open_ended'])
self.assertResult(result, 0, "Female", 2)
self.assertResult(result, 1, "Male", 1)
# create an born field that uses decimals
born = ContactField.get_or_create(self.org, 'born', label="Born", value_type=DECIMAL)
c1.set_field('born', 1977)
c2.set_field('born', 1990)
c3.set_field('born', 1977)
result = Value.get_value_summary(contact_field=born)[0]
self.assertEquals(2, len(result['categories']))
self.assertEquals(3, result['set'])
self.assertEquals(2, result['unset'])
self.assertFalse(result['open_ended'])
self.assertResult(result, 0, "1977", 2)
self.assertResult(result, 1, "1990", 1)
# ok, state field!
state = ContactField.get_or_create(self.org, 'state', label="State", value_type=STATE)
c1.set_field('state', "Kigali City")
c2.set_field('state', "Kigali City")
result = Value.get_value_summary(contact_field=state)[0]
self.assertEquals(1, len(result['categories']))
self.assertEquals(2, result['set'])
self.assertEquals(3, result['unset'])
self.assertResult(result, 0, "1708283", 2)
reg_date = ContactField.get_or_create(self.org, 'reg_date', label="Registration Date", value_type=DATETIME)
now = timezone.now()
c1.set_field('reg_date', now.replace(hour=9))
c2.set_field('reg_date', now.replace(hour=4))
c3.set_field('reg_date', now - timedelta(days=1))
result = Value.get_value_summary(contact_field=reg_date)[0]
self.assertEquals(2, len(result['categories']))
self.assertEquals(3, result['set'])
self.assertEquals(2, result['unset'])
self.assertResult(result, 0, (now - timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0), 1)
self.assertResult(result, 1, now.replace(hour=0, minute=0, second=0, microsecond=0), 2)
示例4: 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, [])
示例5: save
def save(self):
label = self.validated_data.get("label")
value_type = self.validated_data.get("value_type")
if self.instance:
key = self.instance.key
else:
key = ContactField.make_key(label)
return ContactField.get_or_create(self.context["org"], self.context["user"], key, label, value_type=value_type)
示例6: setUp
def setUp(self):
super().setUp()
self.planting_date = ContactField.get_or_create(
self.org, self.admin, "planting_date", "Planting Date", value_type=Value.TYPE_DATETIME
)
self.contact = self.create_contact("Ben Haggerty", number="+12065552020")
self.contact.set_field(self.admin, "planting_date", "2018-06-23T13:48:12.123456Z")
# create a campaign with a message event 1 day after planting date
self.farmers = self.create_group("Farmers", [self.contact])
self.campaign = Campaign.create(self.org, self.admin, "Planting Reminders", self.farmers)
self.event = CampaignEvent.create_message_event(
self.org,
self.admin,
self.campaign,
relative_to=self.planting_date,
offset=1,
unit="D",
message={
"eng": "Hi @(upper(contact.name)) don't forget to plant on @(format_date(contact.planting_date))"
},
base_language="eng",
)
示例7: contact_field
def contact_field(contact, arg):
field = ContactField.get_by_key(contact.org, arg.lower())
if field is None:
return MISSING_VALUE
value = contact.get_field_display(field)
return value or MISSING_VALUE
示例8: pre_save
def pre_save(self, task):
extra_fields = []
cleaned_data = self.form.cleaned_data
# enumerate the columns which the user has chosen to include as fields
for column in self.column_controls:
if cleaned_data[column['include_field']]:
label = cleaned_data[column['label_field']]
label = label.strip()
value_type = cleaned_data[column['type_field']]
org = self.derive_org()
field_key = slugify_with(label)
existing_field = ContactField.get_by_label(org, label)
if existing_field:
field_key = existing_field.key
extra_fields.append(dict(key=field_key, header=column['header'], label=label, type=value_type))
# update the extra_fields in the task's params
params = json.loads(task.import_params)
params['extra_fields'] = extra_fields
task.import_params = json.dumps(params)
return task
示例9: restore_object
def restore_object(self, attrs, instance=None):
"""
Update our contact field
"""
if instance: # pragma: no cover
raise ValidationError("Invalid operation")
org = self.user.get_org()
key = attrs.get('key', None)
label = attrs.get('label')
value_type = attrs.get('value_type')
if not key:
key = ContactField.make_key(label)
return ContactField.get_or_create(org, key, label, value_type=value_type)
示例10: validate
def validate(self, data):
key = data.get("key")
label = data.get("label")
if not key:
key = ContactField.make_key(label)
if not ContactField.is_valid_key(key):
raise serializers.ValidationError(_("Generated key for '%s' is invalid or a reserved name") % label)
fields_count = ContactField.user_fields.filter(org=self.org).count()
if not self.instance and fields_count >= ContactField.MAX_ORG_CONTACTFIELDS:
raise serializers.ValidationError(
"This org has %s contact fields and the limit is %s. "
"You must delete existing ones before "
"you can create new ones." % (fields_count, ContactField.MAX_ORG_CONTACTFIELDS)
)
data["key"] = key
return data
示例11: get_contact_field
def get_contact_field(cls, path):
parts = path.split(".")
if len(parts) > 1:
if parts[0] in ("parent", "child"):
parts = parts[1:]
if len(parts) < 2:
return None
if parts[0] == "contact":
field_name = parts[1]
if ContactField.is_valid_key(field_name):
return parts[1]
return None
示例12: clean
def clean(self):
for key in self.cleaned_data:
if key.startswith('field_'):
idx = key[6:]
label = self.cleaned_data["label_%s" % idx]
if label:
if not ContactField.is_valid_label(label):
raise forms.ValidationError(_("Field names can only contain letters, numbers, spaces and hypens"))
elif label in RESERVED_CONTACT_FIELDS:
raise forms.ValidationError(_("Field name '%s' is a reserved word") % label)
return self.cleaned_data
示例13: clean
def clean(self):
# don't allow users to specify field keys or labels
re_col_name_field = re.compile(r'column_\w+_label')
for key, value in self.data.items():
if re_col_name_field.match(key):
field_label = value
field_key = slugify_with(value)
if not ContactField.is_valid_label(field_label):
raise ValidationError(_("Field names can only contain letters, numbers, spaces and hypens"))
if field_key in RESERVED_CONTACT_FIELDS:
raise ValidationError(_("%s is a reserved name for contact fields") % value)
return self.cleaned_data
示例14: create_event
def create_event(event_spec, notification, campaign):
org = notification.org_dest
user = notification.created_by
relative_to = ContactField.get_or_create(
org,
user,
key=event_spec["relative_to"]["key"],
label=event_spec["relative_to"]["label"],
value_type="D",
)
# 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,
)
event.update_flow_name()
else:
flow = Flow.objects.filter(org=org, is_active=True, name=event_spec["flow"]["name"]).last()
if flow:
CampaignEvent.create_flow_event(
org,
user,
campaign,
relative_to,
event_spec["offset"],
event_spec["unit"],
flow,
event_spec["delivery_hour"],
)
示例15: clean
def clean(self):
used_labels = []
for key in self.cleaned_data:
if key.startswith('field_'):
idx = key[6:]
label = self.cleaned_data["label_%s" % idx]
if label:
if not ContactField.is_valid_label(label):
raise forms.ValidationError(_("Field names can only contain letters, numbers and hypens"))
if label.lower() in used_labels:
raise ValidationError(_("Field names must be unique"))
elif label in Contact.RESERVED_FIELDS:
raise forms.ValidationError(_("Field name '%s' is a reserved word") % label)
used_labels.append(label.lower())
return self.cleaned_data