当前位置: 首页>>代码示例>>Python>>正文


Python text.slugify方法代码示例

本文整理汇总了Python中django.utils.text.slugify方法的典型用法代码示例。如果您正苦于以下问题:Python text.slugify方法的具体用法?Python text.slugify怎么用?Python text.slugify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.utils.text的用法示例。


在下文中一共展示了text.slugify方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: team_view

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
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.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) 
开发者ID:cyanfish,项目名称:heltour,代码行数:20,代码来源:views.py

示例2: get_filename

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
def get_filename(self, obj):
        """Filename of the Document.

        Parameters
        ----------
        obj : Type[models.Document]
            The document that we want to serialize

        Returns
        -------
        String
            The document's filename

        """
        return "{playlist_title:s}_{title:s}{extension:s}".format(
            playlist_title=slugify(obj.playlist.title),
            title=slugify(obj.title),
            extension=self._get_extension_string(obj),
        ) 
开发者ID:openfun,项目名称:marsha,代码行数:21,代码来源:serializers.py

示例3: add_slug_to_article_if_not_exists

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
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 
开发者ID:tryolabs,项目名称:aws-workshop,代码行数:24,代码来源:signals.py

示例4: to_analyser_export

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
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()) 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:24,代码来源:export_tools.py

示例5: add_slug

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
def add_slug(self, slugtext):
        # Add a slug corectly
        with transaction.atomic():
            slugtext = slugify(slugtext)
            # Check if there is another similar slug for the same user/org
            same_slugs = SlugModel.objects.filter(slug=slugtext)
            if len(same_slugs) == 0:
                slug = SlugModel.objects.create(slug=slugtext, petition=self)
            else:
                alread_used = False
                for s in same_slugs:
                    if self.owner_type == "org":
                        if s.petition.owner_type == "org":
                            if self.org == s.petition.org:
                                alread_used = True
                    else:
                        if s.petition.owner_type == "user":
                            if self.user == s.petition.user:
                                alread_used = True
                if alread_used:
                    raise ValueError('This slug is already used')
                else:
                    slug = SlugModel.objects.create(slug=slugtext, petition=self) 
开发者ID:pytition,项目名称:Pytition,代码行数:25,代码来源:models.py

示例6: test_addSlugAlreadyExistsKO

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
def test_addSlugAlreadyExistsKO(self):
        max = self.login("max")
        petition = max.petition_set.all()[0]
        slugtext = 'coucou ceci est un slug'
        data = {
            'slugtext': slugtext,
        }
        previous_slug_count = petition.slugmodel_set.count()
        # first time slug insertion
        response = self.client.post(reverse("add_new_slug", args=[petition.id]), data, follow=True)
        self.assertRedirects(response, reverse("edit_petition", args=[petition.id]) + "#tab_social_network_form")
        slug_count = petition.slugmodel_set.count()
        self.assertEqual(slug_count, previous_slug_count + 1)
        new_slug = petition.slugmodel_set.get(slug=slugify(slugtext))
        self.assertEqual(new_slug.slug, slugify(slugtext))
        # second time slug insertion (should fail)
        with self.assertRaises(ValueError):
            response = self.client.post(reverse("add_new_slug", args=[petition.id]), data, follow=True)
            self.assertRedirects(response, reverse("edit_petition", args=[petition.id]) + "#tab_social_network_form")
        slug_count = petition.slugmodel_set.count()
        self.assertEqual(slug_count, previous_slug_count + 1)
        new_slug = petition.slugmodel_set.get(slug=slugify(slugtext))
        self.assertEqual(new_slug.slug, slugify(slugtext)) 
开发者ID:pytition,项目名称:Pytition,代码行数:25,代码来源:tests_AddSlugView.py

示例7: test_CreateOK

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
def test_CreateOK(self):
        john = self.login("john")
        newname = 'my new-org with @ ç special_chars'
        previous_org_numbers = john.organization_set.count()
        data = {
            'name': newname,
        }
        response = self.client.post(reverse("org_create"), data, follow=True)
        self.assertRedirects(response, reverse("user_dashboard"))
        user = response.context['user']
        orgs = user.organization_set.all()
        self.assertEquals(user, john)
        self.assertEquals(len(orgs), previous_org_numbers + 1)
        org = Organization.objects.get(slugname=slugify(newname))
        self.assertEqual(org.slugname, slugify(newname))
        self.assertEqual(org.name, newname)
        admins_perms = Permission.objects.filter(organization=org, can_modify_permissions=True)
        self.assertGreaterEqual(admins_perms.count(), 1) 
开发者ID:pytition,项目名称:Pytition,代码行数:20,代码来源:tests_OrgCreateView.py

