Python django.utils.text.slugify() Examples

The following are 30 code examples of django.utils.text.slugify(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.text , or try the search function .
Example #1
Source File: views.py    From tom_base with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: models.py    From Episodes with MIT License 6 votes vote down vote up
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() 
Example #3
Source File: signals.py    From aws-workshop with MIT License 6 votes vote down vote up
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 
Example #4
Source File: serializers.py    From marsha with MIT License 6 votes vote down vote up
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),
        ) 
Example #5
Source File: forms.py    From Django-3-by-Example with MIT License 6 votes vote down vote up
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 
Example #6
Source File: models.py    From Pytition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #7
Source File: forms.py    From Django-3-by-Example with MIT License 6 votes vote down vote up
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 
Example #8
Source File: staff_views.py    From palanaeum with GNU Affero General Public License v3.0 6 votes vote down vote up
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)) 
Example #9
Source File: tests_AddSlugView.py    From Pytition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example #10
Source File: views.py    From heltour with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: tests_OrgCreateView.py    From Pytition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #12
Source File: tests_OrgCreateView.py    From Pytition with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #13
Source File: models.py    From BikeMaps with MIT License 6 votes vote down vote up
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 
Example #14
Source File: models.py    From fossevents.in with MIT License 5 votes vote down vote up
def slug(self):
        return slugify(self.name)

    # TODO: return date in localize timezone 
Example #15
Source File: views.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def event_feed_no_slug(request, event_id):
    """
    Redirect to a version with slug in URL.
    """
    event = get_object_or_404(Event, pk=event_id)
    return redirect('event_feed', event_id, slugify(event.name)) 
Example #16
Source File: test_events.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_prev_url(self):
        self.assertEqual(
            self.event1.get_prev_url(),
            None
        )

        self.assertEqual(
            self.event2.get_prev_url(),
            reverse('view_event', args=(self.event1.pk, slugify(self.event1.name)))
        ) 
Example #17
Source File: models.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_next_url(self):
        next_event = Event.all_visible.filter(date__lte=self.date)\
            .exclude(pk=self.pk).values_list("id", "name").first()

        if next_event:
            return reverse('view_event', args=(next_event[0], slugify(next_event[1]))) 
Example #18
Source File: models.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_prev_url(self):
        prev_event = Event.all_visible.filter(date__gte=self.date)\
            .exclude(pk=self.pk).values_list("id", "name").last()

        if prev_event:
            return reverse('view_event', args=(prev_event[0], slugify(prev_event[1]))) 
Example #19
Source File: views.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def view_entry(request, entry_id):
    """
    Redirect user to proper event and entry.
    """
    entry = get_object_or_404(Entry, pk=entry_id)
    return redirect(reverse('view_event', args=(entry.event_id, slugify(entry.event.name))) + '#e{}'.format(entry.id)) 
Example #20
Source File: category.py    From tramcar with MIT License 5 votes vote down vote up
def slug(self):
        return slugify(self.name) 
Example #21
Source File: conftest.py    From dissemin with GNU Affero General Public License v3.0 5 votes vote down vote up
def mock_crossref(requests_mocker):
    def request_callback(request):
        query = parse_qs(urlparse(request.url).query)
        query_f = query['filter'][0].split(',')
        slugified_dois = [slugify(item.split(':')[1]) for item in query_f]
        # Since the file name might be to long if a lot of DOIs are requested, we hash them
        m = hashlib.sha256()
        m.update("-".join(slugified_dois).encode('utf-8'))
        f_name = '{}.json'.format(m.hexdigest())
        f_path = os.path.join(settings.BASE_DIR, 'test_data', 'citeproc', 'crossref', f_name)
        print("curl \"{}\" > {}".format(request.url, f_path))
        with open(f_path, 'r') as f:
            body = f.read()
            return (200, {}, body)

    requests_mocker.add_callback(
        requests_mocker.GET,
        re.compile(r'https://api.crossref.org/works'),
        callback=request_callback
    )
    requests_mocker.add_passthru('http://doi-cache.dissem.in/zotero/')
    requests_mocker.add_passthru('http://localhost') # Our VNU server runs on localhost
    requests_mocker.add_passthru('https://pub.orcid.org/')
    requests_mocker.add_passthru('https://sandbox.zenodo.org/')

    return requests_mocker 
