def render(self, context): try: if self.is_variable: copy = self.copy.resolve(context) else: copy = self.copy if context['user'].is_staff and context['request'].GET.get('edit_copys'): copy_obj = Copy.objects.get(key=copy) return '<a href="/admin/kopy/copy/%d/" style="text-decoration: underline;" target="_blank">Edit: %s</a>' % (copy_obj.id, copy_obj) try: if self.br: return linebreaksbr(Copy.objects.get(key=copy).text) elif self.p: return linebreaks(Copy.objects.get(key=copy).text) elif self.title: return title(Copy.objects.get(key=copy).text) return Copy.objects.get(key=copy).text except ObjectDoesNotExist: if self.default: txt = self.default else: txt = 'Please fill me!!' c = Copy.objects.create(key=copy, text=txt) if self.br: return linebreaksbr(c.text) elif self.p: return linebreaks(c.text) elif self.title: return title(Copy.objects.get(key=copy).text) return c.text except template.VariableDoesNotExist: return ''
def field_name(field): if field in [ 'name', 'publisher', 'country', 'language', 'notes', 'format', 'imprint', 'number', 'volume', 'brand', 'editing', 'type', 'title', 'feature', 'genre', 'script', 'pencils', 'inks', 'colors', 'letters', 'characters', 'synopsis', 'price' ]: return title(field) elif field in [ 'year_began', 'year_ended', 'tracking_notes', 'publication_notes', 'no_volume', 'display_volume_with_number', 'publication_date', 'indicia_frequency', 'key_date', 'indicia_publisher', 'no_brand', 'page_count', 'page_count_uncertain', 'no_editing', 'sequence_number', 'no_script', 'no_pencils', 'no_inks', 'no_colors', 'no_letters', 'job_number', 'reprint_notes' ]: return title(field.replace('_', ' ')) elif field in ['is_current', 'is_surrogate']: return u'%s?' % title(field.replace(u'is_', u'')) elif field == 'url': return field.upper() elif field == 'after': return u'Add Issue After' elif field == 'indicia_pub_not_printed': return u'Indicia Publisher Not Printed' elif field == 'title_inferred': return u'Unofficial Title?' return u''
def render(self, context): try: if self.is_variable: copy = self.copy.resolve(context) else: copy = self.copy if context['user'].is_staff and context['request'].GET.get( 'edit_copys'): copy_obj = Copy.objects.get(key=copy) return '<a href="/admin/kopy/copy/%d/" style="text-decoration: underline;" target="_blank">Edit: %s</a>' % ( copy_obj.id, copy_obj) try: if self.br: return linebreaksbr(Copy.objects.get(key=copy).text) elif self.p: return linebreaks(Copy.objects.get(key=copy).text) elif self.title: return title(Copy.objects.get(key=copy).text) return Copy.objects.get(key=copy).text except ObjectDoesNotExist: if self.default: txt = self.default else: txt = 'Please fill me!!' c = Copy.objects.create(key=copy, text=txt) if self.br: return linebreaksbr(c.text) elif self.p: return linebreaks(c.text) elif self.title: return title(Copy.objects.get(key=copy).text) return c.text except template.VariableDoesNotExist: return ''
def resource_info(resource): resource.resource_status_desc = title(filters.replace_underscores(resource.resource_status)) if resource.resource_status_reason: resource.resource_status_reason = title(filters.replace_underscores(resource.resource_status_reason)) context = {} context["resource"] = resource return render_to_string("project/customize_stack/_resource_info.html", context)
def handle(self, *args, **options): total_updated = 0 total_skipped = 0 contacts = defaultdict(list) with open(self.file, newline='') as csvfile: f = csv.reader(csvfile, delimiter=';') for row in f: first_name = title(row[0].strip()) last_name = title(row[1].strip()) email = row[3].lower() contacts[(first_name,last_name)].append(email) mayor_candidates = list(map(lambda x: (x['first_name'], x['last_name']), MayorCandidate.objects.all().values())) for mayor_candidate in mayor_candidates: emails = contacts[mayor_candidate] if len(emails) != 1: print(f'SKIPPING EMAIL FOR {mayor_candidate}. HAS {len(emails)} EMAILS: {emails}') total_skipped += MayorCandidate.objects.filter(first_name=mayor_candidate[0]).filter(last_name=mayor_candidate[1]).update(email='') else: email = emails[0] total_updated += MayorCandidate.objects.filter(first_name=mayor_candidate[0]).filter(last_name=mayor_candidate[1]).update(email=email) print(f'Added emails for {total_updated} mayor candidates') print(f'Skipped adding emails for {total_skipped} mayor candidates')
def get_context_dict(self): # Fix some ugly data if self.site_name.isupper(): self.site_name = title(self.site_name) if self.address.isupper(): self.address = title(self.address) if self.city.isupper(): self.city = title(self.city) # simple fields to present -- these are the attributes that have text content sfields = [] # boolean fields to present -- these are the attributes that are set to True bfields = [] for field in Location._meta.fields: fname = field.get_attname() if not fname in Location.display_include: continue if self.is_true_bool_field(field): bfields.append(field.verbose_name) elif self.is_simple_field(field): kv = (field.verbose_name, getattr(self, fname)) sfields.append(kv) bfields.sort() sfields.sort(key=lambda a: a[0]) return { 'item': self, 'sfields': sfields, 'bfields': bfields }
def changed_fields(changeset, object_id): if changeset.inline(): revision = changeset.inline_revision() elif changeset.issuerevisions.count() == 1: revision = changeset.issuerevisions.all()[0] else: revision = changeset.issuerevisions.all().get(issue=object_id) prev_rev = revision.previous() changed_list = [] if prev_rev is None: # there was no previous revision so only list the initial add of the object. # otherwise too many fields to list. # note that if an object predates the server move, the first revision right # now is not the initial add (but it doesn't harm to show it as such atm). # when the old log tables are migrated, it will be more accurate. if revision.source.created.date() > NEW_SITE_CREATION_DATE: changed_list = [u'%s added' % title(revision.source_name.replace('_', ' '))] else: changed_list = [u'First change to %s on new site. Older change \ history coming soon.' % revision.source_name.replace('_', ' ')] elif revision.deleted: changed_list = [u'%s deleted' % title(revision.source_name.replace('_', ' '))] else: for field in revision._field_list(): if field == 'after': # most ignorable fields handled in oi/view.py/compare() # but this one should also be ignored on the initial change # history page. the only time it's relevant the line will # read "issue added" continue if getattr(revision, field) != getattr(prev_rev, field): changed_list.append(field_name(field)) return ", ".join(changed_list)
def field_name(field): if field in ['name', 'publisher', 'country', 'language', 'notes', 'format', 'imprint', 'number', 'volume', 'brand', 'editing', 'type', 'title', 'feature', 'genre', 'script', 'pencils', 'inks', 'colors', 'letters', 'characters', 'synopsis', 'price']: return title(field) elif field in ['year_began', 'year_ended', 'tracking_notes', 'publication_notes', 'no_volume', 'display_volume_with_number', 'publication_date', 'indicia_frequency', 'key_date', 'indicia_publisher', 'no_brand', 'page_count', 'page_count_uncertain', 'no_editing', 'sequence_number', 'no_script', 'no_pencils', 'no_inks', 'no_colors', 'no_letters', 'job_number', 'reprint_notes']: return title(field.replace('_', ' ')) elif field in ['is_current', 'is_surrogate']: return u'%s?' % title(field.replace(u'is_', u'')) elif field in ['url', 'isbn']: return field.upper() elif field == 'after': return u'Add Issue After' elif field == 'indicia_pub_not_printed': return u'Indicia Publisher Not Printed' elif field == 'title_inferred': return u'Unofficial Title?' return u''
def parse_row(self, row): title = filters.title(row[1]) item_date = datetime.datetime.strptime(row[9], "%m/%d/%Y") attrs = { 'restaurant_id': row[0], 'restaurant_name': title, 'status_code': row[8], 'score': int(float(row[10])*100), 'form_item_id': row[11], 'form_item_desc': row[12], 'activity_item_id': row[13], 'activity_item_comment': row[14], } address = "%s, %s, %s %s" % (filters.title(row[3]), filters.title(row[4]), row[5], row[6]) try: self.create_newsitem( attrs, title=title, item_date=item_date, location_name=address, zipcode=row[6], ) except geocoder.InvalidBlockButValidStreet, e: message = "InvalidBlockButValidStreet: %s" % address self.logger.error(message)
def changed_fields(changeset, object): object_class = type(object) if object_class is Issue: revision = changeset.issuerevisions.all().get(issue=object.id) elif object_class is Series: revision = changeset.seriesrevisions.all().get(series=object.id) elif object_class is Publisher: revision = changeset.publisherrevisions.all().get(publisher=object.id) elif object_class is Brand: revision = changeset.brandrevisions.all().get(brand=object.id) elif object_class is IndiciaPublisher: revision = changeset.indiciapublisherrevisions.all()\ .get(indicia_publisher=object.id) prev_rev = revision.previous() changed_list = [] if prev_rev is None: # there was no previous revision so only list the initial add of the object. # otherwise too many fields to list. changed_list = [u'%s added' % title(revision.source_name.replace('_', ' '))] elif revision.deleted: changed_list = [u'%s deleted' % title(revision.source_name.replace('_', ' '))] else: for field in revision._field_list(): if field == 'after': # most ignorable fields handled in oi/view.py/compare() # but this one should also be ignored on the initial change # history page. the only time it's relevant the line will # read "issue added" continue if getattr(revision, field) != getattr(prev_rev, field): changed_list.append(field_name(field)) return ", ".join(changed_list)
def MultispectralRGeocode(lat,lng): ticket = "76333D50-F9F4-4088-A9D7-DE5B09F9C27C" url = "http://www.geoportal.com.br/xgeocoder/cxinfo.aspx?x="+lng+"&y="+lat+"&Ticket="+str(ticket) page = urllib2.urlopen(url) conteudo = page.read() page.close() geocodexml = ElementTree.fromstring(conteudo) address = geocodexml.findall("INFO") #self.stdout.write(address[0].text+","+address[0].get("NroIni")+"-"+address[0].get("NroFim")+","+address[0].get("Bairro")+","+address[1].text+"-"+address[2].text+","+address[0].get("CEP")) if (address != []): c = CachedGeocode( lat = float(lat), lng = float(lng), full_address = "", number = address[0].get("NroIni")+"-"+address[0].get("NroFim"), street = title(lower(address[0].text)), city = title(lower(address[1].text)), state = address[2].text, country = "Brasil", postal_code = address[0].get("CEP"), administrative_area = title(lower(address[0].get("Bairro"))) ) c.full_address = c.street+" "+c.number+", "+c.administrative_area+" - "+c.city+", "+c.state c.save() return [c.full_address,c.street+" "+c.number+", "+c.administrative_area,c.city,c.state,c.postal_code] else: raise NotImplementedError
def _list_verbose(self, migration): if self.verbose: lead = ' ' * 5 wrap = TextWrapper(width=80, initial_indent=lead, subsequent_indent=lead) meta = migration.meta if meta: self.console() for field in ('Author', 'link', 'Description'): value = meta.get(field) if value: self.console(lead + defaultfilters.title(field) + ': ' + value) if migration.flagged: self.console() self.console(lead + 'Flagged: True', 'red') message = meta.get('flag_message') if message: self.console(wrap.fill(message)) last_run = migration.last_run if last_run: meta = last_run.meta if last_run.meta: self.console() meta['date'] = self._local_datetime(last_run.create_date) for field in ('runner', 'date'): value = last_run.meta.get(field) if value: self.console(lead + defaultfilters.title(field) + ': ' + value) notes = meta.get('notes') if notes: self.console(wrap.fill(notes)) if meta or last_run: self.console()
def resource_info(resource): resource['resource_status_desc'] = title(replace_underscores(resource.get('resource_status'))) if resource.get('resource_status_reason'): resource['resource_status_reason'] = title(replace_underscores(resource.get('resource_status_reason'))) context = {} context['resource'] = resource return render_to_string('orchestration/stacks/_resource_info.html',context)
def get_context_data(self, **kwargs): request = self.request url = request.get_full_path() crumbs = url.split('/') last_crumb = crumbs[-3:-1] current_crumb = last_crumb[0] stack_id = last_crumb[1] crumbs = crumbs[1:3] breadcrumbs = '' build_url = '' for crumb in crumbs: if crumb: build_url += '/' + crumb if crumb != 'heat': breadcrumbs += '<a href="' + build_url + '">' + title( replace_underscores(crumb)) + '</a> |' breadcrumbs += ' ' + title(replace_underscores(' ' + current_crumb)) breadcrumbs = mark_safe(breadcrumbs) context = super(Breadcrumbs, self).get_context_data(**kwargs) context['breadcrumbs'] = breadcrumbs return context
def stack_info(stack, stack_image): stack['stack_status_desc'] = title(replace_underscores(stack.get('stack_status'))) if stack.get('stack_status_reason'): stack['stack_status_reason'] = title(replace_underscores(stack.get('stack_status_reason'))) context = {} context['stack'] = stack context['stack_image'] = stack_image return render_to_string('orchestration/stacks/_stack_info.html',context)
def get_title(self): if self.mode == 'list': return _('all {}'.format(self.controller.opts.verbose_name_plural)) else: obj = getattr(self, 'object', None) return ('{} {}'.format(title(self.mode_title), obj) if obj else title('{} {}'.format( self.mode_title, self.controller.opts.verbose_name)))
def stack_info(stack, stack_image): stack.stack_status_desc = title(replace_underscores(stack.stack_status)) if stack.stack_status_reason: stack.stack_status_reason = title( replace_underscores(stack.stack_status_reason)) context = {} context['stack'] = stack context['stack_image'] = stack_image return render_to_string('project/stacks/_stack_info.html', context)
def resource_info(resource): resource.resource_status_desc = title( filters.replace_underscores(resource.resource_status)) if resource.resource_status_reason: resource.resource_status_reason = title( filters.replace_underscores(resource.resource_status_reason)) context = {} context['resource'] = resource return render_to_string('project/stacksd/_resource_info.html', context)
def transform_alarm_data(obj): return obj return {'id': getattr(obj, 'id', None), 'name': getattr(obj, 'name', None), 'expression': getattr(obj, 'expression', None), 'state': filters.title(getattr(obj, 'state', None)), 'severity': filters.title(getattr(obj, 'severity', None)), 'actions_enabled': filters.title(getattr(obj, 'actions_enabled', None)), 'notifications': getattr(obj, 'alarm_actions', None), }
def get_title(self): if self.mode == 'list': ret = (str(self.view_parent.get_object()) if self.view_parent else _('all') if self.public_modes else str(self.user) + "'s") ret += ' {}'.format(self.verbose_name_plural) else: obj = getattr(self, 'object', None) return ('{} {}'.format(title( self.view.mode_title), obj) if obj else title('{} {}'.format( self.view.mode_title, self.verbose_name))) return ret
def stack_info(stack, stack_image): stack.stack_status_desc = title(replace_underscores(stack.stack_status)) if stack.stack_status_reason: stack.stack_status_reason = title( replace_underscores(stack.stack_status_reason) ) context = {} context['stack'] = stack context['stack_image'] = stack_image return render_to_string('project/stacks/_stack_info.html', context)
def resource_info(resource): resource.resource_status_desc = title( filters.replace_underscores(resource.resource_status) ) if resource.resource_status_reason: resource.resource_status_reason = title( filters.replace_underscores(resource.resource_status_reason) ) context = {} context['resource'] = resource return render_to_string('project/stacks/_resource_info.html', context)
def handle(self, *args, **options): mapped_regions = {} with open(self.file, newline='') as csvfile: f = csv.reader(csvfile, delimiter=';') for row in f: first_name = title(row[1]) last_name = title(row[2]) region_str = row[4] party = row[5] image_file_name = slugify(last_name).upper() + "_" + slugify( first_name).upper() image_file_name = image_file_name.replace('-', '_') municipality = self.get_municipality(region_str) mapped_regions[region_str] = municipality photo_file = None for file in glob.glob( f"2019SAV_meru_foto/**/*{image_file_name}*", recursive=True): photo_file = file # print(file) photo_file_base64 = None if photo_file: with open(photo_file, mode='rb') as f: photo_file_base64 = base64.b64encode(f.read()).decode() response = requests.put(self.endpoint, json={ 'first_name': first_name, 'last_name': last_name, 'municipality': municipality.name, 'party': party, 'photo': photo_file_base64 }) if not response.ok: print("Fail with photo") requests.put(self.endpoint, json={ 'first_name': first_name, 'last_name': last_name, 'municipality': municipality.name, 'party': party, 'photo': None }) else: print("Success") pprint(mapped_regions)
def populate_fields(self): self.artists = self.album_data['artist']['name'] self.album_name = title(self.album_data['title']) self.album_year = datetime.utcfromtimestamp(self.album_data['released_at']).year track_data = [] for track in self.album_data['tracks']['items']: track_data.append({ 'media_number': track['media_number'], 'artists': track['performer']['name'], 'title': title(track['title']), }) self.track_data_json = ujson.dumps(track_data)
def field_name(field): if field in ['is_current', 'is_surrogate']: return u'%s?' % title(field.replace(u'is_', u'')) elif field in ['url', 'isbn']: return field.upper() elif field == 'after': return u'Add Issue After' elif field == 'indicia_pub_not_printed': return u'Indicia Publisher Not Printed' elif field == 'title_inferred': return u'Unofficial Title?' else: return title(field.replace('_', ' '))
def populate_fields(self): self.artists = self.album_data['artist']['name'] self.album_name = title(self.album_data['title']) self.album_year = datetime.utcfromtimestamp( self.album_data['released_at']).year track_data = [] for track in self.album_data['tracks']['items']: track_data.append({ 'media_number': track['media_number'], 'artists': track['performer']['name'], 'title': title(track['title']), }) self.track_data_json = ujson.dumps(track_data)
def handle(self, name=None, ident=None): if ident is not None: # identify user using ``ident`` and add this connection try: connection = Connection.objects.get(uri__endswith="://%s" % ident) except Connection.DoesNotExist: pass else: if connection.user is not None: connection.user.connections.add( self.request.message.connection) self.request.message.connection.save() return "Thank you for your registration." return u"Registration failed! We did not find " \ "an existing reporter identified by: %s." % ident if name is not None: if self.user is None: created = True reporter = Reporter.from_uri( self.request.message.uri, name=name) else: reporter, created = Reporter.objects.get_or_create( pk=self.user.pk, defaults={'name': name}) if created: Report.from_observations( "registration", new_reporter=1, source=self.request.message) return "Welcome, %s. " \ "You have been registered." % title(name) else: reporter.name = name reporter.save() return "Thank you, %s. You have updated your information." % \ title(name) if self.user is not None: try: reporter = Reporter.objects.get(pk=self.user.pk) except Reporter.DoesNotExist: pass else: return "Hello, %s. You have already registered." % \ title(reporter.name) return "Please provide your name to register."
def render(self, name, value, attrs=None): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) output = [u'<table><tr>'] # Set up the table heading header = [] for field in self.fields[1:]: # We don't want the ID header.append('<th>%s</th>' % title(field)) output.append("".join(header)) output.append('</tr>') # Normalize to strings str_values = set([force_unicode(v) for v in value]) for choice in self.choices: output.append('<tr>') if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], choice[0])) # We use a regular CheckboxInput for displaying a checkbox. cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(choice[0]) rendered_cb = cb.render(name, option_value) output.append(u'<td class="first">%s %s</td>' % (rendered_cb, conditional_escape(force_unicode(choice[1])))) for field in choice[2:]: output.append('<td>%s</td>' % field) output.append('</tr>') output.append(u'</table>') return mark_safe(u'\n'.join(output))
def pretty_service_names(name): name = name.replace("-", " ") if name in ["ec2", "s3"]: name = name.upper() else: name = title(name) return name
def title_lang(value, locale='en'): """Convert to title case only for given locale.""" lang = translation.get_language() if lang.startswith(locale): return title(value) return value
def render_options(self, choices, selected_choices): separator = ' | ' choices = sorted(chain(self.choices, choices), key=lambda x: x[1].split(separator)[1].lower()) grouped = groupby(choices, lambda x: x[1].split(separator)[1]) rendered_options = '' for group_key, group_choices in grouped: items = list(group_choices) local_values = [item[0] for item in items] local_selected = set(local_values) & set(selected_choices or []) slug = slugify(group_key) label = title(group_key) rendered_options += mark_safe(""" <li class="accordion-navigation"> <a href="#{slug}"> {title}<i class="right"> <span class="counter">{selected}</span> of {total} </i> </a> <div id="{slug}" class="content"> {all}{items} </div> </li>""".format(slug=slug, title=label, selected=len(local_selected), total=len(local_values), all=self.render_all_option(slugify(group_key)), items='<br />'.join([ self.render_option( local_selected, c[0], c[1].split(separator)[-1]) for c in items ]))) return rendered_options
def clean_name(self): """ A cleaned up version of the ALL CAPS names that are provided by the source data. """ n = self.name n = n.strip() n = n.lower() n = title(n) n = n.replace("A. D.", "A.D.") force_lowercase = ["Of", "For", "To", "By"] for fl in force_lowercase: s = [] for p in n.split(" "): if p in force_lowercase: s.append(p.lower()) else: s.append(p) n = " ".join(s) force_uppercase = ["Usaf", "Pac", "Ca", "Ad", "Rcc", "Cdp", "Aclu", "Cbpa-Pac", "Aka", "Aflac"] for fl in force_uppercase: s = [] for p in n.split(" "): if p in force_uppercase: s.append(p.upper()) else: s.append(p) n = " ".join(s) n = n.replace("Re-Elect", "Re-elect") n = n.replace("Political Action Committee", "PAC") return n
def get_fieldsets(self, request, obj=None): """ Add fieldsets of placeholders to the list of already existing fieldsets. """ template = get_template_from_request(request, obj) if obj: # edit given_fieldsets = deepcopy(self.fieldsets) if not obj.has_publish_permission(request): l = list(given_fieldsets[0][1]['fields'][2]) l.remove('published') given_fieldsets[0][1]['fields'][2] = tuple(l) for placeholder_name in get_placeholders(request, template): if placeholder_name not in self.mandatory_placeholders: if placeholder_name in settings.CMS_PLACEHOLDER_CONF and "name" in settings.CMS_PLACEHOLDER_CONF[ placeholder_name]: name = settings.CMS_PLACEHOLDER_CONF[placeholder_name][ "name"] else: name = placeholder_name given_fieldsets += [(title(name), { 'fields': [placeholder_name], 'classes': ['plugin-holder'] })] advanced = given_fieldsets.pop(3) if obj.has_advanced_settings_permission(request): given_fieldsets.append(advanced) if settings.CMS_SEO_FIELDS: seo = given_fieldsets.pop(3) given_fieldsets.append(seo) else: # new page given_fieldsets = deepcopy(self.add_fieldsets) return given_fieldsets
def render_placeholder_toolbar(placeholder, context, content, name_fallback=None): from cms.plugin_pool import plugin_pool request = context["request"] page = placeholder.page if placeholder else None if not page: page = getattr(request, "current_page", None) if page: template = page.template if name_fallback and not placeholder: placeholder = Placeholder.objects.create(slot=name_fallback) page.placeholders.add(placeholder) placeholder.page = page else: template = None if placeholder: slot = placeholder.slot else: slot = None installed_plugins = plugin_pool.get_all_plugins(slot, page) name = get_placeholder_conf("name", slot, template, title(slot)) name = _(name) context.push() context["installed_plugins"] = installed_plugins context["language"] = get_language_from_request(request) context["placeholder_label"] = name context["placeholder"] = placeholder context["page"] = page toolbar = render_to_string("cms/toolbar/placeholder.html", context) context.pop() return "".join([toolbar, content])
def get_styleguide_templates(): """Return tuples of (display name, slug) for found styleguide templates""" templates = [] for slug in utils.get_styleguide_templates(): name = defaultfilters.title(slug.replace('-', ' ')) templates.append((name, slug)) return templates
def title(value): """ Turns 'my_title' into 'My Title' """ from django.template.defaultfilters import title return title(value).replace("_", " ")
def render_placeholder_toolbar(placeholder, context, content): from cms.plugin_pool import plugin_pool request = context['request'] page = get_page_from_placeholder_if_exists(placeholder) if page: template = page.template else: template = None installed_plugins = plugin_pool.get_all_plugins(placeholder.slot, page) name = settings.CMS_PLACEHOLDER_CONF.get( "%s %s" % (template, placeholder.slot), {}).get("name", None) if not name: name = settings.CMS_PLACEHOLDER_CONF.get(placeholder.slot, {}).get("name", None) if not name: name = placeholder.slot name = title(name) toolbar = render_to_string( "cms/toolbar/add_plugins.html", { 'installed_plugins': installed_plugins, 'language': get_language_from_request(request), 'placeholder_label': name, 'placeholder': placeholder, 'page': page, }) return "".join([toolbar, content])
def save(self, **kwargs): commit = kwargs.pop('commit', True) location = super(ClientLocationForm, self).save(commit=False) if not self.cleaned_data['title']: location.title = self.cleaned_data['address_line1'] if self.cleaned_data['postal_code']: zip_code = Zipcode.objects.filter( code=self.cleaned_data['postal_code']) if len(zip_code) > 0: zip_code = zip_code[0] location.city = title(zip_code.city) location.state_province = zip_code.state if (self.cleaned_data['postal_code'] == self.cleaned_data['title'] or location.title == '%s, %s' % (self.cleaned_data['city'], self.cleaned_data['state_province'])): location.title = '%s, %s' % (location.city, location.state_province) location.google_maps_request() if commit: location.save() return location
def get_label(self): from cms.utils.placeholder import get_placeholder_conf template = self.page.get_template() if self.page else None name = get_placeholder_conf("name", self.slot, template=template, default=title(self.slot)) name = _(name) return name
def get_label(self): from cms.utils.placeholder import get_placeholder_conf name = get_placeholder_conf("name", self.slot, default=title(self.slot)) name = _(name) return name
def render_placeholder_toolbar(placeholder, context, content, name_fallback=None): from cms.plugin_pool import plugin_pool request = context["request"] page = get_page_from_placeholder_if_exists(placeholder) if not page: page = getattr(request, "current_page", None) if page: template = page.template if name_fallback and not placeholder: placeholder = Placeholder.objects.create(slot=name_fallback) page.placeholders.add(placeholder) else: template = None if placeholder: slot = placeholder.slot else: slot = None installed_plugins = plugin_pool.get_all_plugins(slot, page) name = get_placeholder_conf(slot, template, "name", title(slot)) name = _(name) toolbar = render_to_string( "cms/toolbar/placeholder.html", { "installed_plugins": installed_plugins, "language": get_language_from_request(request), "placeholder_label": name, "placeholder": placeholder, "page": page, }, ) return "".join([toolbar, content])
def render_placeholder_toolbar(placeholder, context, content, name_fallback=None): from cms.plugin_pool import plugin_pool request = context['request'] page = placeholder.page if placeholder else None if not page: page = getattr(request, 'current_page', None) if page: template = page.template if name_fallback and not placeholder: placeholder = Placeholder.objects.create(slot=name_fallback) page.placeholders.add(placeholder) placeholder.page = page else: template = None if placeholder: slot = placeholder.slot else: slot = None installed_plugins = plugin_pool.get_all_plugins(slot, page) name = get_placeholder_conf("name", slot, template, title(slot)) name = _(name) context.push() context['installed_plugins'] = installed_plugins context['language'] = get_language_from_request(request) context['placeholder_label'] = name context['placeholder'] = placeholder context['page'] = page toolbar = render_to_string("cms/toolbar/placeholder.html", context) context.pop() return "".join([toolbar, content])
def clean_name(self): """ A cleaned up version of the ALL CAPS names that are provided by the source data. """ n = self.name n = n.strip() n = n.lower() n = title(n) n = n.replace("A. D.", "A.D.") force_lowercase = ['Of', 'For', 'To', 'By'] for fl in force_lowercase: s = [] for p in n.split(" "): if p in force_lowercase: s.append(p.lower()) else: s.append(p) n = " ".join(s) force_uppercase = [ 'Usaf', 'Pac', 'Ca', 'Ad', 'Rcc', 'Cdp', 'Aclu', 'Cbpa-Pac', 'Aka', 'Aflac', ] for fl in force_uppercase: s = [] for p in n.split(" "): if p in force_uppercase: s.append(p.upper()) else: s.append(p) n = " ".join(s) n = n.replace("Re-Elect", "Re-elect") n = n.replace("Political Action Committee", "PAC") return n
def social_user_links(user): profile = user.get_profile() accounts = UserSocialAuth.objects.filter(user=user) providers_links = { 'facebook': {'show': profile.show_facebook, 'link': 'https://www.facebook.com/[id]'}, 'twitter': {'show': profile.show_twitter, 'link': 'https://www.twitter.com/[uname]'}, 'google-oauth2': {'show': profile.show_google_plus, 'link': 'https://plus.google.com/[id]'}, 'github': {'show': profile.show_github, 'link': 'https://github.com/[uname]'}, } output = '' for account in accounts: if providers_links[account.provider]['show']: extra = account.extra_data if not 'id' in extra: extra['id'] = '' link = providers_links[account.provider]['link'] \ .replace('[uname]', extra['username']) \ .replace('[id]', str(extra['id'])) output += '<li class="%(provider)s-icon">' \ '<a data-toggle="tooltip" title="%(title)s" href="%(link)s"></a>' \ % { 'link': link, 'provider': account.provider, 'title': title(account.provider) } return mark_safe(output)
def get_field_lookups(self): """ Returns a list of column name-value/callback tuples. Any callable value will be passed the instance of the object being evaluated during data collection. By default, ALL fields from the model will be included. e.g. [ # Static value # Note, if the string is a property of the object, # that will take precidence. ('Column Name', 'Value'), # Callback to a method on the ModelReport ('Example 2', self.my_callback), # Inline lambda callback ('Example 3', lambda obj: unicode(obj.my_method())), # Attempt to get the property from the object by name ('Example 4', 'property_name'), ] """ if self.field_lookups: return self.field_lookups self.field_lookups = [ (title(field), field) for field in self._get_model_fields() ] return self.field_lookups
def test_non_string_input(self): # Filters shouldn't break if passed non-strings self.assertEqual(addslashes(123), '123') self.assertEqual(linenumbers(123), '1. 123') self.assertEqual(lower(123), '123') self.assertEqual(make_list(123), ['1', '2', '3']) self.assertEqual(slugify(123), '123') self.assertEqual(title(123), '123') self.assertEqual(truncatewords(123, 2), '123') self.assertEqual(upper(123), '123') self.assertEqual(urlencode(123), '123') self.assertEqual(urlize(123), '123') self.assertEqual(urlizetrunc(123, 1), '123') self.assertEqual(wordcount(123), 1) self.assertEqual(wordwrap(123, 2), '123') self.assertEqual(ljust('123', 4), '123 ') self.assertEqual(rjust('123', 4), ' 123') self.assertEqual(center('123', 5), ' 123 ') self.assertEqual(center('123', 6), ' 123 ') self.assertEqual(cut(123, '2'), '13') self.assertEqual(escape(123), '123') self.assertEqual(linebreaks_filter(123), '<p>123</p>') self.assertEqual(linebreaksbr(123), '123') self.assertEqual(removetags(123, 'a'), '123') self.assertEqual(striptags(123), '123')
def render_placeholder_toolbar(placeholder, context, content, name_fallback=None): from cms.plugin_pool import plugin_pool request = context['request'] page = get_page_from_placeholder_if_exists(placeholder) if not page: page = getattr(request, 'current_page', None) if page: template = page.template if name_fallback and not placeholder: placeholder = Placeholder.objects.create(slot=name_fallback) page.placeholders.add(placeholder) else: template = None if placeholder: slot = placeholder.slot else: slot = None installed_plugins = plugin_pool.get_all_plugins(slot, page) name = get_placeholder_conf(slot, template, "name", title(slot)) name = _(name) context.push() context.update({ 'installed_plugins': installed_plugins, 'language': get_language_from_request(request), 'placeholder_label': name, 'placeholder': placeholder, 'page': page, }) toolbar = render_to_string("cms/toolbar/placeholder.html", context) context.pop() return "".join([toolbar, content])
def pretty_service_names(name): name = name.replace('-', ' ') if name in ['ec2', 's3']: name = name.upper() else: name = title(name) return name
def guardar_alumnos(self): for alumno in self.get_alumnos_list(): alumnoObj = Alumno.objects.filter( matricula=alumno.get('matricula')) if not alumnoObj.exists(): # Crear alumno alumnoObj = Alumno.objects.create( matricula=alumno.get('matricula'), apellido_paterno=alumno.get( 'apellido_paterno').capitalize(), apellido_materno=alumno.get( 'apellido_materno').capitalize(), nombre=title(alumno.get('nombre')), email="al{}@alumnos.uacj.mx".format( alumno.get('matricula')), nivel=alumno.get('nivel'), activo=True) InformacionPersonal.objects.create(alumno=alumnoObj) self.alumnos_creados += 1 else: alumnoObj.update(nivel=alumno.get('nivel')) alumnoObj = alumnoObj.last() self.alumnos_actualizados += 1 # Guardar en grupo grupo = Grupo.objects.filter(periodo__activo=True, grupo__iexact=alumno.get('grupo'), campus__iexact=alumno.get('campus')) if grupo.exists(): grupo = grupo.last() grupo.alumnos.add(alumnoObj)
def render_placeholder_toolbar(placeholder, context, content, name_fallback=None): from cms.plugin_pool import plugin_pool request = context['request'] page = get_page_from_placeholder_if_exists(placeholder) if not page: page = getattr(request, 'current_page', None) if page: template = page.template if name_fallback and not placeholder: placeholder = Placeholder.objects.create(slot=name_fallback) page.placeholders.add(placeholder) else: template = None if placeholder: slot = placeholder.slot else: slot = None installed_plugins = plugin_pool.get_all_plugins(slot, page) mixed_key = "%s %s" % (template, slot) name = settings.CMS_PLACEHOLDER_CONF.get(mixed_key, {}).get("name", None) if not name: name = settings.CMS_PLACEHOLDER_CONF.get(slot, {}).get("name", None) if not name: name = slot if not name: name = name_fallback name = title(name) toolbar = render_to_string("cms/toolbar/add_plugins.html", { 'installed_plugins': installed_plugins, 'language': get_language_from_request(request), 'placeholder_label': name, 'placeholder': placeholder, 'page': page, }) return "".join([toolbar, content])
def get_fieldsets(self, request, obj=None): """ Add fieldsets of placeholders to the list of already existing fieldsets. """ template = get_template_from_request(request, obj) if obj: # edit given_fieldsets = deepcopy(self.fieldsets) if not obj.has_publish_permission(request): l = list(given_fieldsets[0][1]['fields'][2]) l.remove('published') given_fieldsets[0][1]['fields'][2] = tuple(l) for placeholder_name in get_placeholders(request, template): if placeholder_name not in self.mandatory_placeholders: if placeholder_name in settings.CMS_PLACEHOLDER_CONF and "name" in settings.CMS_PLACEHOLDER_CONF[placeholder_name]: name = settings.CMS_PLACEHOLDER_CONF[placeholder_name]["name"] else: name = placeholder_name given_fieldsets += [(title(name), {'fields':[placeholder_name], 'classes':['plugin-holder']})] advanced = given_fieldsets.pop(3) if obj.has_advanced_settings_permission(request): given_fieldsets.append(advanced) if settings.CMS_SEO_FIELDS: seo = given_fieldsets.pop(3) given_fieldsets.append(seo) else: # new page given_fieldsets = deepcopy(self.add_fieldsets) return given_fieldsets
def fix_headers(header): """ Note, because of WSGI mangling the headers, it's impossable to access the origional header names directly. Here we try to reconstruct them, but it will fail sometimes. """ header = header[5:].lower().replace('_', '-') return title(header)
def sectionname_label_title(self): """ Include the course label and section name; as well as the ``title`` label for this handout. """ title_label = title(self.label) return "{self.section.course.label} {self.section.section_name}: {title_label}".format( self=self, title_label=title_label)
def coursename_label_title(self): """ Include the course label and course name; as well as the ``title`` label for this handout. """ title_label = title(self.label) return "{self.course.label} - {self.course.name}: {title_label}".format( self=self, title_label=title_label)