Home > OS >  Django Redirect to Second URL
Django Redirect to Second URL

Time:03-09

I'm trying to redirect to an custom url as it's coded in the below. However there might be a broken url. Therefore, I like to redirect to an second url in case of error.

Is there any way to redirect to an second url in case of an error?

        page = self.request.POST.get('ex_page')
        return redirect(page)                

CodePudding user response:

You can use this to check if the URL resolves and then redirect to a secondary page.

page = self.request.POST.get('ex_page')

try:
  resolve(page)
  return redirect(page)
except Resolver404:
  return redirect(secondary_url)

CodePudding user response:

If "broken URL" menas that the lookup of page is impossible because it doesn't exist in the relevant urls.py, then:

from django.urls.exceptions import NoReverseMatch
...

try:
    destination = redirect(page)
except NoReverseMatch:
    destination = redirect('homepage')
return destination
  • Related