示例8: test_CreateAlreadyExistsKO

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
def test_CreateAlreadyExistsKO(self):
        john = self.login("john")
        newname = 'my new-org with @ ç special_chars'
        previous_org_numbers = john.organization_set.count()
        data = {
            'name': newname,
        }
        # first creation
        response = self.client.post(reverse("org_create"), data, follow=True)
        self.assertRedirects(response, reverse("user_dashboard"))
        user = response.context['user']
        orgs = user.organization_set.all()
        self.assertEquals(user, john)
        self.assertEquals(len(orgs), previous_org_numbers + 1)
        org = Organization.objects.get(slugname=slugify(newname))
        self.assertEqual(org.slugname, slugify(newname))
        self.assertEqual(org.name, newname)

        # second creation try
        response = self.client.post(reverse("org_create"), data, follow=True)
        self.assertEquals(response.status_code, 200)
        org_count = user.organization_set.filter(name=newname).count()
        self.assertEquals(org_count, 1) 
开发者ID:pytition,项目名称:Pytition,代码行数:25,代码来源:tests_OrgCreateView.py

示例9: pre_save

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
def pre_save(self, instance, add):
        default = super(AutoSlugField, self).pre_save(instance, add)

        if default or not add or not self.populate_from:
            return default

        value = getattr(instance, self.populate_from)

        if value is None:
            return default

        slug = slugify(smart_text(value))[:self.max_length].strip('-')

        # Update the model’s attribute
        setattr(instance, self.attname, slug)

        return slug

    # def deconstruct(self):
        # TODO: django 1.7 requires this 
开发者ID:SPARLab,项目名称:BikeMaps,代码行数:22,代码来源:models.py

示例10: render_to_response

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
def render_to_response(self, context, **response_kwargs):
        """
        Returns a response containing the exported CSV of selected targets.

        :param context: Context object for this view
        :type context: dict

        :returns: response class with CSV
        :rtype: StreamingHttpResponse
        """
        qs = context['filter'].qs.values()
        file_buffer = export_targets(qs)
        file_buffer.seek(0)  # goto the beginning of the buffer
        response = StreamingHttpResponse(file_buffer, content_type="text/csv")
        filename = "targets-{}.csv".format(slugify(datetime.utcnow()))
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
        return response 
开发者ID:TOMToolkit,项目名称:tom_base,代码行数:19,代码来源:views.py

示例11: save

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
def save(self, force_insert=False,
                   force_update=False,
                   commit=True):
        image = super().save(commit=False)
        image_url = self.cleaned_data['url']
        name = slugify(image.title)
        extension = image_url.rsplit('.', 1)[1].lower()
        image_name = f'{name}.{extension}'

        # download image from the given URL
        response = request.urlopen(image_url)
        image.image.save(image_name,
                         ContentFile(response.read()),
                         save=False)
        if commit:
            image.save()
        return image 
开发者ID:PacktPublishing,项目名称:Django-3-by-Example,代码行数:19,代码来源:forms.py

示例12: add_show

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
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() 
开发者ID:guptachetan1997,项目名称:Episodes,代码行数:19,代码来源:models.py

示例13: reject_source

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
def reject_source(request, source_type, pk):
    if source_type == 'audio':
        source = get_object_or_404(AudioSource, pk=pk)
    elif source_type == 'image':
        source = get_object_or_404(ImageSource, pk=pk)
    else:
        raise Http404

    if source.is_approved:
        messages.error(request, "Source {} is already approved!".format(
            source.title
        ))
    else:
        source.delete()
        messages.success(request, "Source {} has been rejected.".format(source.title))
        logging.getLogger('palanaeum.staff').info("Source %s has been rejected by %s.",
                                                  source.id, request.user)

    return redirect('view_event', source.event_id, slugify(source.event.name)) 
开发者ID:Palanaeum,项目名称:palanaeum,代码行数:21,代码来源:staff_views.py

示例14: category_class

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
def category_class(self):
        if self.category:
            return slugify(self.category)

        return "default" 
开发者ID:kimeraapp,项目名称:pythonjobs.ie,代码行数:7,代码来源:models.py

示例15: save

# 需要导入模块: from django.utils import text [as 别名]
# 或者: from django.utils.text import slugify [as 别名]
def save(self, *args, **kwargs):
        from django.utils.text import slugify
        self.slug = slugify(self.title[:50])
        return super(ProductCategory, self).save(*args, **kwargs) 
开发者ID:fpsw,项目名称:Servo,代码行数:6,代码来源:product.py


注:本文中的django.utils.text.slugify方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。