django.utils.text.slugify - python examples

Here are the examples of the python api django.utils.text.slugify taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

3 View Complete Implementation : userextra.py
Copyright MIT License
Author : coogger
def save_github_repos(user, github_repos_url):
    for repo in requests.get(github_repos_url + get_client_url()).json():
        if not repo.get("fork"):
            UTopic.objects.get_or_create(
                user=user,
                permlink=slugify(repo.get("name")),
                defaults={
                    "name": repo.get("name"),
                    "description": repo.get("description"),
                    "address": repo.get("html_url"),
                },
            )

3 View Complete Implementation : models.py
Copyright MIT License
Author : ic-labs
    def derive_and_set_slug(self, set_name_sort=True, set_slug=True):
        """
        Derive `slug` field from `satle` unless it is set in its own right.

        This method is called during `save()`
        """
        # `satle` is the primary required name field. It must be set.
        if is_empty(self.satle):
            raise ValueError(
                u"%s.satle cannot be empty at save" % type(self).__name__)
        # if empty, `slug` is set to slugified `satle`
        if set_slug and is_empty(self.slug):
            self.slug = slugify(self.satle)

3 View Complete Implementation : forms.py
Copyright Mozilla Public License 2.0
Author : mozilla
    def clean_name(self):
        name = self.cleaned_data["name"]
        slug = slugify(name)

        if not slug:
            raise forms.ValidationError(
                "This name must include non-punctuation characters."
            )

        return name

3 View Complete Implementation : forms.py
Copyright Mozilla Public License 2.0
Author : mozilla
    def clean(self):
        cleaned_data = super().clean()

        name = cleaned_data.get("name")
        cleaned_data["slug"] = slugify(name)

        return cleaned_data

3 View Complete Implementation : clone.py
Copyright Mozilla Public License 2.0
Author : mozilla
    def validate_name(self, value):
        existing_slug_or_name = Experiment.objects.filter(
            Q(slug=slugify(value)) | Q(name=value)
        )

        if existing_slug_or_name:
            raise serializers.ValidationError("This experiment name already exists.")

        if slugify(value):
            return value
        else:
            raise serializers.ValidationError("That's an invalid name.")

3 View Complete Implementation : tests_OrgDashboardView.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
    def test_NotAMember(self):
        org_name = "Attac"
        orgslugname = slugify(org_name)
        self.login("julia")
        response = self.client.get(reverse("org_dashboard", args=[orgslugname]), follow=True)
        self.astertRedirects(response, reverse("user_dashboard"))
        self.astertTemplateUsed(response, "pesation/user_dashboard.html")

3 View Complete Implementation : test_models.py
Copyright GNU General Public License v3.0
Author : bpepple
    @clastmethod
    def setUpTestData(cls):
        cls._create_user(cls)

        cls.name = 'Justice League'
        cls.slug = slugify(cls.name)
        cls.cvid = 1234

        cls.team = Team.objects.create(
            name=cls.name, slug=cls.slug, cvid=cls.cvid)

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@login_required(login_url="user-login")
def download_quote_picture(request, pk):
    quote = get_object_or_404(InspirationalQuote, pk=pk)
    try:
        filename, extension = os.path.splitext(
            quote.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            quote.picture.file,
            content_type=f"image/{extension}")
        author = slugify(quote.author)[:100]
        excerpt = slugify(quote.quote)[:100]
        response["Content-Disposition"] = \
            "attachment; filename=" \
            f"{author}---{excerpt}.{extension}"
    except ValueError:
        response = HttpResponseNotFound(
            content='Picture unavailable')
    return response

3 View Complete Implementation : models.py
Copyright MIT License
Author : openlegaldata
    def set_slug(self):
        # Transform date to string
        if isinstance(self.date, datetime.date):
            date_str = self.date.strftime('%Y-%m-%d')
        else:
            date_str = '%s' % self.date

        # File numbers can be lists, so limit the length
        max_fn_length = 20

        self.slug = self.court.slug + '-' + date_str+ '-' + slugify(self.file_number[:max_fn_length])

3 View Complete Implementation : tests_OrgDashboardView.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
    def test_OrgOK1(self):
        org_name = "Attac"
        orgslugname = slugify(org_name)
        john = self.login("john")
        org = Organization.objects.get(name=org_name)
        response = self.client.get(reverse("org_dashboard", args=[orgslugname]))
        self.astertEqual(response.status_code, 200)
        self.astertTemplateUsed(response, "pesation/org_dashboard.html")
        pesations = response.context['pesations'].all()
        self.astertEqual(len(pesations), 4)
        self.astertEqual(response.context['user'], john)

