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'
})
python类slugify()的实例源码
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
0002_integrate_w_mercator.py 文件源码
项目:django-happenings
作者: natgeosociety
项目源码
文件源码
阅读 15
收藏 0
点赞 0
评论 0
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)