Example #22
Source File: conftest.py    From dissemin with GNU Affero General Public License v3.0 5 votes vote down vote up
def mock_doi(requests_mocker):
    def request_callback(request):
        doi = request.path_url[1:]
        f_name = '{}.json'.format(slugify(doi))
        f_path = os.path.join(settings.BASE_DIR, 'test_data', 'citeproc', 'doi', f_name)
        headers = {
            'Content-Type' : 'application/citeproc+json'
        }
        try:
            with open(f_path, 'r') as f:
                body = f.read()
                return (200, headers, body)
        except FileNotFoundError:
            print('File not found: {} - Returning 404'.format(f_path))
            return (404, {}, None)

    requests_mocker.add_callback(
        requests_mocker.GET,
        re.compile('{}(.*)'.format(settings.DOI_RESOLVER_ENDPOINT)),
        callback=request_callback
    )
    requests_mocker.add_passthru('http://doi-cache.dissem.in/zotero/')
    requests_mocker.add_passthru('https://doi-cache.dissem.in/zotero/')
    requests_mocker.add_passthru('http://localhost') # Our VNU server runs on localhost
    requests_mocker.add_passthru('https://pub.orcid.org/')
    requests_mocker.add_passthru('https://sandbox.zenodo.org/')

    return requests_mocker 
Example #23
Source File: test_api.py    From django-klingon with GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.library = Library.objects.create(
            name=u"Indepent",
            description="All in ebooks",
        )
        self.es_name = u"Independiente"
        self.es_description = 'Todo en ebooks'
        self.es_slug = slugify(self.es_name) 
Example #24
Source File: models.py    From Django-3-by-Example with MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs) 
Example #25
Source File: models.py    From Django-3-by-Example with MIT License 5 votes vote down vote up
def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs) 
Example #26
Source File: models.py    From django-private-storage with Apache License 2.0 5 votes vote down vote up
def upload_subfolder2(self):
        # Slightly incorrect usage by developers, joining locally.
        return os.path.join(slugify(self.customer), 'sub2') 
Example #27
Source File: test_api.py    From django-klingon with GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.book = Book.objects.create(
            title="The Raven",
            description="The Raven is a narrative poem",
            publication_date=datetime.date(1845, 1, 1),
            slug="the-raven"
        )
        self.es_title = u"El Cuervo"
        self.es_description = 'El Cuervo es un poema narrativo'
        self.es_slug = slugify(self.es_title) 
Example #28
Source File: models.py    From django-private-storage with Apache License 2.0 5 votes vote down vote up
def upload_subfolder(self):
        # self.pk is still None here!
        return [slugify(self.customer)] 
Example #29
Source File: test_commands.py    From django-klingon with GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.book = Book.objects.create(
            title="The Raven",
            description="The Raven is a narrative poem",
            publication_date=datetime.date(1845, 1, 1),
            slug="the-raven",
        )
        self.es_title = u"El Cuervo"
        self.es_description = 'El Cuervo es un poema narrativo'
        self.es_slug = slugify(self.es_title) 
Example #30
Source File: test_api.py    From django-klingon with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_translation_slug(self):
        self.library.set_translation('es', 'name', self.es_name)
        self.library.set_translation('es', 'description', self.es_description)
        self.assertEqual(self.library.slug, slugify(self.library.name))
        self.assertEqual(self.library.get_translation('es', 'name'),
                          self.es_name)
        self.assertEqual(self.library.get_translation('es', 'slug'),
                          self.es_slug)