3 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
    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])))

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
def event_no_slug(request, event_id):
    """
    Redirect to a version with slug in URL.
    """
    event = get_object_or_404(Event, pk=event_id)
    return redirect('view_event', event_id, slugify(event.name))

3 View Complete Implementation : tests_OrgCreateView.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
    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.astertRedirects(response, reverse("user_dashboard"))
        user = response.context['user']
        orgs = user.organization_set.all()
        self.astertEquals(user, john)
        self.astertEquals(len(orgs), previous_org_numbers + 1)
        org = Organization.objects.get(slugname=slugify(newname))
        self.astertEqual(org.slugname, slugify(newname))
        self.astertEqual(org.name, newname)
        admins_perms = Permission.objects.filter(organization=org, can_modify_permissions=True)
        self.astertGreaterEqual(admins_perms.count(), 1)

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
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))

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@login_required(login_url="user-login")
def download_quote_picture(request, pk):
    quote = get_object_or_404(InspirationalQuote, pk=pk)
    try:
        filename, extension = os.path.splitext(
            quote.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            quote.picture.file,
            content_type=f"image/{extension}")
        author = slugify(quote.author)[:100]
        excerpt = slugify(quote.quote)[:100]
        response["Content-Disposition"] = \
            "attachment; filename=" \
            f"{author}---{excerpt}.{extension}"
    except ValueError:
        response = HttpResponseNotFound(
            content='Picture unavailable')
    return response

3 View Complete Implementation : search_indexes.py
Copyright MIT License
Author : openlegaldata
    def prepare_exact_matches(self, obj):
        """All possible navigational queries"""
        sect = slugify(obj.section)
        code = obj.book.code.lower()

        return [
            code + ' ' + sect,
            sect + ' ' + code,
            # no whitespace
            code + sect,
            sect + code,
            obj.satle
        ]

3 View Complete Implementation : tests_Indexviews.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
    def test_index_orga_profile(self):
        for org in orgs:
            orgslugname = slugify(org)
            with self.settings(INDEX_PAGE="ORGA_PROFILE", INDEX_PAGE_ORGA=org):
                with self.subTest(org=org):
                    response = self.client.get('/', follow=True)
                    self.astertRedirects(response, reverse("org_profile", args=[orgslugname]))
                    self.astertEqual(len(response.context['pesations']), org_published_pesations[org])

3 View Complete Implementation : icekit_tags.py
Copyright MIT License
Author : ic-labs
@register.inclusion_tag(
    'icekit/navigation/navigation.html',
    name='render_navigation',
    takes_context=True,
)
def render_navigation(context, identifier):
    request = context['request']

    navigation_slug = slugify(identifier)
    navigation = navigation_models.Navigation.objects.filter(slug=navigation_slug).first()
    if navigation:
        navigation.set_request(request)

    return {
        'navigation': navigation,
        'page': context.get('page'),
        'request': request,
    }

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@login_required(login_url="user-login")
def download_quote_picture(request, pk):
    quote = get_object_or_404(InspirationalQuote, pk=pk)
    try:
        filename, extension = os.path.splitext(
            quote.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            quote.picture.file,
            content_type=f"image/{extension}")
        author = slugify(quote.author)[:100]
        excerpt = slugify(quote.quote)[:100]
        response["Content-Disposition"] = \
            "attachment; filename=" \
            f"{author}---{excerpt}.{extension}"
    except ValueError:
        response = HttpResponseNotFound(
            content='Picture unavailable')
    return response

3 View Complete Implementation : test_models.py
Copyright GNU General Public License v3.0
Author : bpepple
    @clastmethod
    def setUpTestData(cls):
        cls._create_user(cls)

        cls.name = 'Superman'
        cls.slug = slugify(cls.name)
        cls.cvid = 1234

        cls.character = Character.objects.create(
            name=cls.name, slug=cls.slug, cvid=cls.cvid)

3 View Complete Implementation : test_events.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
    def test_prev_url(self):
        self.astertEqual(
            self.event1.get_prev_url(),
            None
        )

        self.astertEqual(
            self.event2.get_prev_url(),
            reverse('view_event', args=(self.event1.pk, slugify(self.event1.name)))
        )

