'How to redirect users to a mobile app in Django view?

I have a Django web application and I'm trying to redirect users to my mobile app in one of the views.

def magic_link(request, token):
    return redirect(f"{settings.FRONTEND_URL}/magic_link/{token}")

This redirect link is like: appname://magic_link/token. However, I'm getting the following error.

DisallowedRedirect at /magic_link/{token}/
Unsafe redirect to URL with protocol 'appname'

How can I fix this issue and redirect users to the mobile app in Django view?



Solution 1:[1]

You should create your own HttpResponsePermanentRedirect which inherits from HttpResponsePermanentRedirect by django. In your own class, you add your app scheme to the allow_schemes (something relevant, i can't remember so well) to let django know your app scheme is valid.

Example:

class HttpResponsePermanentRedirect(HttpResponsePermanentRedirect by django):
   allow_schemes=['your_app_scheme',...]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Huy Le