我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.template.defaultfilters.slugify()。
def export_supervision_authorities(self, *args, **options): writer = unicodecsv.DictWriter(open(options['filename'], 'w'), ( 'name', 'email', 'address', 'contact', 'jurisdiction__slug', 'other_names', 'description', 'tags', 'parent__name', 'classification', 'url', 'website_dump', 'request_note' )) writer.writeheader() for authority in SupervisionAuthority.objects.all(): slug = slugify(authority.name) authority.fds_url = 'https://fragdenstaat.de/behoerde/%s/' % slug authority.save() writer.writerow({ 'name': authority.name, 'email': authority.email, 'address': authority.address, 'contact': authority.contact, 'jurisdiction__slug': slugify(authority.state.name), 'classification': 'Heimaufsicht' })
def get_context_data(self, **kwargs): context = super(EventDetailView, self).get_context_data(**kwargs) context.update(self.extra_context) if self.object.is_archived(): self.template_name = 'happenings/404.html' elif self.object.event_type == 'current exhibition' and self.object.end_date() < datetime.datetime.today(): self.template_name = 'happenings/detail/past-exhibition.html' elif self.object.parent is not None: self.template_name = 'happenings/detail/child.html' elif self.object.child_events.all(): self.template_name = 'happenings/detail/parent.html' else: self.template_name = 'happenings/detail/%s.html' % slugify(self.object.event_type) return context
def make_image(path_to, filename): try: data = await df_multi_reader(filename=join(path_to, filename)) if len(data.index) > 0: info = name_deconstructor(filename=filename, t="s") info["broker"] = slugify(info["broker"]).replace('-', '_') info["direction"] = "longs" image_filename = filename_constructor(info=info, folder="meta") data = data.loc[data['CLOSE'] != 0] if (not isfile(image_filename)) | (datetime.fromtimestamp(getmtime(image_filename)) < \ (datetime.now() - timedelta(days=30))): await make_strat_image(info=info, data=data) except Exception as err: print(colored.red("At making images {}\n".format(err)))
def get_or_create_calendar_for_object(self, obj, distinction=None, name=None): """ >>> user = User(username="jeremy") >>> user.save() >>> calendar = Calendar.objects.get_or_create_calendar_for_object(user, name = "Jeremy's Calendar") >>> calendar.name "Jeremy's Calendar" """ try: return self.get_calendar_for_object(obj, distinction) except Calendar.DoesNotExist: if name is None: calendar = Calendar(name=str(obj)) else: calendar = Calendar(name=name) calendar.slug = slugify(calendar.name) calendar.save() calendar.create_relation(obj, distinction) return calendar
def __init__(self, *args, **kwargs): kwargs.setdefault('blank', True) kwargs.setdefault('editable', False) populate_from = kwargs.pop('populate_from', None) if populate_from is None: raise ValueError("missing 'populate_from' argument") else: self._populate_from = populate_from self.slugify_function = kwargs.pop('slugify_function', slugify) self.separator = kwargs.pop('separator', six.u('-')) self.overwrite = kwargs.pop('overwrite', False) self.check_is_bool('overwrite') self.allow_duplicates = kwargs.pop('allow_duplicates', False) self.check_is_bool('allow_duplicates') self.max_unique_query_attempts = kwargs.pop('max_unique_query_attempts', MAX_UNIQUE_QUERY_ATTEMPTS) super(AutoSlugField, self).__init__(*args, **kwargs)
def form_valid(self, form): topic = self.get_object() old_tags = [tag.title for tag in topic.tags.all()] topic = form.save() tags_text = form.cleaned_data['tags'] if tags_text: new_tags = tags_text.split(',') remove_tags = set(new_tags) - set(old_tags) for tag in new_tags: tag_slug = slugify(tag) if not Tags.objects.filter(slug=tag_slug).exists(): tag = Tags.objects.create(slug=tag_slug, title=tag) topic.tags.add(tag) else: tag = Tags.objects.filter(slug=tag_slug).first() if tag.title in remove_tags: topic.remove(tag) else: topic.tags.add(tag) topic.save() return JsonResponse({"error": False, "success_url": reverse('django_simple_forum:signup')})
def save(self, commit=True): instance = super(CategoryForm, self).save(commit=False) instance.created_by = self.user instance.title = self.cleaned_data['title'] if str(self.cleaned_data['is_votable']) == 'True': instance.is_votable = True else: instance.is_votable = False if str(self.cleaned_data['is_active']) == 'True': instance.is_active = True else: instance.is_active = False if not self.instance.id: instance.slug = slugify(self.cleaned_data['title']) if commit: instance.save() return instance
def _update_or_create_item( cls, geocode_result, types_list, url, parent, error_log=""): address_components = geocode_result['address_components'][0] location = geocode_result['geometry']['location'] slug = slugify(address_components['short_name'])[:200] if slug == "": slug = slugify(address_components['long_name'])[:200] mapitem, _ = cls.objects.update_or_create( place_id=geocode_result['place_id'], defaults={ 'long_name': address_components['long_name'], 'short_name': address_components['short_name'], 'geo_type': _get_main_type(types_list), 'types': ",".join(types_list), 'response_json': json.dumps(geocode_result), 'geocode': "{},{}".format(location['lat'], location['lng']), 'slug': slug, 'url': "{}/{}".format(url, slug), 'parent': parent, 'error_log': error_log, }) return mapitem
def update_or_create_from_political_place( cls, place_id, name, geo_type, types, response_json, geocode, url, parent, error_log=""): slug = slugify(name)[:200] mapitem, _ = cls.objects.update_or_create( place_id=place_id, defaults={ 'long_name': name, 'short_name': name, 'geo_type': geo_type, 'types': types, 'response_json': response_json, 'geocode': geocode, 'slug': slug, 'url': "{}/{}".format(url, slug), 'parent': parent, 'error_log': error_log, }) return mapitem
def generate_valid_slug(source, parent, language): """ Generate a valid slug for a page from source for the given language. Parent is passed so we can make sure the slug is unique for this level in the page tree. """ if parent: qs = Title.objects.filter(language=language, page__parent=parent) else: qs = Title.objects.filter(language=language, page__parent__isnull=True) used = list(qs.values_list('slug', flat=True)) baseslug = slugify(source) slug = baseslug i = 1 if used: while slug in used: slug = '%s-%s' % (baseslug, i) i += 1 return slug
def get_patterns(self): self.discover_plugins() # We want untranslated name of the plugin for its slug so we deactivate translation lang = get_language() deactivate_all() try: url_patterns = [] for plugin in self.get_all_plugins(): p = plugin() slug = slugify(force_text(normalize_name(p.__class__.__name__))) url_patterns += [ url(r'^plugin/%s/' % (slug,), include(p.plugin_urls)), ] finally: # Reactivate translation activate(lang) return url_patterns
def forwards(self, orm): from django.template.defaultfilters import slugify from sentry.db.models import update for project in orm['sentry.Project'].objects.all(): if project.slug: continue base_slug = slugify(project.name) slug = base_slug n = 0 while orm['sentry.Project'].objects.filter(slug=slug).exists(): n += 1 slug = base_slug + '-' + str(n) update(project, slug=slug)
def ver_ciudad(request, nombre_ciudad): slug_ciudad = slugify(nombre_ciudad) ciudad_actual = get_object_or_404(Ciudad, slug=slug_ciudad, activa=True) lineas = natural_sort_qs(ciudad_actual.lineas.all(), 'slug') tarifas = Tarifa.objects.filter(ciudad=ciudad_actual) imagenes = ImagenCiudad.objects.filter(ciudad=ciudad_actual) template = "core/ver_ciudad.html" if ( request.GET.get("dynamic_map") ): template = "core/ver_obj_map.html" return render_to_response(template, {'obj': ciudad_actual, 'ciudad_actual': ciudad_actual, 'imagenes': imagenes, 'lineas': lineas, 'tarifas': tarifas}, context_instance=RequestContext(request))
def ver_mapa_ciudad(request, nombre_ciudad): desde = request.GET.get("desde") hasta = request.GET.get("hasta") slug_ciudad = slugify(nombre_ciudad) ciudad_actual = get_object_or_404(Ciudad, slug=slug_ciudad, activa=True) # "default_lat":ciudad_actual.centro.coords[1], # "default_lon":ciudad_actual.centro.coords[0], # pois = Poi.objects.filter(ciudad=ciudad_actual) # comercios = Comercio.objects.filter(ciudad=ciudad_actual) return render_to_response('core/buscador.html', { 'es_vista_mapa': True, 'ciudad_actual': ciudad_actual, 'desde': desde, 'hasta': hasta, }, context_instance=RequestContext(request))
def ver_linea(request, nombre_ciudad, nombre_linea): slug_ciudad = slugify(nombre_ciudad) slug_linea = slugify(nombre_linea) ciudad_actual = get_object_or_404(Ciudad, slug=slug_ciudad, activa=True) """ TODO: Buscar solo lineas activas """ linea_actual = get_object_or_404(Linea, slug=slug_linea, ciudad=ciudad_actual) recorridos = natural_sort_qs(Recorrido.objects.filter(linea=linea_actual), 'slug') template = "core/ver_linea.html" if ( request.GET.get("dynamic_map") ): template = "core/ver_obj_map.html" return render_to_response(template, {'obj': linea_actual, 'ciudad_actual': ciudad_actual, 'linea_actual': linea_actual, 'recorridos': recorridos }, context_instance=RequestContext(request))
def redirect_nuevas_urls(request, ciudad=None, linea=None, ramal=None, recorrido=None): """ cualbondi.com.ar/la-plata/recorridos/Norte/10/IDA/ (ANTES) cualbondi.com.ar/la-plata/norte/10-desde-x-hasta-y (DESPUES) cualbondi.com.ar/cordoba/recorridos/T%20(Transversal)/Central/IDA/ """ url = '/' if not ciudad: ciudad = 'la-plata' url += slugify(ciudad) + '/' if linea: url += slugify(linea) + '/' if ramal and recorrido: try: recorrido = Recorrido.objects.get(linea__nombre=linea, nombre=ramal, sentido=recorrido) url += slugify(recorrido.nombre) + '-desde-' + slugify(recorrido.inicio) + '-hasta-' + slugify(recorrido.fin) except ObjectDoesNotExist: pass return redirect(url)
def get(self, request, keypair_name=None, optional=None): try: if optional == "regenerate": mogan.keypair_delete(request, keypair_name) keypair = mogan.keypair_create(request, keypair_name) except Exception: redirect = reverse('horizon:project:server_key_pairs:index') exceptions.handle(self.request, _('Unable to create key pair: %(exc)s'), redirect=redirect) response = http.HttpResponse(content_type='application/binary') response['Content-Disposition'] = ('attachment; filename=%s.pem' % slugify(keypair.name)) response.write(keypair.private_key) response['Content-Length'] = str(len(response.content)) return response
def find_template(self, template_type, action_type): """look for template""" potential_templates = [] if action_type: action_type = slugify(action_type.name) potential_templates += [ u"documents/_{0}_{1}.html".format(action_type, template_type), ] potential_templates += [ "documents/_{0}.html".format(template_type), ] for template_name in potential_templates: try: get_template(template_name) return template_name except TemplateDoesNotExist: pass return None
def get_objects(self): objects = [] known_objects = [] api = PeeringDB() for ix in InternetExchange.objects.all(): if ix.peeringdb_id: known_objects.append(ix.peeringdb_id) ix_networks = api.get_ix_networks_for_asn(settings.MY_ASN) for ix_network in ix_networks: if ix_network.id not in known_objects: objects.append({ 'peeringdb_id': ix_network.id, 'name': ix_network.name, 'slug': slugify(ix_network.name), 'ipv6_address': ix_network.ipaddr6, 'ipv4_address': ix_network.ipaddr4, }) return objects
def _credentials_filename(item): return slugify( '-'.join([ "openbare", "credentials", str(item.pk), item.name ]) ) + ".json"
def get_upload_path(self, filename): if self.user != None: string = "%s/genomes/%s/%s/%s" % (settings.BASE_DIR, slugify(self.user.username), self.id, filename)#.replace(' ', '_') else: string = "%s/genomes/public/%s/%s" % (settings.BASE_DIR, self.id, filename)#.replace(' ', '_') print('string',string) return string
def get(self, request, keypair_name): """Creates a new keypair and associates it to the current project. * Since the response for this endpoint creates a new keypair and is not idempotent, it normally would be represented by a POST HTTP request. However, this solution was adopted as it would support automatic file download across browsers. :param keypair_name: the name to associate the keypair to :param regenerate: (optional) if set to the string 'true', replaces the existing keypair with a new keypair This returns the new keypair object on success. """ try: regenerate = request.GET.get('regenerate') == 'true' if regenerate: api.nova.keypair_delete(request, keypair_name) keypair = api.nova.keypair_create(request, keypair_name) except exceptions.Conflict: return HttpResponse(status=409) except Exception: return HttpResponse(status=500) else: response = HttpResponse(content_type='application/binary') response['Content-Disposition'] = ('attachment; filename=%s.pem' % slugify(keypair_name)) response.write(keypair.private_key) response['Content-Length'] = str(len(response.content)) return response
def slugify(string): return slugify_django(unidecode(force_text(string)))
def create_attributes_and_values(attribute_data): attributes = [] for attribute_name, attribute_values in attribute_data.items(): attribute = create_attribute( slug=slugify(attribute_name), name=attribute_name) for value in attribute_values: create_attribute_value(attribute, name=value) attributes.append(attribute) return attributes
def create_attribute_value(attribute, **kwargs): name = fake.word() defaults = { 'attribute': attribute, 'name': name} defaults.update(kwargs) defaults['slug'] = slugify(defaults['name']) attribute_value = AttributeChoiceValue.objects.get_or_create(**defaults)[0] return attribute_value
def initialize_slug(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. Event = apps.get_model("happenings", "Event") # NOQA for event in Event.objects.all(): if event.slug is None: event.slug = slugify(event.title) event.save()
def choices(self, cl): yield { 'system_name': slugify(self.title), 'query_string': cl.get_query_string( {}, remove=self._get_expected_fields() ) }
def save(self, *args, **kwargs): self.slug = slugify(self.name) super(List, self).save(*args, **kwargs)
def save(self, *args, **kwargs): if self.slug is None: self.slug = slugify(self.title) super(Photo, self).save(*args, **kwargs)
def save(self, *args, **kwargs): if not self.id or not self.slug: self.slug = slugify(unidecode(self.title)) super().save(*args, **kwargs)
def oc_slugify(value): value = value.replace('.', '-') return slugify(value)
def save(self): instance = super(PackageForm, self).save(commit=False) if not instance.slug: slug = name_slug = slugify(instance.name) for x in itertools.count(2): if Project.objects.filter(slug=slug).exists(): slug = '{}-{}'.format(name_slug, x) else: instance.slug = slug instance.save() break return instance
def clean_title(value): value = slugify(value) for char in CHARS: value = value.replace(char, "") return value
def make_heat_img(path_to, filename): try: info = name_deconstructor(filename=filename, t="s") info["broker"] = str(slugify(info["broker"])).replace("-", "_") file_name = join(path_to, info["filename"]) file_name = ext_drop(filename=file_name) df = await df_multi_reader(filename=file_name) if len(df.index) > settings.MIN_TRADES: info["direction"] = 1 longs = await convert_to_perc(data=df.LONG_PL, info=info) info["direction"] = 2 shorts = await convert_to_perc(data=df.SHORT_PL, info=info) info["direction"] = 0 long_short = await convert_to_perc(data=(df.LONG_PL + df.SHORT_PL), info=info) if not longs is None: info["direction"] = "longs" await save_heatmap(data=longs, info=info) await make_yearly_returns(returns=longs, info=info) if not shorts is None: info["direction"] = "shorts" await save_heatmap(data=longs, info=info) await make_yearly_returns(returns=longs, info=info) if not long_short is None: info["direction"] = "longs_shorts" await save_heatmap(data=longs, info=info) await make_yearly_returns(returns=longs, info=info) except Exception as err: print(colored.red("At make_heat_img {}".format(err)))
def clean(self): super().clean() user = User(first_name=self.cleaned_data.get('first_name'), last_name=self.cleaned_data.get('last_name')) username = slugify(user.get_full_name()) if User.objects.filter(username=username).exists(): raise forms.ValidationError(_('An user with that firstname and that lastname already exists.'))
def save(self, commit=True): user = super().save(commit=False) user.username = slugify(user.get_full_name()) user.set_password(get_random_string(length=32)) if commit: user.save() return user
def slugifier(sender, instance,*args, **kwargs): if hasattr(sender, "title"): instance.slug = slugify(instance.title) else: raise AttributeError("Slug Error") return instance
def create_slug(self, model_instance, add): # get fields to populate from and slug field to set if not isinstance(self._populate_from, (list, tuple)): self._populate_from = (self._populate_from, ) slug_field = model_instance._meta.get_field(self.attname) if add or self.overwrite: # slugify the original field content and set next step to 2 slug_for_field = lambda lookup_value: self.slugify_func(self.get_slug_fields(model_instance, lookup_value)) slug = self.separator.join(map(slug_for_field, self._populate_from)) start = 2 else: # get slug from the current model instance slug = getattr(model_instance, self.attname) # model_instance is being modified, and overwrite is False, # so instead of doing anything, just return the current slug return slug # strip slug depending on max_length attribute of the slug field # and clean-up self.slug_len = slug_field.max_length if self.slug_len: slug = slug[:self.slug_len] slug = self._slug_strip(slug) original_slug = slug if self.allow_duplicates: setattr(model_instance, self.attname, slug) return slug return super(AutoSlugField, self).find_unique( model_instance, slug_field, self.slug_generator(original_slug, start))
def environment(**options): """Get jinja2 environment. :param options: Options :return env: return environment instance """ env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'url': reverse, 'LANGUAGES': settings.LANGUAGES, 'translation': translation, }) # add django filters env.filters['slugify'] = slugify # use django-bootstrap-form on jinja from bootstrapform.templatetags import bootstrap env.filters['bootstrap'] = bootstrap.bootstrap env.filters['bootstrap_horizontal'] = bootstrap.bootstrap_horizontal env.filters['bootstrap_inline'] = bootstrap.bootstrap_inline # add custom filters env.filters['fupper'] = fupper env.install_gettext_translations(translation) return env
def generate_slug(sender, instance, *args, **kwargs): if not instance.slug: if hasattr(sender, "name"): instance.slug = slugify(instance.name) else: raise AttributeError("Name field is required for slug.") return instance
def post(self, request): """Handles POST requests. The forms on the analysis page POST here to set URL params. This page then redirects to GET with those params set and the values are read out of the URL to determine how to run the actual computations. """ user_profile = models.UserProfile.objects.get(user=request.user) if not user_profile.user.is_staff: return response.Response('', status=status.HTTP_404_NOT_FOUND) network = user_profile.network url_params = {} if request.POST.get('network', None): url_params['network'] = request.POST.get('network') # Encode the proposed prices from the table into the URL. The 'name' # of each input is pretty convoluted and there are lots of inputs. # Each name and corresponding url param is a combo of the params below. traffic_types = ('call', 'sms') entities = ('sub', 'op', 'e') tiers = self.get_ordered_tiers(network) for entity in entities: for traffic_type in traffic_types: for tier in tiers: key = '%s_%s_proposed_%s_cost' % ( traffic_type, slugify(tier.name), entity) if request.POST.get(key, None): # Only encode values in the URL when the proposed cost # is different than the actual cost. proposed = int(request.POST.get(key)) actual = self.get_cost(tier, traffic_type, entity) if proposed != actual: url_params[key] = proposed base_url = urlresolvers.reverse('margin-analysis') url = '%s?%s' % (base_url, urllib.urlencode(url_params)) return redirect(url)
def do_unique_slug(self, using=DEFAULT_DB): """ Ensures that the slug is always unique for the year this article was posted """ if not self.id: # make sure we have a slug first if not len(self.slug.strip()): self.slug = slugify(self.title) self.slug = self.get_unique_slug(self.slug, using) return True return False
def create_slug(sender, instance, *args, **kwargs): if not instance.slug: if hasattr(sender, "name"): instance.slug = slugify(instance.name) if hasattr(sender, "title"): instance.slug = slugify(instance.title) else: raise AttributeError("No name or title found!") return instance
def generate_slug(channel, model, name): if name: slug = slugify(name)[0:99] append = '' i = 0 query = model.objects.filter(slug=slug + append, channel__slug=channel) while query.count() > 0: i += 1 append = '-' + str(i) query = model.objects.filter(slug=slug + append, channel__slug=channel) return slug + append return None
def save(self, *args, **kwargs): pk_field_name = self._meta.pk.name value_field_name = getattr(self, 'value_field_name', 'channel_title') slug_field_name = getattr(self, 'slug_field_name', 'slug') max_interations = getattr(self, 'slug_max_iterations', 1000) slug_separator = getattr(self, 'slug_separator', '-') # fields, query set, other setup variables slug_field = self._meta.get_field(slug_field_name) slug_len = slug_field.max_length queryset = self.__class__.objects.all() # if the pk of the record is set, exclude it from the slug search current_pk = getattr(self, pk_field_name) if current_pk: queryset = queryset.exclude(**{pk_field_name: current_pk}) slug = slugify(getattr(self, value_field_name)).replace('-', '_') if slug_len: slug = slug[:slug_len] setattr(self, slug_field.attname, slug) super(AutoSlugifyOnSaveVideoModel, self).save(*args, **kwargs)
def _get_unique_slug(self): slug = slugify(self.title) unique_slug = slug num = 1 while Ideas.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug
def save(self, *args, **kwargs): """ Update the display title with the title, if blank """ if self.display_title in [None, '']: self.display_title = self.title if self.slug in [None, '']: self.slug = slugify(self.title) super(Project, self).save(*args, **kwargs)
def slug_from_instance(cls, instance): slug = slugify(instance.name) if slug == "": slug = "organization" slug = slug[:61] slugbase = slug i = 0 while (cls.objects.filter(url_slug=slug).exists() and (i < 100 or slugbase == "organization")): i += 1 slug = slugbase + "-" + str(i) return slug
def _extract_sections(self): """ Here is an example of what a section header looks like in the html of a Google Document: <h3 class="c1"><a name="h.699ffpepx6zs"></a><span>Hello World </span></h3> We split the content of the Google Document up using a regular expression that matches the above header. re.split is a pretty cool function if you haven't tried it before. It puts the matching groups into the list as well as the content between the matches. Check it out here: http://docs.python.org/library/re.html#re.split One big thing we do in this method is replace the ugly section id that Google creates with a nicely slugified version of the section title. This makes for pretty urls. """ self._sections = [] header = r'<h(?P<level>\d) class="[^"]+">' \ r'<a name="(?P<id>[^"]+)"></a>' \ r'<span>(?P<title>[^<]+)</span>' \ r'</h\d>' l = re.split(header, self._content) l.pop(0) while l: section = Section( # hack: cause we started with h3 in google docs level=int(l.pop(0)) - 2, id=l.pop(0), title=l.pop(0).decode('utf8'), content=l.pop(0), ) section['id'] = slugify(section['title']) if section['level'] >= 1: self._sections.append(section)
def save(self, *args, **kwargs): #self.slug = slugify(self.title) self.body = markdown(self.body) super(Post, self).save(*args, **kwargs)