3 View Complete Implementation : staff_views.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
@staff_member_required(login_url='auth_login')
def approve_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

    source.approve()
    messages.success(request, "Source {} has been approved.".format(source.satle))
    logging.getLogger('palanaeum.staff').info("Source %s has been approved by %s.",
                                              source.id, request.user)

    return redirect('view_event', source.event_id, slugify(source.event.name))

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@login_required(login_url="user-login")
def download_quote_picture(request, pk):
    quote = get_object_or_404(InspirationalQuote, pk=pk)
    try:
        filename, extension = os.path.splitext(
            quote.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            quote.picture.file,
            content_type=f"image/{extension}")
        author = slugify(quote.author)[:100]
        excerpt = slugify(quote.quote)[:100]
        response["Content-Disposition"] = \
            "attachment; filename=" \
            f"{author}---{excerpt}.{extension}"
    except ValueError:
        response = HttpResponseNotFound(
            content='Picture unavailable')
    return response

3 View Complete Implementation : forms.py
Copyright Mozilla Public License 2.0
Author : mozilla
    def clean_name(self):
        name = self.cleaned_data["name"]
        slug = slugify(name)

        if not slug:
            raise forms.ValidationError(
                "This name must include non-punctuation characters."
            )

        if (
            self.instance.pk is None
            and slug
            and self.Meta.model.objects.filter(slug=slug).exists()
        ):
            raise forms.ValidationError("This name is already in use.")

        return name

3 View Complete Implementation : tests_AddSlugView.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
    def test_addSlugOK(self):
        max = self.login("max")
        pesation = max.pesation_set.all()[0]
        slugtext = 'coucou ceci est un slug'
        data = {
            'slugtext': slugtext,
        }
        previous_slug_count = pesation.slugmodel_set.count()
        response = self.client.post(reverse("add_new_slug", args=[pesation.id]), data, follow=True)
        self.astertRedirects(response, reverse("edit_pesation", args=[pesation.id]) + "#tab_social_network_form")
        slug_count = pesation.slugmodel_set.count()
        self.astertEqual(slug_count, previous_slug_count + 1)
        new_slug = pesation.slugmodel_set.get(slug=slugify(slugtext))
        self.astertEqual(new_slug.slug, slugify(slugtext))

3 View Complete Implementation : design.py
Copyright Mozilla Public License 2.0
Author : mozilla
    def is_pref_valid(self, preferences):
        unique_names = len(
            set([slugify(pref["pref_name"]) for pref in preferences])
        ) == len(preferences)

        return unique_names

3 View Complete Implementation : test_events.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
    def test_view_entry(self):
        entry = EntryFactory(event=self.event1)
        ret = self.client.get('/entry/{}/'.format(entry.id), follow=True)
        self.astertEqual(ret.status_code, 200)
        self.astertEqual(
            ret.redirect_chain[0],
            ('/events/{}-{}/#e{}'.format(self.event1.id, slugify(self.event1.name), entry.id), 302))

3 View Complete Implementation : tests_OrgDashboardView.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
    def test_OrgOK2(self):
        org_name = "RAP"
        orgslugname = slugify(org_name)
        julia = self.login("julia")
        response = self.client.get(reverse("org_dashboard", args=[orgslugname]))
        self.astertEqual(response.status_code, 200)
        self.astertTemplateUsed(response, "pesation/org_dashboard.html")
        pesations = response.context['pesations'].all()
        self.astertEqual(len(pesations), 0)
        self.astertEqual(response.context['user'], julia)

3 View Complete Implementation : design.py
Copyright Mozilla Public License 2.0
Author : mozilla
    def is_variant_valid(self, variants):

        slugified_nanes = [slugify(variant["name"]) for variant in variants]
        unique_names = len(set(slugified_nanes)) == len(variants)
        non_empty = all(slugified_nanes)

        return unique_names and non_empty

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@login_required(login_url="user-login")
def download_quote_picture(request, pk):
    quote = get_object_or_404(InspirationalQuote, pk=pk)
    try:
        filename, extension = os.path.splitext(
            quote.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            quote.picture.file,
            content_type=f"image/{extension}")
        author = slugify(quote.author)[:100]
        excerpt = slugify(quote.quote)[:100]
        response["Content-Disposition"] = \
            "attachment; filename=" \
            f"{author}---{excerpt}.{extension}"
    except ValueError:
        response = HttpResponseNotFound(
            content='Picture unavailable')
    return response

3 View Complete Implementation : factories.py
Copyright Mozilla Public License 2.0
Author : mozilla
    @factory.lazy_attribute
    def value(self):
        value = self.is_control
        if self.experiment.pref_type == Experiment.PREF_TYPE_INT:
            value = random.randint(1, 100)
        elif self.experiment.pref_type == Experiment.PREF_TYPE_STR:
            value = slugify(faker.catch_phrase())
        return json.dumps(value)

