短いバージョンでの私の問題:
login_required
ビューの 1 つにデコレータを追加しました。このビューを実行するブラウザに URL を入力すると、ユーザーが認証されていない場合、ブラウザはログイン フォームを含む URL に正しくリダイレクトされます。ただし、ブラウザーが前のページにリダイレクトされることはなく、なぜこれが機能しないのかわかりません。私は何百ものことを試しました。
長いバージョンでの私の問題:
単一のアプリを含む Django プロジェクトがあります。それを と呼びましょうmy_app
。私のプロジェクトのすべてのテンプレートは にありますtemplates/my_app/
。main.html
ログインフォームを含むいくつかのフォームを含むというテンプレートがあります。という追加のPOST
パラメーターform-type
を使用して、どのフォームが送信されたかを確認します。コードは次のようになります。
def process_main_page_forms(request):
if request.method == 'POST':
if request.POST['form-type'] == u'login-form':
template_context = _log_user_in(request)
elif request.POST['form-type'] == u'registration-form':
template_context = _register_user(request)
elif request.POST['form-type'] == u'password-recovery-form':
template_context = _recover_password(request)
else:
template_context = {
'auth_form': AuthenticationForm(),
'registration_form': RegistrationForm(),
'password_recovery_form': EmailBaseForm()
}
return render(request, 'my_app/main.html', template_context)
関数_log_user_in()
は次のようになります。
def _log_user_in(request):
message = ''
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
else:
message = 'Your account has been disabled. ' \
'Please contact the administrator.'
else:
message = 'Your username and password didn\'t match. Please try again.'
template_context = {
'auth_form': AuthenticationForm(),
'registration_form': RegistrationForm(),
'password_recovery_form': EmailBaseForm(),
'message': message,
}
return template_context
また、必要な<input>
要素をテンプレートに含めます。たとえば、ログイン フォームの場合は次のようになります。
<input type="hidden" name="form-type" value="login-form" />
<input type="hidden" name="next" value="{{ next }}" />
このビューの URL パターンは次のとおりです。
url(r'^$', process_main_page_forms, name='main-page')
2 番目のビューは、認証済みユーザーのメール アドレスとパスワードを変更するための 2 つのフォームをレンダリングします。次のようになります。
@login_required(login_url='/')
def change_user_credentials(request):
if request.method == 'POST':
if request.POST['form-type'] == u'change-email-form':
template_context = _change_email_address(request)
elif request.POST['form-type'] == u'change-password-form':
template_context = _change_password(request)
else:
template_context = {'change_email_form': ChangeEmailForm()}
return render(request, 'my_app/user.html', template_context)
この 2 番目のビューの URL パターンは次のとおりです。
url(r'^account/$', change_user_credentials, name='user-page')
認証されていないときにアクセス/account/
すると、ログイン フォームを含むメイン ページに正常にリダイレクトされます。結果の URL にはhttp://127.0.0.1:8000/?next=/account/
、必要なnext
パラメーターが含まれています。ただし、アカウントにログインすると、まだメイン ページにいます。next
ログインフォームで必要なパラメーターを指定したにもかかわらず、ユーザーページにリダイレクトされることはありません。このパラメーターは常に空のようですが、理由はわかりません。私のコードには、他のリダイレクト呼び出しもありません。
この問題を解決するのを手伝ってくれませんか? 事前にどうもありがとうございました。