2009-10-22 19 views
7

私はユーザ名(例えばhttp://domain/username/)を含むURLにユーザをリダイレクトしようとしています。私は私のユーザー管理のためにdjango.contrib.authを使用していますので、私は設定でLOGIN_REDIRECT_URLを使用して試してみた:django LOGIN_REDIRECT_URL(動的値を使用)

LOGIN_REDIRECT_URL = '/%s/' % request.user.username # <--- fail.. 

それだけで固定された文字列ではなく、後に決定されます何かを受け入れているようですユーザーはログインしていますが、これをどうすれば達成できますか?

答えて

17

解決策は、 '/ userpage /'のような静的ルートにリダイレクトし、それを最終的な動的ページにリダイレクトすることです。

しかし、本当の解決策は、あなたが本当にしたいことをする新しい視点を作ることだと思います。ビューの書き換えについての詳細は

from django.contrib.auth import authenticate, login 
from django.http import HttpResponseRedirect 

def my_view(request): 
    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) 
      HttpResponseRedirect('/%s/'%username) 
     else: 
      # Return a 'disabled account' error message 
    else: 
     # Return an 'invalid login' error message. 

http://docs.djangoproject.com/en/dev/topics/auth/#authentication-in-web-requests

。これは、ドキュメントがこの種のものをオーバーライドする方法です。

+2

私はTを好む彼は静的/ユーザーページ/からのリダイレクトの最初の提案です。そうすれば、 'django.contrib.auth.views'からのログインビューを引き続き使用することができます。 – Alasdair

+0

私はURLを簡素化し、リダイレクトを最小限に抑えようとしているので、あなたのソリューションは行く方法のように思えます。ありがとう! – sa125

+0

私の正確な質問を解決するための単純で華麗な答え。私はこれを考えないと恥じている。あなたのインターネットポイントを楽しむ。 – Esteban

0

認証ビューを独自のカスタム表示で囲み、認証が成功した場合はどこにでもリダイレクトします。

from django.http import HttpResponseRedirect 
from django.contrib import auth 
from django.core.urlresolvers import reverse 

def login(request): 
    template_response = auth.views.login(request) 

    if isinstance(template_response, HttpResponseRedirect) and template_response.url == '/accounts/profile/': 
     return HttpResponseRedirect(reverse('user', args=(request.user.username,))) 


    return template_response 

別の方法としては、どこログイン後にリダイレクトするように指示するクエリのparam nextを使用することです。クラスベースdjango.contrib.auth.views.LoginView

<a href="{% url 'login' %}?next={{ request.path }}">sign in</a> 
0

、あなたは今、単にget_success_urlを上書きすることができます。

urls.py:

url(r'^login$', MyLoginView.as_view(), name='login'), 
url(r'^users/(?P<username>[a-zA-Z0-9]+)$', MyAccountView.as_view(), name='my_account'), 

views.py

class MyLoginView(LoginView): 

    def get_success_url(self): 
     return reverse('my_account', args=[self.request.user.username]) 
関連する問題