def oc_slugify(value):
value = value.replace('.', '-')
return slugify(value)
python类slugify()的实例源码
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
__init__.py 文件源码
项目:django-open-volunteering-platform
作者: OpenVolunteeringPlatform
项目源码
文件源码
阅读 17
收藏 0
点赞 0
评论 0
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)