39

我有一个登录页面,除了重定向到引用页面之外,它工作正常。用户在应用程序中收到一封带有直接链接的电子邮件,他们(在此示例中)尚未登录并被重定向到登录页面。成功登录后,用户被重定向到硬编码路径。请参见下面的示例。

电子邮件中的网址:http://localhost:8000/issueapp/1628/view/22

登录页面网址:http://localhost:8000/login?next=/issueapp/1628/view/22

登录视图(带有硬编码重定向):

def login_user(request):    
    state = "Please log in below..."
    username = password = ''

    if request.POST:
        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)
                state = "You're successfully logged in!"
                return HttpResponseRedirect('/issueapp/1628/')
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."

    return render_to_response(
        'account_login.html',
        {
        'state':state,
        'username': username
        },
        context_instance=RequestContext(request)
    )

登录视图(带有“下一个”重定向):

def login_user(request):    
    state = "Please log in below..."
    username = password = ''

    if request.POST:
        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)
                state = "You're successfully logged in!"
                return HttpResponseRedirect(request.GET['next'])
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."

    return render_to_response(
        'account_login.html',
        {
        'state':state,
        'username': username
        },
        context_instance=RequestContext(request)
    )

上面的视图导致异常"Key 'next' not found in <QueryDict: {}>"表单似乎没有发布“下一个”变量,即使它在 url 和表单中。我到处搜索和查看,无法弄清楚为什么它不起作用。有任何想法吗?

附加参考:

登录模板:

{% block content %}

    {{ state }}
    <form action="/login/" method="post" >
                {% csrf_token %}
        {% if next %}
        <input type="hidden" name="next" value="{{ next }}" />
        {% endif %}
        username:
        <input type="text" name="username" value="{{ username }}" /><br />
        password:
        <input type="password" name="password" value="" /><br />

        <input type="submit" value="Log In"/>

        {% debug %}
    </form>
{% endblock %}

编辑:下面是现在为我工作的代码(感谢 Paulo Bu 的帮助)!**

登录视图:

def login_user(request):

    state = "Please log in below..."
    username = password = ''

    next = ""

    if request.GET:  
        next = request.GET['next']

    if request.POST:
        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)
                state = "You're successfully logged in!"
                if next == "":
                    return HttpResponseRedirect('/issueapp/')
                else:
                    return HttpResponseRedirect(next)
            else:
                state = "Your account is not active, please contact the site admin."
        else:
            state = "Your username and/or password were incorrect."

    return render_to_response(
        'account_login.html',
        {
        'state':state,
        'username': username,
        'next':next,
        },
        context_instance=RequestContext(request)
    )

登录模板:

{{ state }}

{% if next %}
<form action="/login/?next={{next}}" method="post" >
{%else%}
<form action="/login/" method="post" >
{% endif %}

            {% csrf_token %}

    username:
    <input type="text" name="username" value="{{ username }}" /><br />
    password:
    <input type="password" name="password" value="" /><br />

    <input type="submit" value="Log In"/>

    {% debug %}
</form>
4

5 回答 5

43

您的代码很好,唯一的问题是在表单中您将next属性作为帖子传递,因为方法是post. 在视图中,您尝试获取字典中明显不存在的next参数。get

您必须action像这样声明 html 表单才能使您的视图正常工作。

{% if next %}
<form action="/login/?next={{next}}" method="post" >
{%else%}
<form action="/login/" method="post" >
{% endif %}
        {% csrf_token %}
        username:
        <input type="text" name="username" value="{{ username }}" /><br />
        password:
        <input type="password" name="password" value="" /><br />

        <input type="submit" value="Log In"/>

        {% debug %}
    </form>

在那里,如果有一个next变量,那么你在urlfor 检索它作为一个 get 参数。如果不是,则表单不包含它。

这是最好的方法,但您也可以通过nextPOST字典中请求来解决此问题,如下所示:

return HttpResponseRedirect(request.POST.get('next'))

请注意,这仅在模板account_login 具有名为 的变量时才有效next。您应该在视图中生成它并在渲染时将其传递给模板。

通常,在模板中你会做这样的事情:

# this would be hardcoded
next = '/issueapp/1628/view/22'
# you may add some logic to generate it as you need.

然后你做:

return render_to_response(
    'account_login.html',
    {
    'state':state,
    'username': username,
    'next':next
    },
    context_instance=RequestContext(request)
)

希望这可以帮助!

于 2013-05-25T15:00:53.157 回答
6

简而言之

我会在你的视图函数中定义next_page = request.GET['next'],然后重定向到它,return HttpResponseRedirect(next_page)这样你就不需要更改模板;刚刚设置@login_required,你很好。

例如:

用户 A 在未登录的情况下尝试访问https://www.domain.tld/account/。Django 重定向他,因为@login_required设置为LOGIN_URL您的 settings.py 中定义的。如果用户 A 成功登录,该方法UserLogin现在会尝试使用GET该参数并重定向到该参数。next

设置.py

LOGIN_URL = '/login/'

网址.py

url(r'^account/', account, name='account'),
url(r'^login/$', UserLogin, name='login'),

视图.py

@login_required
def account(request):
    return HttpResponseRedirect("https://www.domain.tld/example-redirect/")

def UserLogin(request):
    next_page = request.GET['next']
    if request.user.is_authenticated():
        return HttpResponseRedirect(next_page)
    else:
        if request.method == 'POST':
            if form.is_valid():
                username = form.cleaned_data['username']
                password = form.cleaned_data['password']
                user = authenticate(email=username, password=password)
                if user is not None and user.is_active:
                    login(request, user)
                    return HttpResponseRedirect(next_page)
                else:
                    error_msg = 'There was an error!'
                    return render(request, "login", {'form': form, 'error_msg': error_msg})
            else:
                error_msg = "There was an error!"
                return render(request, "login", {'form':form, 'error_msg':error_msg})
        else:
            form = UserLoginForm()
            return render(request, "login", {'form': form})
于 2016-03-01T16:56:08.280 回答
4

就放

<form action="" method="post" >

空动作' what ever current complete url is'

于 2015-11-19T11:42:57.627 回答
3

如果你想更通用,你可以做这样的事情,当表单发布时传递任何 GET 参数:

<form action="/path-to-whatever/{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}" method="post">
于 2014-09-05T15:40:34.710 回答
1

与其next在您的视图中分配并将其传递给模板,不如?next={{request.path}}在您的模板中使用它不是更干净。(记得启用django.core.context_processors.requestin settings.py,通常在 django 1.6 中默认启用)

这是链接讲述相同的内容

https://docs.djangoproject.com/en/1.6/topics/auth/default/#the-raw-way

<form action="/login/?next={{request.path}}" method="post" >

是所需的代码。

笔记:

request.path您也可以使用from获取当前 url view

感谢缓冲区。在我自己的代码中尝试之后,我刚刚复制并粘贴了您的评论。

于 2014-10-29T05:32:46.497 回答