django在URL中没有next=时返回index

4szc88ey  于 2023-06-07  发布在  Go
关注(0)|答案(1)|浏览(151)

我做了一个应该重定向到上一页的登录(用/?next=/)似乎可以工作,但当没有next=时,它会停留在登录页面上,而不会重定向到索引。我在哪里犯了错误?

def login_user(request):
    login_form = LoginForm(request.POST or None)
    if request.POST and login_form.is_valid():
        user = login_form.login(request)
        if user:
            login(request, user)
            return HttpResponseRedirect(request.POST.get('next', reverse('index')))
            #return HttpResponseRedirect(reverse('index'))

    return render(request, 'login.html', {'login_form': login_form, 'next': request.GET.get('next', '') })

我的urls.py(在我的用户应用程序中)

from django.conf.urls import patterns, url
from users import views
urlpatterns = patterns('',
    #Authentication urls
    url(r'^login/$', views.login_user, name='login_user'),
    url(r'^logout/$', views.logout, name='logout'),
    url(r'^register/$', views.register_user, name='register_user'),
)

我的urls.py(在我的角色应用程序中)

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
)

我的模板:(是的,这不是一个漂亮的,有点旧的作品)

{% block content %}
<div>
    <form action="{% url 'login_user' %}" method="post" class="login">{% csrf_token %}
        <table>
        {% if login_form.non_field_errors %}
            <tr>
                <td><i style="font-size: small;">{{ login_form.non_field_errors|striptags }}</i></td>
            </tr>
        {% endif %}
        {% for field in login_form %}
            <tr>
                <td>{{ field }}</td>
            </tr>
        {% endfor %}
            <tr>
                <td style="text-align:right;" >
                    <a href="{% url 'register_user' %}">register</a>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <input type="submit" value="Login" />
                </td>
            </tr>
        </table>

        <input type="hidden" name="next" value="{{ next }}">
    </form>
</div>
{% endblock %}
u5rb5r59

u5rb5r591#

问题是,如果在GET参数中没有指定next参数,它将是一个空字符串,但它仍然会被定义。request.POST.get('next')永远不会失败,只是返回一个空字符串。您可以执行以下操作:

def login_user(request):
    login_form = LoginForm(request.POST or None)
    if request.POST and login_form.is_valid():
        user = login_form.login(request)
        if user:
            login(request, user)
            return HttpResponseRedirect(request.POST.get('next') or reverse('index'))
            #return HttpResponseRedirect(reverse('index'))

    return render(request, 'login.html', {'login_form': login_form, 'next': request.GET.get('next', '') })

这将返回next的值,如果该值为空,则返回reverse('index')

相关问题