我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.utils.text.slugify()。
def gen_unique_slug(apps, schema_editor): FrequentlyAskedQuestion = apps.get_model('cms', 'FrequentlyAskedQuestion') for row in FrequentlyAskedQuestion.objects.all(): if not row.slug: max_length = FrequentlyAskedQuestion._meta.get_field('slug').max_length slug = orig_slug = slugify(row.question)[:max_length] slug_is_unique = not FrequentlyAskedQuestion.objects.filter(slug=orig_slug).exists() count = 1 while not slug_is_unique: slug = "{orig}-{count}".format( orig=orig_slug[:max_length - len(str(count)) - 1], count=count) slug_is_unique = not FrequentlyAskedQuestion.objects.filter(slug=slug).exists() count += 1 row.slug = slug row.save()
def unique_slug_generator(instance, new_slug=None): """ This is for a Django project and it assumes your instance has a model with a slug field and a title character (char) field. """ if new_slug is not None: slug = new_slug else: slug = slugify(instance.title) if slug in DONT_USE: new_slug = "{slug}-{randstr}".format( slug=slug, randstr=random_string_generator(size=4) ) return unique_slug_generator(instance, new_slug=new_slug) Klass = instance.__class__ qs_exists = Klass.objects.filter(slug=slug).exists() if qs_exists: new_slug = "{slug}-{randstr}".format( slug=slug, randstr=random_string_generator(size=4) ) return unique_slug_generator(instance, new_slug=new_slug) return slug
def test_slug(self): title_length = Event._meta.get_field('title').max_length slug_length = Event._meta.get_field('slug').max_length self.assertGreaterEqual(slug_length, title_length) title = random_string(title_length) slug = slugify(title) date_from = now date_to = date_from + datetime.timedelta(seconds=1) location = models.Location.objects.order_by('?').first() event1 = Event(title=title, slug=slug, event_type=Event.MEETUP, date_from=date_from, date_to=date_to, location=location, cfp_allowed=False) event1.save() self.assertEqual(Event.objects.get(slug=slug).title, title) event2 = Event(title=random_string(128, unicode=True), slug=slug, event_type=Event.MEETUP, date_from=date_from, date_to=date_to, location=location, cfp_allowed=False) self.assertRaises(IntegrityError, event2.save) # slug must be unique
def test_order_event_with_ticket(self): entry = models.Order.objects.create(price=155.5, discount=5.5) # Create Event title = 'Test Event title' slug = slugify(title) date_from = timezone.now() date_to = date_from + datetime.timedelta(days=1) location = models.Location.objects.create(title="Test Location title") event = Event.objects.create(title=title, slug=slug, event_type=Event.MEETUP, date_from=date_from, date_to=date_to, location=location, status=Event.PUBLISHED, cfp_allowed=False) # Create TicketType for Event ticket_type = TicketType.objects.create(title='Test Ticket Type', price=150, event=event, date_from=date_from, date_to=date_to) # Create Ticket with TicketType models.Ticket.objects.create(title='Test Ticket', type=ticket_type, order=entry) self.assertEqual(entry.event, event)
def create_user(user=None, **attributes): name = attributes.get('name', fake.name()) first_name = attributes.get('first_name', fake.first_name()) last_name = attributes.get('last_name', fake.last_name()) username = attributes.get('username', slugify(name)) email = attributes.get('email', username + '@' + fake.free_email_domain()) password = fake_password if user: attributes.pop('password') for attr, value in attributes.iteritems(): setattr(user, attr, value) user.set_password(password) user.save() else: user = auth_models.User.objects.create_user( first_name=first_name, last_name=last_name, username=username, email=email, password=password ) return user
def create_demo_fixtures(): fake = Faker() name = fake.name() # have username be demo-username, so demos-users are easy to tell username = 'demo-{name}'.format(name=name) username = slugify(username) # since these are demo accounts, just set the username/pass the same # so this is a really weird bug since you'd wonder why this would be a get_or_create # but faker doesn't always generate fake names in celery instances ... user, _ = User.objects.get_or_create(username=username) # create a log of this person as a demo user, otherwise we would never be able to tell if someone is a demo or not! _, created = DemoUserLog.objects.get_or_create(user=user) if not created: return fixtures_builder = DemoHistoricalDataBuilder(user, periods_back=180) fixtures_builder.create_historical_fixtures()
def create_slug(instance, new_slug=None): temp_title = '' if len(instance.title) > 40: temp_title = instance.title[:40] else: temp_title = instance.title slug = slugify(temp_title) if new_slug is not None: slug = new_slug qs = Post.objects.filter(slug=slug).order_by('-id') exists = qs.exists() if exists: new_slug = "%s-%s" %(slug, qs.first().id) return create_slug(instance, new_slug) return slug
def form_valid(self, form): form = PartialNewPostForm(self.request.POST) post = form.save(commit=False) post.author = self.request.user post.slug = unidecode(post.title) post.slug = slugify(post.slug) post.save() if self.request.POST['tags_field']: tags = self.request.POST['tags_field'].replace(', ', ',').split(',') for tag_name in tags: tag = Tag() tag.post = post tag.name = tag_name tag.save() self.success_url = "/post/" + post.slug return super(NewPostView, self).form_valid(form)
def save(self, *args, **kwargs): # ## avg of all ratings # # self.rating_avg = # Aggregate Avg of all ratings for this user if self.approved_by_user or self.approved_by_admin: self.status = 'approved' elif not self.status: self.status = 'added' # if self.added_by_other: # self.status = 'added_by_other' if not self.slug: first = self.first_name #.replace(r'^".*"$', '') last = self.last_name self.slug = slugify(first + '-' + last) if self.twitter: self.twitter = self.twitter.replace('@', '') if not self.entry_method: self.entry_method = 'site-form' return super(Person, self).save(*args, **kwargs)
def to_analyser_export(self, path, data, username, xform_id_string, *args): # Get the XLSForm. xform = XForm.objects.get(user__username__iexact=username, id_string__exact=xform_id_string) xlsform_io= xform.to_xlsform() if xlsform_io is None: raise RuntimeError('XLSForm `{}` for user `{}` could not be retrieved from storage.'. format(xform_id_string, username)) prefix = slugify('analyser_data__{}__{}'.format(username, xform_id_string)) with tempfile.NamedTemporaryFile('w+b', prefix=prefix, suffix='.xlsx',) as xls_data: # Generate a new XLS export to work from. self.to_xls_export(xls_data.name, data) xls_data.file.seek(0) # Generate the analyser file. analyser_io= generate_analyser(xlsform_io, xls_data) # Write the generated analyser file to the specified path # ...which itself points to a temp file. with open(path, 'wb') as analyser_file: analyser_file.write(analyser_io.read())
def render_pdf_document(self): if self.blueprint.reviewer_is_anonymous: if self.submission: name = '{0} für {1}'.format(self.blueprint, self.submission) else: name = str(self.blueprint) name = '{0}-{1}'.format(name, uuid4().hex[:5]) else: name = str(self) filename = '{0}.pdf'.format(slugify(name)) pdfdata = self.render_pdf() self.pdf_document = Document.objects.create_from_buffer(pdfdata, doctype='checklist', parent_object=self, name=name, original_file_name=filename) self.save()
def team_view(self, round_number=None, team_number=None): context = self.get_team_context( self.league.tag, self.season.tag, round_number, team_number, self.request.user.is_staff, self.request.user.has_perm('tournament.change_pairing', self.league)) calendar_title = "" if context['current_team']: calendar_title = "{} Games".format(context['current_team']) uid_component = slugify(context['current_team'].name) else: calendar_title = "{} Games".format(self.league.name) uid_component = 'all' full_pairings_list = [] for pairing_list in context['pairing_lists']: for pairing in pairing_list: if pairing.scheduled_time is None: continue full_pairings_list.append(pairing) return self.ical_from_pairings_list(full_pairings_list, calendar_title, uid_component)
def upload_recipients(self, request): if not request.method == 'POST': raise PermissionDenied if not self.has_change_permission(request): raise PermissionDenied reader = unicodecsv.DictReader(request.FILES['file']) for lineno, line in enumerate(reader, 1): group = line.pop('group', None) if 'slug' not in line: line['slug'] = slugify(line['name']) recipient = Recipient.objects.create( **line ) if group is not None: rg = RecipientGroup.objects.get(slug=group) recipient.groups.add(rg) return redirect('admin:confrontiv_recipient_changelist')
def add_show(self, data, runningStatus): self.seriesName = data['seriesName'] self.slug = slugify(self.seriesName) self.overview = data['overview'] self.banner = 'http://thetvdb.com/banners/' + data['banner'] self.imbdID = data['imdbID'] self.tvdbID = data['tvdbID'] self.siteRating = data['siteRating'] self.network = data['network'] self.runningStatus = runningStatus self.genre_list = json.dumps(data['genre']) self.last_updated = timezone.now() try: self.firstAired = datetime.strptime(data['firstAired'], '%Y-%m-%d').date() except: pass self.save()
def start(self, name, user, **kwargs): slug = slugify(name) # first, we check if a timer for this group is already started qs = user.timer_groups.filter(slug=slug).running() existing = qs.first() if existing: return existing # we stop any previously running group for the same user user.timer_groups.stop() # then we get_or_create a new group based on the given name group, created = self.get_or_create( user=user, slug=slugify(name), defaults={'name': name}, ) # and finally, we start the whole thing group.start() return group
def add_slug_to_article_if_not_exists(sender, instance, *args, **kwargs): MAXIMUM_SLUG_LENGTH = 255 if instance and not instance.slug: slug = slugify(instance.title) unique = generate_random_string() if len(slug) > MAXIMUM_SLUG_LENGTH: slug = slug[:MAXIMUM_SLUG_LENGTH] while len(slug + '-' + unique) > MAXIMUM_SLUG_LENGTH: parts = slug.split('-') if len(parts) is 1: # The slug has no hypens. To append the unique string we must # arbitrarly remove `len(unique)` characters from the end of # `slug`. Subtract one to account for extra hyphen. slug = slug[:MAXIMUM_SLUG_LENGTH - len(unique) - 1] else: slug = '-'.join(parts[:-1]) instance.slug = slug + '-' + unique
def test_default_jumbotron(self): """ Default jumbotron rendering """ page1 = self.create_page(slug='page1', title="Hello", content="<p>test</p>", button1_url='http://example.org/', button1_title="GO") template = Template('{% load fluent_contents_tags %}{% page_placeholder "content" %}') request = RequestFactory().get("/", HTTP_HOST='example.org') html = template.render(Context({'page': page1, 'request': request})) expected = '''<div class="jumbotron"> <div class="container"> <h1>Hello</h1> <p>test</p> <p><a class="btn btn-primary btn-lg" href="http://example.org/" role="button">GO</a></p> </div> </div>''' self.assertEqual(slugify(strip_tags(html)), 'hello-test-go') self.assertHTMLEqual(html.strip(), expected)
def create_organization(self): new_organization = Organization.objects.create( name=self.cleaned_data['organization_name'], slug=slugify(self.cleaned_data['organization_name']), ) new_user = User.objects.create_user( self.cleaned_data['user_name'], self.cleaned_data['user_email'], self.cleaned_data['user_password'] ) new_user.is_staff = True new_user.save() new_ablator_user = AblatorUser.objects.create( user=new_user, organization=new_organization ) return new_ablator_user
def get(self, request): try: boards = trello_client.list_boards() if boards: result = [h.delete() for h in trello_client.list_hooks()] print("delete trello hook :: result={}".format(result)) for board in boards: slug_board = slugify(board.name, allow_unicode=False) b, created = Board.objects.get_or_create(name=slug_board) host = getenv("MATTERLLO_HOST") or request.get_host() url = "{}://{}/callback/{}/".format(request.scheme, host, b.id) result = trello_client.create_hook(url, board.id) print("create trello hook :: callback={} :: board={} :: result={}".format(url, slug_board, result)) return super(BoardView, self).get(request) except Exception as e: print("unable to display board :: {}".format(e)) return super(BoardView, self).get(request)
def has_object_perm(self, user_obj, perm=None, obj=None): """ Validate permissions for the object specified. If there is not object should be validated before with the `contrib.auth.backends.ModelBackend`. Is required class permission to has permission over an object of the class. permissions: `change` `delete` `view` """ if not user_obj.is_active or user_obj.is_anonymous or not all([perm, obj]): return False # validation object permission obj_permission_label = '_has_perm_cache_{}_{}'.format(slugify(perm), obj.id) if not hasattr(user_obj, obj_permission_label): setattr(user_obj, obj_permission_label, self._has_object_permissions(user_obj, perm, obj)) return getattr(user_obj, obj_permission_label)
def full_clean(self, *args, **kwargs): # autogenerate slugs for non-empty title translation for lang_code in mt_settings.AVAILABLE_LANGUAGES: title_field = build_localized_fieldname('title', lang_code) slug_field = build_localized_fieldname('slug', lang_code) title = getattr(self, title_field) slug = getattr(self, slug_field) if title and not slug: if DJANGO_VERSION >= (1, 9): base_slug = slugify(title, allow_unicode=True) else: base_slug = slugify(title) if base_slug: setattr(self, slug_field, self._get_autogenerated_lang_slug(base_slug, lang_code)) super(Page, self).full_clean(*args, **kwargs)
def readcsv_and_update(): df = pd.DataFrame() #getting herolist with open('hero_list.txt', 'rb') as file: for thing in file: try: time.sleep(2) name = thing[:len(thing)-1] final_url = "http://www.dotabuff.com/heroes/" + slugify(name) + "/matchups?date=week" current_attribute = get_requests_single_hero(final_url, name) df[name] = 4 df[name] = pd.Series(current_attribute) print (name) except Exception as e: print (e) df.to_csv('hero_data.csv', header=None, index=False) #testing func tions
def __str__(self): return self.name # def save(self, *args, **kwargs): # if not self.id: # # Newly created object, so set slug # original = slugify(self.name) # #Checking if slug is unique # if University.objects.filter(slug=original).exists(): # in_university = University.objects.get(slug=original) # #Make new slug by combining name and id of previous instance # self.slug = slugify('%s-%d' % (original, in_university.id)) # else: # self.slug = original # super(University, self).save(*args, **kwargs)
def test_slug(self): self.assertEqual(self.public_content.slug, slugify(self.public_content.short_text))
def test_channel_group_name(self): self.assertEquals( self.public_content.channel_group_name, "%s_%s" % (self.public_content.id, slugify(self.public_content.guid)), ) long_non_ascii_guid_content = ContentFactory(guid="ä"*150) self.assertEquals( long_non_ascii_guid_content.channel_group_name, "%s_%s" % ( long_non_ascii_guid_content.id, "a"*(79-len(str(long_non_ascii_guid_content.id))) ) )
def channel_group_name(self): """Make a safe Channel group name. ASCII or hyphens or periods only. Prefix with ID as we have to slugify the name and cut long guids due to asgi library group name restriction. """ return ("%s_%s" % (self.id, slugify(self.name)))[:80]
def slug(self): return slugify(self.short_text)
def channel_group_name(self): """Make a safe Channel group name. ASCII or hyphens or periods only. Prefix with ID as we have to cut long guids due to asgi library group name restriction. """ return ("%s_%s" % (self.id, slugify(self.guid)))[:80]
def create_draft_page(site, title): page = SimplePage( title=title, slug=slugify(title), content='content', live=False ) site.root_page.add_child(instance=page) return page
def upload(self, request, parent_lookup_torrent=None): """ Handles sent file, creates File object, chunks and writes it into Volume.UPLOAD. :return: Response """ if parent_lookup_torrent: return Response(status=status.HTTP_406_NOT_ACCEPTABLE) uploaded_file_obj = request.data['file'] uploaded_file_name, uploaded_file_ext = os.path.splitext(uploaded_file_obj.name) uploaded_file_name = '{}{}'.format(slugify(uploaded_file_name), uploaded_file_ext) uploaded_file_upload_path = '{}/{}'.format(self.request.user.username, uploaded_file_name) file_obj, created = File.objects.get_or_create( path=uploaded_file_upload_path, defaults={ 'volume': Volume.UPLOAD, 'size': uploaded_file_obj.size } ) if not created: return Response({ 'detail': "File already exists." }, status=status.HTTP_400_BAD_REQUEST) # Link file to authenticated user. request.user.files.add(file_obj) # Handle uploaded file. handle_uploaded_file(uploaded_file_obj, file_obj.full_path) return Response(status=status.HTTP_201_CREATED)
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 name(self): return text.slugify(six.text_type(self.title))
def archiveurl(context, page, *args): """[DEPRECATED] Returns the URL for the page that has the given slug. Use routablepageurl from wagtail.contrib.wagtailroutablepage templatetag instead. for example: `{% archiveurl page author %}` should be: `{% routablepageurl page 'author' author %}` """ logger.warning( ('DEPRECATED: wagtailbase tag archiveurl is depracated. ' 'Use routablepageurl from wagtail.contrib.wagtailroutablepage ' 'templatetag instead.')) try: url_name = 'author' a_args = [slugify(args[0].username)] except AttributeError: try: url_name = 'tag' a_args = [slugify(args[0].name)] except AttributeError: url_name = 'date' a_args = args except IndexError: url_name = '' a_args = [] return routablepageurl(context, page.specific, url_name, *a_args)
def remove_states_from_labels(apps, schema_editor): Neighborhood = apps.get_model("pfb_analysis", "Neighborhood") for n in Neighborhood.objects.all(): # Remove state abbreviation from label n.label = re.sub(r', *[A-Z]{2} *$', '', n.label) # Set name to new slugified label n.name = slugify(n.label) n.save()
def perform_create(self, serializer): if serializer.is_valid(): serializer.save(organization=self.request.user.organization, name=slugify(serializer.validated_data['label']))
def get_neighborhood_file_upload_path(instance, filename): """ Upload each boundary file to its own directory """ return 'neighborhood_boundaries/{0}/{1}/{2}{3}'.format(slugify(instance.organization.name), instance.state_abbrev, instance.name, os.path.splitext(filename)[1])
def name_for_label(cls, label): return slugify(label)
def save(self, *args, **kwargs): """Override save method to add slug label. """ if not self.label: self.label = slugify(self.name) super(Organization, self).save(*args, **kwargs)
def save(self, commit=True): self.instance.slug = slugify(self.instance.name) return super(AttributeChoiceValueForm, self).save(commit=commit)
def save(self, commit=True): self.instance.slug = slugify(unidecode(self.instance.name)) if self.parent_pk: self.instance.parent = get_object_or_404( Category, pk=self.parent_pk) if self.instance.parent and self.instance.parent.hidden: self.instance.hidden = True super(CategoryForm, self).save(commit=commit) self.instance.set_hidden_descendants(self.cleaned_data['hidden']) return self.instance
def create_slugs(apps, schema_editor): Value = apps.get_model('product', 'AttributeChoiceValue') for value in Value.objects.all(): value.slug = slugify(value.display) value.save()
def get_slug(self): return slugify(smart_text(unidecode(self.name)))
def get_formfield_name(self): return slugify('attribute-%s' % self.slug, allow_unicode=True)
def save(self, *args, **kwargs): # if not self.slug and self.title: # self.slug = slugify(self.title) super(PostModel, self).save(*args, **kwargs)
def blog_post_model_pre_save_receiver(sender, instance, *args, **kwargs): print("before save") if not instance.slug and instance.title: instance.slug = slugify(instance.title)
def blog_post_model_post_save_receiver(sender, instance, created, *args, **kwargs): print("after save") print(created) if created: if not instance.slug and instance.title: instance.slug = slugify(instance.title) instance.save()
def handle(self, *args, **options): name = input('Enter the Tenant name: ') slug = input('Enter the Tenant slug: (%s)' % slugify(name)) domain = input('Enter the Tenant site: (localhost:8000)') if not slug: slug = slugify(name) if not domain: domain = 'localhost:8000' with transaction.atomic(): create_tenant(name, slug, {}, [domain]) self.stdout.write(self.style.SUCCESS('Successfully created Tenant %s' % name))
def _underscore_slugify(name): # Slugify given string, except using undesrscores instead of hyphens. return slugify(name).replace('-', '_')
def get_group_name_by(username): """Return an alarm group name by given username.""" return slugify("alarm-%s" % username)