Python django.http.HttpResponsePermanentRedirect() Examples

The following are 30 code examples for showing how to use django.http.HttpResponsePermanentRedirect(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.http , or try the search function .

Example 1
Project: normandy   Author: mozilla   File: middleware.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def process_request(self, request):
        response = super().process_request(request)
        if response is not None:
            assert type(response) is http.HttpResponsePermanentRedirect
            patch_cache_control(response, public=True, max_age=settings.HTTPS_REDIRECT_CACHE_TIME)

            # Pull out just the HTTP headers from the rest of the request meta
            headers = {
                key.lstrip("HTTP_"): value
                for (key, value) in request.META.items()
                if key.startswith("HTTP_") or key == "CONTENT_TYPE" or key == "CONTENT_LENGTH"
            }

            logger.debug(
                f"Served HTTP to HTTPS redirect for {request.path}",
                extra={
                    "code": DEBUG_HTTP_TO_HTTPS_REDIRECT,
                    "method": request.method,
                    "body": request.body.decode("utf-8"),
                    "path": request.path,
                    "headers": headers,
                },
            )
        return response 
Example 2
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
def activate(request, activation_key):
    context = {'info_title': _(u'oshibka')}
    user, user_info = AdmissionRegistrationProfile.objects.activate_user(activation_key)
    if user:
        if user_info:
            set_user_info(user, json.loads(user_info))

        contest_id = contest_register(user)
        if contest_id:
            return HttpResponsePermanentRedirect(settings.CONTEST_URL + 'contest/' + str(contest_id))
        else:
            context['info_text'] = _(u'oshibka_registracii_v_contest')
    else:
        context['info_text'] = _(u'nevernyy_kod_aktivatsii')

    return render(request, 'info_page.html', context) 
Example 3
Project: bioforum   Author: reBiocoder   File: views.py    License: MIT License 6 votes vote down vote up
def flatpage(request, url):
    """
    Public interface to the flat page view.

    Models: `flatpages.flatpages`
    Templates: Uses the template defined by the ``template_name`` field,
        or :template:`flatpages/default.html` if template_name is not defined.
    Context:
        flatpage
            `flatpages.flatpages` object
    """
    if not url.startswith('/'):
        url = '/' + url
    site_id = get_current_site(request).id
    try:
        f = get_object_or_404(FlatPage, url=url, sites=site_id)
    except Http404:
        if not url.endswith('/') and settings.APPEND_SLASH:
            url += '/'
            f = get_object_or_404(FlatPage, url=url, sites=site_id)
            return HttpResponsePermanentRedirect('%s/' % request.path)
        else:
            raise
    return render_flatpage(request, f) 
Example 4
Project: waliki   Author: mgaitan   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def detail(request, slug, raw=False):

    slug = slug.strip('/')

    # handle redirects first
    try:
        redirect = Redirect.objects.get(old_slug=slug)      # noqa
        if redirect.status_code == 302:
            return HttpResponseRedirect(redirect.get_absolute_url())
        return HttpResponsePermanentRedirect(redirect.get_absolute_url())
    except Redirect.DoesNotExist:
        pass

    try:
        page = Page.objects.get(slug=slug)
    except Page.DoesNotExist:
        page = None
    if raw and page:
        return HttpResponse(page.raw, content_type='text/plain; charset=utf-8')
    elif raw:
        raise Http404

    context = {'page': page, 'slug': slug}
    return render(request, 'waliki/detail.html', context) 
Example 5
Project: tramcar   Author: tramcar   File: categories.py    License: MIT License 6 votes vote down vote up
def categories_show(request, category_id, slug=None):
    category = get_object_or_404(
                   Category,
                   pk=category_id,
                   site_id=get_current_site(request).id
    )

    if slug is None:
        return HttpResponsePermanentRedirect(category.get_absolute_url())

    jobs = Job.objects.filter(site_id=get_current_site(request).id) \
                      .filter(category_id=category_id) \
                      .filter(paid_at__isnull=False) \
                      .filter(expired_at__isnull=True) \
                      .order_by('-paid_at')
    form = SubscribeForm()
    meta_desc = 'Browse a list of all active %s jobs' % category.name
    feed_url = reverse('categories_feed', args=(category.id, category.slug(),))
    title = '%s Jobs' % category.name
    context = {'meta_desc': meta_desc,
               'link_rss': feed_url,
               'title': title,
               'form': form,
               'jobs': jobs}
    return render(request, 'job_board/jobs_index.html', context) 
Example 6
Project: WCnife   Author: imjdl   File: views.py    License: MIT License 6 votes vote down vote up
def uploadFile(request):
    if request.method == 'POST':
        url = request.session.get("url")
        pwd = request.session.get("pwd")
        s = SendCode(url=url, pwd=pwd)
        newfile = request.FILES.get("newfile")
        now_filepath = request.session.get('now_path')
        path = now_filepath.split('/')[-1]
        filename = newfile.name
        filepath = now_filepath + "/" + filename
        content = ""
        for chunk in newfile.chunks():
            content = chunk.hex()
        res = s.uploadFile(filepath, content)
        return JsonResponse({"status": res, "path": path})
    else:
        return HttpResponsePermanentRedirect("/") 
Example 7
Project: WCnife   Author: imjdl   File: views.py    License: MIT License 6 votes vote down vote up
def createFile(request):
    if request.method == 'POST':
        url = request.session.get("url")
        pwd = request.session.get("pwd")
        s = SendCode(url=url, pwd=pwd)
        now_filepath = request.session.get('now_path')
        path = now_filepath.split('/')[-1]
        filename = request.POST.get('filename')
        content = request.POST.get('content')
        if content is None:
            content = ''
        filepath = now_filepath + '/' + filename
        res = s.createFile(filepath, content)
        return JsonResponse({"status": res, "path": path})
    else:
        return HttpResponsePermanentRedirect("/") 
Example 8
Project: django_OA   Author: abaoMAO   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get("username", "")
            pass_word = request.POST.get("password", "")
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponsePermanentRedirect(reverse('index'))
                else:
                    return render(request, "user_login.html", {"msg": "邮箱未激活"})
            else:
                return render(request, "user_login.html", {"msg": "用户名或密码错误"})
        else:
            return render(request, "user_login.html", {"login_form": login_form}) 
Example 9
Project: nyc-councilmatic   Author: datamade   File: views.py    License: MIT License 6 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        slug = self.kwargs['slug']

        try:
            bill = self.model.objects.get(slug=slug)
            response = super().dispatch(request, *args, **kwargs)
        except NYCBill.DoesNotExist:
            bill = None

        if bill is None:
            try:
                bill = self.model.objects.get(slug__startswith=slug)
                response = HttpResponsePermanentRedirect(reverse('bill_detail', args=[bill.slug]))
            except NYCBill.DoesNotExist:
                try: 
                    one, two, three, four = slug.split('-')
                    short_slug = slug.replace('-' + four, '')
                    bill = self.model.objects.get(slug__startswith=short_slug)
                    response = HttpResponsePermanentRedirect(reverse('bill_detail', args=[bill.slug]))
                except:
                    response = HttpResponseNotFound()

        return response 
Example 10
Project: nyc-councilmatic   Author: datamade   File: views.py    License: MIT License 6 votes vote down vote up
def dispatch(self, request, *args, **kwargs):
        slug = self.kwargs['slug']

        try:
            committee = self.model.objects.get(slug=slug)
            response = super().dispatch(request, *args, **kwargs)
        except Organization.DoesNotExist:
            committee = None

        if committee is None:
            try:
                slug = slug.replace(',', '').replace('\'', '')
                committee = self.model.objects.get(slug__startswith=slug)
                response = HttpResponsePermanentRedirect(reverse('committee_detail', args=[committee.slug]))
            except Organization.DoesNotExist:
                response = HttpResponseNotFound()

        return response 
Example 11
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: views.py    License: MIT License 6 votes vote down vote up
def flatpage(request, url):
    """
    Public interface to the flat page view.

    Models: `flatpages.flatpages`
    Templates: Uses the template defined by the ``template_name`` field,
        or :template:`flatpages/default.html` if template_name is not defined.
    Context:
        flatpage
            `flatpages.flatpages` object
    """
    if not url.startswith('/'):
        url = '/' + url
    site_id = get_current_site(request).id
    try:
        f = get_object_or_404(FlatPage, url=url, sites=site_id)
    except Http404:
        if not url.endswith('/') and settings.APPEND_SLASH:
            url += '/'
            f = get_object_or_404(FlatPage, url=url, sites=site_id)
            return HttpResponsePermanentRedirect('%s/' % request.path)
        else:
            raise
    return render_flatpage(request, f) 
Example 12
Project: python2017   Author: bpgc-cte   File: views.py    License: MIT License 6 votes vote down vote up
def flatpage(request, url):
    """
    Public interface to the flat page view.

    Models: `flatpages.flatpages`
    Templates: Uses the template defined by the ``template_name`` field,
        or :template:`flatpages/default.html` if template_name is not defined.
    Context:
        flatpage
            `flatpages.flatpages` object
    """
    if not url.startswith('/'):
        url = '/' + url
    site_id = get_current_site(request).id
    try:
        f = get_object_or_404(FlatPage, url=url, sites=site_id)
    except Http404:
        if not url.endswith('/') and settings.APPEND_SLASH:
            url += '/'
            f = get_object_or_404(FlatPage, url=url, sites=site_id)
            return HttpResponsePermanentRedirect('%s/' % request.path)
        else:
            raise
    return render_flatpage(request, f) 
Example 13
Project: simonwillisonblog   Author: simonw   File: middleware.py    License: Apache License 2.0 6 votes vote down vote up
def redirect_middleware(get_response):
    def middleware(request):
        path = request.path.lstrip('/')
        redirects = list(Redirect.objects.filter(
            domain=request.get_host(),
            # We redirect on either a path match or a '*'
            # record existing for this domain
            path__in=(path, '*')
        ))
        # A non-star redirect always takes precedence
        non_star = [r for r in redirects if r.path != '*']
        if non_star:
            return HttpResponsePermanentRedirect(non_star[0].target)
        # If there's a star redirect, build path and redirect to that
        star = [r for r in redirects if r.path == '*']
        if star:
            new_url = star[0].target + path
            if request.META['QUERY_STRING']:
                new_url += '?' + request.META['QUERY_STRING']
            return HttpResponsePermanentRedirect(new_url)
        # Default: no redirects, just get on with it:
        return get_response(request)

    return middleware 
Example 14
Project: ImitationTmall_Django   Author: Liweimin0512   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get("username", "")
            pass_word = request.POST.get("password", "")
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return HttpResponsePermanentRedirect(reverse('index'))
                else:
                    return render(request, "user_login.html", {"msg": "邮箱未激活"})
            else:
                return render(request, "user_login.html", {"msg": "用户名或密码错误"})
        else:
            return render(request, "user_login.html", {"login_form": login_form}) 
Example 15
Project: jorvik   Author: CroceRossaItaliana   File: viste.py    License: GNU General Public License v3.0 6 votes vote down vote up
def serve_protected_file(request, persona, pk):
    """
    Restituisce il file e incrementa il numero di downloads
    """
    try:
        file_obj = File.objects.get(pk=int(pk))
        file_obj.incrementa_downloads()
    except File.DoesNotExist:
        raise Http404('File not found')
    if file_obj.url_documento:
        return HttpResponsePermanentRedirect(file_obj.url_documento)
    if not file_obj.has_read_permission(request):
        if settings.DEBUG:
            raise PermissionDenied
        else:
            raise Http404('File not found')
    return server.serve(request, file_obj=file_obj.file, save_as=True) 
Example 16
Project: donation-tracker   Author: GamesDoneQuick   File: decorators.py    License: Apache License 2.0 5 votes vote down vote up
def no_querystring(view_func):
    def decorator(request, *args, **kwargs):
        if request.GET:
            return HttpResponsePermanentRedirect(request.path)
        return view_func(request, *args, **kwargs)

    return decorator 
Example 17
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def student_info(request, userid=None):
    # old student search view: new search is better in every way.
    messages.add_message(request, messages.INFO, 'The old student search has been replaced with an awesome site search, accessible from the search box at the top of every page in %s.' % (product_name(request),))
    return HttpResponsePermanentRedirect(reverse('dashboard:site_search'))


# documentation views 
Example 18
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        url = self.get_redirect_url(*args, **kwargs)
        if url:
            if self.permanent:
                return http.HttpResponsePermanentRedirect(url)
            else:
                return http.HttpResponseRedirect(url)
        else:
            logger.warning('Gone: %s', request.path,
                        extra={
                            'status_code': 410,
                            'request': request
                        })
            return http.HttpResponseGone() 
Example 19
Project: GTDWeb   Author: lanbing510   File: security.py    License: GNU General Public License v2.0 5 votes vote down vote up
def process_request(self, request):
        path = request.path.lstrip("/")
        if (self.redirect and not request.is_secure() and
                not any(pattern.search(path)
                        for pattern in self.redirect_exempt)):
            host = self.redirect_host or request.get_host()
            return HttpResponsePermanentRedirect(
                "https://%s%s" % (host, request.get_full_path())
            ) 
Example 20
Project: GTDWeb   Author: lanbing510   File: views.py    License: GNU General Public License v2.0 5 votes vote down vote up
def flatpage(request, url):
    """
    Public interface to the flat page view.

    Models: `flatpages.flatpages`
    Templates: Uses the template defined by the ``template_name`` field,
        or :template:`flatpages/default.html` if template_name is not defined.
    Context:
        flatpage
            `flatpages.flatpages` object
    """
    if not url.startswith('/'):
        url = '/' + url
    site_id = get_current_site(request).id
    try:
        f = get_object_or_404(FlatPage,
            url=url, sites=site_id)
    except Http404:
        if not url.endswith('/') and settings.APPEND_SLASH:
            url += '/'
            f = get_object_or_404(FlatPage,
                url=url, sites=site_id)
            return HttpResponsePermanentRedirect('%s/' % request.path)
        else:
            raise
    return render_flatpage(request, f) 
Example 21
Project: anytask   Author: znick   File: views.py    License: MIT License 5 votes vote down vote up
def get_or_create(request, task_id, student_id):
    # if not request.is_ajax():
    #    return HttpResponseForbidden()

    issue, created = Issue.objects.get_or_create(task_id=task_id, student_id=student_id)

    # data = {
    #     'issue_url': issue.get_absolute_url(),
    # }

    return HttpResponsePermanentRedirect(
        "/issue/" + str(issue.id))  # (json.dumps(data), content_type='application/json') 
Example 22
Project: linkedevents   Author: City-of-Helsinki   File: api.py    License: MIT License 5 votes vote down vote up
def retrieve(self, request, *args, **kwargs):
        try:
            keyword = Keyword.objects.get(pk=kwargs['pk'])
        except Keyword.DoesNotExist:
            raise Http404()
        if keyword.replaced_by:
            keyword = keyword.get_replacement()
            return HttpResponsePermanentRedirect(reverse('keyword-detail',
                                                         kwargs={'pk': keyword.pk},
                                                         request=request))
        return super().retrieve(request, *args, **kwargs) 
Example 23
Project: linkedevents   Author: City-of-Helsinki   File: api.py    License: MIT License 5 votes vote down vote up
def retrieve(self, request, *args, **kwargs):
        try:
            place = Place.objects.get(pk=kwargs['pk'])
        except Place.DoesNotExist:
            raise Http404()
        if place.deleted:
            if place.replaced_by:
                place = place.get_replacement()
                return HttpResponsePermanentRedirect(reverse('place-detail',
                                                             kwargs={'pk': place.pk},
                                                             request=request))
        return super().retrieve(request, *args, **kwargs) 
Example 24
Project: linkedevents   Author: City-of-Helsinki   File: api.py    License: MIT License 5 votes vote down vote up
def retrieve(self, request, *args, **kwargs):
        try:
            event = Event.objects.get(pk=kwargs['pk'])
        except Event.DoesNotExist:
            raise Http404()
        if event.replaced_by:
            event = event.get_replacement()
            return HttpResponsePermanentRedirect(reverse('event-detail',
                                                         kwargs={'pk': event.pk},
                                                         request=request))
        return super().retrieve(request, *args, **kwargs) 
Example 25
Project: bioforum   Author: reBiocoder   File: security.py    License: MIT License 5 votes vote down vote up
def process_request(self, request):
        path = request.path.lstrip("/")
        if (self.redirect and not request.is_secure() and
                not any(pattern.search(path)
                        for pattern in self.redirect_exempt)):
            host = self.redirect_host or request.get_host()
            return HttpResponsePermanentRedirect(
                "https://%s%s" % (host, request.get_full_path())
            ) 
Example 26
Project: Politikon   Author: KlubJagiellonski   File: middleware.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _get_redirect(new_hostname, request):
    new_location = '%s://%s%s' % (
        request.is_secure() and 'https' or 'http',
        new_hostname,
        request.get_full_path()
    )
    return HttpResponsePermanentRedirect(new_location) 
Example 27
Project: conf_site   Author: pydata   File: views.py    License: MIT License 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        pk = self.kwargs.get("pk")
        try:
            this_object = self.model.objects.get(pk=pk)
        except self.model.DoesNotExist:
            raise Http404()

        redirect_url = reverse(
            self.redirect_view_name,
            kwargs={"pk": this_object.pk, "slug": this_object.slug},
        )
        return HttpResponsePermanentRedirect(redirect_url) 
Example 28
Project: dissemin   Author: dissemin   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        if 'researcher' in kwargs:
            researcher = get_object_or_404(Researcher, pk=kwargs['researcher'])
        elif 'orcid' in kwargs:
            try:
                researcher = Researcher.objects.get(orcid=kwargs['orcid'])
            except Researcher.DoesNotExist:
                try:
                    orcid = validate_orcid(kwargs['orcid'])
                    researcher = Researcher.get_or_create_by_orcid(orcid)
                    if not researcher:
                        raise Http404(_("Invalid ORCID profile. Please make sure it includes a public name."))
                    researcher.init_from_orcid()
                except MetadataSourceException:
                    raise Http404(_('Invalid ORCID profile.'))

        if not researcher.visible:
            name = researcher.name.full
            return HttpResponsePermanentRedirect(reverse('search')+'?'+urlencode({'authors':name}))

        if kwargs.get('slug') != researcher.slug:
            view_args = {'researcher': researcher.id, 'slug': researcher.slug}
            url = reverse('researcher', kwargs=view_args)
            self.url = self.url_with_query_string(url=url)
            return HttpResponsePermanentRedirect(self.url)

        self.queryset = self.queryset.filter(researchers=researcher.id)
        self.researcher = researcher
        return super(ResearcherView, self).get(request, *args, **kwargs) 
Example 29
Project: dissemin   Author: dissemin   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def redirect_by_doi(request, doi):
    """
    This view is inherited from doai.io, migrated to this code base
    to preserve the existing behaviour. We could instead
    redirect to unpaywall, but that would not include ResearchGate urls.
    """
    doi = unquote(doi)
    doi = to_doi(doi)
    if not doi:
        raise Http404(_("Invalid DOI."))
    paper = Paper.get_by_doi(doi)
    if paper and paper.pdf_url:
        return HttpResponsePermanentRedirect(paper.pdf_url)
    return HttpResponsePermanentRedirect(doi_to_url(doi)) 
Example 30
Project: mangaki   Author: mangaki   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        if self.object.category.slug != self.kwargs.get('category'):
            return HttpResponsePermanentRedirect(self.object.get_absolute_url())

        context = self.get_context_data(object=self.object)
        return self.render_to_response(context)