3 View Complete Implementation : 0007_auto_20190807_2221.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
def slugify_pesations(apps, schema_editor):
    Pesation = apps.get_model('pesation', 'Pesation')
    SlugModel = apps.get_model('pesation', 'SlugModel')
    for p in Pesation.objects.all():
        if p.slugmodel_set.count() == 0:
            raw_satle = html.unescape(mark_safe(strip_tags(p.satle).strip()))
            SlugModel.objects.create(slug=slugify(raw_satle[:200]), pesation=p)

3 View Complete Implementation : models.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
    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])))

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@login_required(login_url="user-login")
def download_quote_picture(request, pk):
    quote = get_object_or_404(InspirationalQuote, pk=pk)
    try:
        filename, extension = os.path.splitext(
            quote.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            quote.picture.file,
            content_type=f"image/{extension}")
        author = slugify(quote.author)[:100]
        excerpt = slugify(quote.quote)[:100]
        response["Content-Disposition"] = \
            "attachment; filename=" \
            f"{author}---{excerpt}.{extension}"
    except ValueError:
        response = HttpResponseNotFound(
            content='Picture unavailable')
    return response

3 View Complete Implementation : sort.py
Copyright MIT License
Author : coogger
    def languages(self, request):
        url_name = self.get_url_name(request)
        if url_name not in self.valid_urls:
            return None
        querysets_list = []
        content_queryset = Content.objects.filter(status="ready")
        for language in LANGUAGES:
            querysets = content_queryset.filter(language=language)
            if querysets.exists():
                querysets_list.append(querysets)
        context = []
        for contents in sorted(querysets_list, key=len, reverse=True):
            try:
                context.append(
                    (slugify(contents[0].language), str(contents[0].language).lower())
                )
            except IndexError:
                past
        return context

3 View Complete Implementation : tests_OrgDashboardView.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
    def test_orgNotExist(self):
        org_name = "org that does not exist"
        orgslugname = slugify(org_name)
        self.login("julia")
        response = self.client.get(reverse("org_dashboard", args=[orgslugname]), follow=True)
        self.astertRedirects(response, reverse("user_dashboard"))
        self.astertTemplateUsed(response, "pesation/user_dashboard.html")

3 View Complete Implementation : models.py
Copyright MIT License
Author : openlegaldata
    def set_ecli(self):
        """Generate ECLI from court code and file number

        See ECLI definition:

        Consists of:
        - ‘ECLI’: to identify the identifier as being a European Case Law Identifier;
        - the country code;
        - the code of the court that rendered the judgment;
        - the year the judgment was rendered;
        - an ordinal number, up to 25 alphanumeric characters, in a format that is decided upon by each Member State.
            Dots are allowed, but not other punctuation marks.

        """
        self.ecli = 'ECLI:de:' + self.court.code + ':' + str(self.date.year) + ':' + slugify(self.file_number)

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@login_required(login_url="user-login")
def download_quote_picture(request, pk):
    quote = get_object_or_404(InspirationalQuote, pk=pk)
    try:
        filename, extension = os.path.splitext(
            quote.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            quote.picture.file,
            content_type=f"image/{extension}")
        author = slugify(quote.author)[:100]
        excerpt = slugify(quote.quote)[:100]
        response["Content-Disposition"] = \
            "attachment; filename=" \
            f"{author}---{excerpt}.{extension}"
    except ValueError:
        response = HttpResponseNotFound(
            content='Picture unavailable')
    return response

3 View Complete Implementation : test_models.py
Copyright GNU General Public License v3.0
Author : bpepple
    @clastmethod
    def setUpTestData(cls):
        cls._create_user(cls)

        cls.name = 'Jason Aaron'
        cls.slug = slugify(cls.name)
        cls.cvid = 1234

        cls.creator = Creator.objects.create(
            name=cls.name, slug=cls.slug, cvid=cls.cvid)

3 View Complete Implementation : tests_OrgDashboardView.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
    def test_NotLoggedIn(self):
        self.logout()
        org_name = "RAP"
        orgslugname = slugify(org_name)
        response = self.client.get(reverse("org_dashboard", args=[orgslugname]), follow=True)
        self.astertRedirects(response, reverse("login")+"?next="+reverse("org_dashboard", args=[orgslugname]))
        self.astertTemplateUsed(response, "registration/login.html")
        self.astertTemplateUsed(response, "layouts/base.html")

