Semih
Semih

Reputation: 165

Django Redirect to Second URL

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)                

Upvotes: 0

Views: 657

Answers (2)

nigel222
nigel222

Reputation: 8192

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

Upvotes: 1

vinkomlacic
vinkomlacic

Reputation: 1879

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)

Upvotes: 1

Related Questions