質問

ユーザーをユーザー名を含むURLにリダイレクトしようとしています( http:// domain / username / )、およびこれを行う方法を理解しようとしています。ユーザー管理にdjango.contrib.authを使用しているため、設定でLOGIN_REDIRECT_URLを使用しようとしました:

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

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

役に立ちましたか?

解決

解決策は、「/ 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

ビューの書き換えの詳細については。これは、ドキュメントがこの種のことをオーバーライドする方法です。

他のヒント

独自のカスタムビューで認証ビューをラップし、認証が成功した場合は必要な場所にリダイレクトします。

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

別の方法は、クエリパラメータ next を使用して、ログイン後にリダイレクトする場所を示すことです。

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

クラスベースの django.contrib.auth.views.LoginView を使用すると、単に get_success_url をオーバーライドできます:

urls.py:

url(r'^login

views.py

class MyLoginView(LoginView):

    def get_success_url(self):
        return reverse('my_account', args=[self.request.user.username])
, MyLoginView.as_view(), name='login'), url(r'^users/(?P<username>[a-zA-Z0-9]+)

views.py

<*>, MyAccountView.as_view(), name='my_account'),

views.py

<*>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top