本文整理汇总了Python中models.slugify函数的典型用法代码示例。如果您正苦于以下问题:Python slugify函数的具体用法?Python slugify怎么用?Python slugify使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了slugify函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_object
def get_object(self, request, slug='', file=''):
obj = PageFile(slug=slugify(slug), name=file)
page = Page(slug=slugify(slug))
obj.page = page.versions.most_recent()
obj.title = _('File %(filename)=s on page "%(pagename)s"') % {
'filename': obj.name, 'pagename': obj.page.name}
return obj
示例2: render
def render(self, context):
try:
cls = ''
url = self.href
page = context['page']
if self.is_relative_link(url):
if url.startswith('_files/'):
filename = file_url_to_name(url)
url = reverse('pages:file-info', args=[page.pretty_slug,
filename])
try:
file = PageFile.objects.get(slug__exact=page.slug,
name__exact=filename)
cls = ' class="file_%s"' % file.rough_type
except PageFile.DoesNotExist:
cls = ' class="missing_link"'
else:
try:
page = Page.objects.get(slug__exact=slugify(url))
url = reverse('pages:show', args=[page.pretty_slug])
except Page.DoesNotExist:
# Check if Redirect exists.
if not Redirect.objects.filter(source=slugify(url)):
cls = ' class="missing_link"'
# Convert to proper URL: My%20page -> My_page
url = name_to_url(url_to_name(url))
url = reverse('pages:show', args=[url])
return '<a href="%s"%s>%s</a>' % (url, cls,
self.nodelist.render(context))
except:
return ''
示例3: get_redirect_url
def get_redirect_url(self, **kwargs):
pagename = self.request.GET.get('pagename')
if not pagename.strip():
# No page name provided, so let's return a useful error message.
messages.add_message(self.request, messages.SUCCESS,
_('You must provide a page name when creating a page.'))
return reverse('haystack_search')
if Page.objects.filter(slug=slugify(pagename)):
return Page.objects.get(slug=slugify(pagename)).get_absolute_url()
else:
return reverse('pages:edit', args=[pagename])
示例4: get_object
def get_object(self, request, region='', slug=''):
self.setup_region(region)
obj = Page(slug=slugify(slug), region=self.region)
obj.title = obj.versions.most_recent().name
obj.page = obj
return obj
示例5: get_cache_key
def get_cache_key(*args, **kwargs):
from django.core.urlresolvers import get_urlconf
from pages.models import name_to_url
slug = kwargs.get('slug')
# Control characters and whitespace not allowed in memcached keys
return 'globaltags:%s' % slugify(slug).replace(' ', '_')
示例6: form_valid
def form_valid(self, form):
try:
p = Page.objects.get(slug=slugify(self.kwargs['slug']))
self.new_pagename = form.cleaned_data['pagename']
p.rename_to(self.new_pagename)
except PageExistsError, s:
messages.add_message(self.request, messages.SUCCESS, s)
return HttpResponseRedirect(reverse('pages:show', args=[p.slug]))
示例7: get_queryset
def get_queryset(self):
self.tag_name = slugify(self.kwargs["slug"])
try:
self.tag = Tag.objects.get(slug=self.tag_name)
self.tag_name = self.tag.name
return PageTagSet.objects.filter(tags=self.tag)
except Tag.DoesNotExist:
self.tag = None
return PageTagSet.objects.none()
示例8: suggest_tags
def suggest_tags(request):
"""
Simple tag suggest.
"""
def _make_unique(l):
d = {}
ll = []
for m in l:
if m['slug'] in d:
continue
ll.append(m)
d[m['slug']] = True
return ll
# XXX TODO: Break this out when doing the API work.
import json
term = request.GET.get('term', None)
if not term:
return HttpResponse('')
region_id = request.GET.get('region_id', None)
if region_id is not None:
results = Tag.objects.filter(
slug__startswith=slugify(term),
region__id=int(region_id)).exclude(pagetagset=None)
if len(results) < 5:
# Set a sane limit before adding
results = results.values('slug').distinct().values('slug', 'name').order_by('slug')[:20]
global_results = Tag.objects.filter(
slug__startswith=slugify(term)).exclude(pagetagset=None).values('slug').distinct().values('slug', 'name').order_by('slug')[:20]
results = _make_unique(list(results) + list(global_results))[:20]
else:
results = results.values('slug').distinct().values('slug', 'name').order_by('slug')[:20]
else:
results = Tag.objects.filter(
slug__startswith=slugify(term)).exclude(pagetagset=None).values('slug').distinct().values('slug', 'name').order_by('slug')[:20]
results = [t['name'] for t in results]
return HttpResponse(json.dumps(results))
示例9: get_queryset
def get_queryset(self):
self.tag_name = slugify(self.kwargs['slug'])
try:
region = self.get_region()
self.tag = Tag.objects.get(
slug=self.tag_name, region=region)
self.tag_name = self.tag.name
pts = PageTagSet.objects.filter(tags=self.tag, region=region).\
select_related('page', 'region').defer('page__content')
if not pts.exists():
raise Http404
return pts
except Tag.DoesNotExist:
self.tag = None
raise Http404
示例10: validate_league_name
def validate_league_name(form, field):
"""Validate the league name."""
current_league_id = form.data['id']
current_league_name = None
if current_league_id:
current_league = models.League.get_by_id(int(current_league_id))
current_league_name = current_league.name
league_name = field.data.strip()
if not league_name:
raise validators.ValidationError('No league name specified.')
else:
# Only throw a name already exists error, if the user is trying to
# create a league or change their league name.
if ((league_name != current_league_name) and
models.League.get_by_name(models.slugify(league_name))):
raise validators.ValidationError('League name already exists.')
示例11: handler404
def handler404(self, request, *args, **kwargs):
tag_name = slugify(kwargs['slug'])
msg = (_('<p>No pages tagged "%s".</p>') %
tag_name)
html = render_to_string('404.html', {'message': msg}, RequestContext(request))
return HttpResponseNotFound(html)
示例12: wrapped
def wrapped(*args, **kwargs):
if "slug" in kwargs:
kwargs["original_slug"] = kwargs["slug"]
kwargs["slug"] = models.slugify(kwargs["slug"])
return func(*args, **kwargs)
示例13: get_object
def get_object(self):
from pages.models import slugify
p = Page.objects.filter(slug=slugify(self.request.POST['page_name']), region=self.get_region())
if p.exists():
return p[0]
示例14: file_name
def file_name(self, req, obj):
return '%s-screenshot-%s' % (
models.slugify(obj.question.get().answer_title), obj.key.id())
示例15: post
def post(self, verb, team_slug):
assert (verb in ["new", "toggle", "join", "decline", "leave"]), "POST verb is not supported: %s" % `verb`
user = users.get_current_user()
profile = models.Profile.get_by_key_name(user.user_id())
if verb == "new":
# if user is creating a new team...
team_name = self.request.get('newteamname')
emails_to_invite = self.request.get('colleagues')
logging.info(emails_to_invite)
list_of_emails = [l.strip() for l in emails_to_invite.split(',')]
logging.info(list_of_emails)
if team_name not in [None, '', ' ']:
# see if team already exists
team = models.Team.find_by_name(team_name)
if team is not None:
memberships_teams_keys = [m.team.key() for m in profile.membership_set]
# don't allow user to invite others to the team
# if they are not a member of the team
if team.key() not in memberships_teams_keys:
self.response.out.write("Oops. That team name is already taken.")
return
if team is None:
# create new team
team = models.Team(name=team_name)
# make a slug from the supplied team name
team.slug = models.slugify(team_name)
team.put()
# create a new membership for the user
membership = models.Membership(team=team, profile=profile)
membership.put()
for email in list_of_emails:
logging.info(email)
invite = models.Invitation.invite_colleague(team,\
profile, email)
logging.info(invite)
self.response.out.write("Invitations sent for team '%s'" % team.name)
# TODO get rid of toggle in favor of "leave"
if verb == "toggle":
# get the user's team memberships
memberships = profile.membership_set
# get a list of keys of the teams user has membership in
memberships_teams_keys = [m.team.key() for m in memberships]
team_slug = self.request.get('teamslug')
team = models.Team.find_by_slug(team_slug)
if team.key() not in memberships_teams_keys:
new_member = models.Membership(team=team, profile=profile)
new_member.put()
self.response.out.write("You are now a member of %s" % team.name)
else:
if team.key() in memberships_teams_keys:
old_membership = models.Membership.find_by_profile_and_team(profile, team)
if old_membership is not None:
old_membership.delete()
self.response.out.write("You are no longer a member of %s" % team.name)
if verb in ["join", "decline"]:
# get the user's invitations
invitations = profile.pending_invitation_set
if invitations is None:
self.response.out.write("Oops. Can't find any pending invitations.")
else:
invitations_teams_keys = [i.team.key() for i in invitations]
# get the user's team memberships
memberships = profile.membership_set
# get a list of keys of the teams user has membership in
memberships_teams_keys = [m.team.key() for m in memberships]
invitation = models.Invitation.get(self.request.get('invitekey'))
if invitation is not None:
team = invitation.team
if team.key() not in memberships_teams_keys:
if team.key() in invitations_teams_keys:
if verb == "join":
new_member = models.Membership(team=team, profile=profile)
new_member.put()
#self.response.out.write("You are now a member of %s" % team.name)
self.redirect("/team/show/%s" % team.slug)
else:
self.response.out.write("You declined invitation to %s" % team.name)
# TODO sidebar should be reloaded to get rid of accept/decline links
invitation.delete()
else:
self.response.out.write("Oops. Can't find a pending invitation for %s" % team.name)
else:
self.response.out.write("Oops. You are already a member of %s" % team.name)