登录后重定向到另一个页面

时间:2016-10-22 17:44:28

标签: django redirect login

我正在使用django 1.10嵌入式身份验证。我想登录重定向到另一个页面并传递变量。 我提出了我的观点,但我一直有错误404.我读到了" login-redirect-url"默认为帐户/个人资料。我在我的模板中创建了一个文件夹。这是正确的方法吗?我将它存储在Django / myapp / myapp / templates / accounts / profile / home.html

错误:"当前网址(accounts / profile / home.html)与这些网址中的任何一个都不匹配。"

views.py

    def home(request):
        username = None
        if request.user.is_authenticated:
            username = request.user.username
            return redirect('accounts/profile/home.html',{'username': username})
        else:
            return redirect('/accounts/profile')


 myapp/ulrs.py

    url(r'^accounts/profile/$', views.home, name='home')

我更改了settings.py

LOGIN_REDIRECT_URL = '/'

欢迎提出任何建议。如果我做错了,请提供一个例子。

感谢。

4 个答案:

答案 0 :(得分:2)

Dariusz Niespodziany的答案是有效的,但更好的是改变你的模板。您的视图将如下所示:

 def home(request):
      return redirect('/accounts/profile')

然后在您的模板(home.html)中,您可以执行以下操作:

{% if request.user.is_authenticated %}
    <h1> Hi {{request.user.username}} </h1>
{% else %}
    <h1> Hi stranger </h1>
{% endif %}

答案 1 :(得分:1)

你不需要在渲染请求中传递用户名。 这是一个例子:

view.py

def profile(request):
    username = None
    if request.user.is_staff:
       return redirect('/admin/')
    else:
       return render(request, 'accounts/profile/home.html',{})

home.html(将其存储为myapp / myapp / templates / myapp / home.html)

Hello user:{{request.user.username}}

答案 2 :(得分:0)

您可能希望使用accounts/profile/home.html的上下文呈现{'username': username}模板。

return render(request, 'accounts/profile/home.html', context={'username': username})

答案 3 :(得分:0)

试试这个: -

def user_login(request):
    context = RequestContext(request)
    if request.method == 'POST':
        username = request.POST['login']
        password = request.POST['password']
        user = authenticate (email=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user, backend='django.contrib.auth.backends.ModelBackend')
                redirect_to = settings.LOGIN_REDIRECT_URL
                return redirect(redirect_to,{your varible })
相关问题