Djangoでuser_passes_testデコレータでリダイレクト先を動的に変えたい
もしuser_passes_testデコレータでリダイレクト先を動的に変えたい場合、login_urlパラメータに関数を渡す方法があります。この関数はユーザーが条件を満たさない場合にリダイレクト先のURLを返します。
以下は例です:
python
from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import render, redirect
def has_permission(user):
# 例: userがstaffまたはsuperuserの場合にTrueを返す
return user.is_staff or user.is_superuser
def redirect_to_custom_url(request):
# リダイレクト先の条件を適切に設定する
if some_condition:
return '/custom-url/'
else:
return '/default-url/'
@user_passes_test(has_permission, login_url=redirect_to_custom_url)
def your_protected_view(request):
# ビューの本来の処理をここに書く
return render(request, 'protected_view.html')
上記の例では、redirect_to_custom_url関数が条件に基づいて適切なリダイレクト先のURLを返します。この関数を適切に変更して、ユーザーが条件を満たさない場合のリダイレクト先を制御できます。

ディスカッション
コメント一覧
まだ、コメントがありません