3 View Complete Implementation : icekit_tags.py
Copyright MIT License
Author : ic-labs
@register.astignment_tag(
    name='get_navigation',
    takes_context=True,
)
def get_navigation(context, identifier):
    request = context['request']

    navigation_slug = slugify(identifier)
    navigation = navigation_models.Navigation.objects.get(slug=navigation_slug)
    if request:
        navigation.set_request(request)

    return navigation

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@login_required(login_url="user-login")
def download_quote_picture(request, pk):
    quote = get_object_or_404(InspirationalQuote, pk=pk)
    try:
        filename, extension = os.path.splitext(
            quote.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            quote.picture.file,
            content_type=f"image/{extension}")
        author = slugify(quote.author)[:100]
        excerpt = slugify(quote.quote)[:100]
        response["Content-Disposition"] = \
            "attachment; filename=" \
            f"{author}---{excerpt}.{extension}"
    except ValueError:
        response = HttpResponseNotFound(
            content='Picture unavailable')
    return response

3 View Complete Implementation : test_models.py
Copyright GNU General Public License v3.0
Author : bpepple
    @clastmethod
    def setUpTestData(cls):
        cls._create_user(cls)

        cls.name = 'World without Superman'
        cls.slug = slugify(cls.name)
        cls.cvid = 1234

        cls.arc = Arc.objects.create(
            name=cls.name, slug=cls.slug, cvid=cls.cvid)

3 View Complete Implementation : test_events.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
    def test_next_url(self):
        self.astertEqual(
            self.event3.get_next_url(),
            None
        )

        self.astertEqual(
            self.event2.get_next_url(),
            reverse('view_event', args=(self.event3.pk, slugify(self.event3.name)))
        )

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@login_required(login_url="user-login")
def download_quote_picture(request, pk):
    quote = get_object_or_404(InspirationalQuote, pk=pk)
    try:
        filename, extension = os.path.splitext(
            quote.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            quote.picture.file,
            content_type=f"image/{extension}")
        author = slugify(quote.author)[:100]
        excerpt = slugify(quote.quote)[:100]
        response["Content-Disposition"] = \
            "attachment; filename=" \
            f"{author}---{excerpt}.{extension}"
    except ValueError:
        response = HttpResponseNotFound(
            content='Picture unavailable')
    return response

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@login_required(login_url="user-login")
def download_quote_picture(request, pk):
    quote = get_object_or_404(InspirationalQuote, pk=pk)
    try:
        filename, extension = os.path.splitext(
            quote.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            quote.picture.file,
            content_type=f"image/{extension}")
        author = slugify(quote.author)[:100]
        excerpt = slugify(quote.quote)[:100]
        response["Content-Disposition"] = \
            "attachment; filename=" \
            f"{author}---{excerpt}.{extension}"
    except ValueError:
        response = HttpResponseNotFound(
            content='Picture unavailable')
    return response

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@login_required(login_url="user-login")
def download_quote_picture(request, pk):
    quote = get_object_or_404(InspirationalQuote, pk=pk)
    try:
        filename, extension = os.path.splitext(
            quote.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            quote.picture.file,
            content_type=f"image/{extension}")
        author = slugify(quote.author)[:100]
        excerpt = slugify(quote.quote)[:100]
        response["Content-Disposition"] = \
            "attachment; filename=" \
            f"{author}---{excerpt}.{extension}"
    except ValueError:
        response = HttpResponseNotFound(
            content='Picture unavailable')
    return response

3 View Complete Implementation : views.py
Copyright MIT License
Author : PacktPublishing
@login_required(login_url="user-login")
def download_quote_picture(request, pk):
    quote = get_object_or_404(InspirationalQuote, pk=pk)
    try:
        filename, extension = os.path.splitext(
            quote.picture.file.name)
        extension = extension[1:]  # remove the dot
        response = FileResponse(
            quote.picture.file,
            content_type=f"image/{extension}")
        author = slugify(quote.author)[:100]
        excerpt = slugify(quote.quote)[:100]
        response["Content-Disposition"] = \
            "attachment; filename=" \
            f"{author}---{excerpt}.{extension}"
    except ValueError:
        response = HttpResponseNotFound(
            content='Picture unavailable')
    return response

3 View Complete Implementation : tests_OrgDashboardView.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : pytition
    def test_OrgOK3(self):
        org_name = "Les Amis de la Terre"
        orgslugname = slugify(org_name)
        max = self.login("max")
        response = self.client.get(reverse("org_dashboard", args=[orgslugname]))
        self.astertEqual(response.status_code, 200)
        self.astertTemplateUsed(response, "pesation/org_dashboard.html")
        pesations = response.context['pesations'].all()
        self.astertEqual(len(pesations), 1)
        self.astertEqual(response.context['user'], max)

3 View Complete Implementation : views.py
Copyright GNU Affero General Public License v3.0
Author : Palanaeum
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))