0

我已经检查了以下关于 HttpResponse、HttpResponseRedirect 和 render_to_response 之间区别的 stackoverflow 问题,以及浏览了官方 django 文档,但我真的不确定如何最好地获得我想要创建的功能.

现在我有一个带有登录功能的index.html(如下面的views.py所示),render_to_response它把我带到了portal/index.html。但是,正如urls.py(见下文)所指示的,我的浏览器 url 栏中的 url 是http://127.0.0.1:8000/login/. 这意味着刷新页面会强制表单再次运行。

我如何让该 url(一旦登录)看起来像http://127.0.0.1:8000/,或者,如果这不可行,http://127.0.0.1:8000/portal/- 这是因为我认为每次登录后重新加载页面时,它都会强制浏览器打开提示符是笨拙的确定要再次发送表格吗?.

非常感谢您帮助 Django 新手!

视图.py

@cache_page(60 * 15)
def login_user(request):
    #inactive_image_url = ""
    #invalid_credentials_url = ""
    context_instance=RequestContext(request)
    if request.POST:
        username = request.POST.get('username')
        password = request.POST.get('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 render_to_response('ucproject/portal/index.html', 
                        {'state':state, 'username':username}, context_instance=RequestContext(request))
            else:
                #state_img = inactive_image_url
                state = "Your account is not active, please contact UC admin."
        else:
            #state_img = invalid_credentials_url
            state = "Your username and/or password were incorrect."
    return render_to_response('ucproject/index.html', 
            {'state': state,
             #'state_img': state_img,
             'username': username
            }, context_instance=RequestContext(request))

def portal(request):
    username = 'username'
    return render_to_response('ucproject/portal/index.html', 
            {'state': state,'username': username}, context_instance=RequestContext(request))

网址.py

# Login / logout.
url(r'^registration/$', 'portal.views.registration'),
url(r'^login/$', 'portal.views.login_user'),
url(r'^portal/$', 'portal.views.portal'),
url(r'^portal/index.html$', 'portal.views.portal'),
4

1 回答 1

3

将此处的 HttpResponse 替换为重定向:

if user.is_active:
    login(request, user)            
    state = "You're successfully logged in!"
    return render_to_response('ucproject/portal/index.html', 
           {'state':state, 'username':username}, context_instance=RequestContext(request))

相反,您想在 urls.py 中使用名称来消除歧义:

urls.py
url(r'^portal/$', 'portal.views.portal', name='home'),
url(r'^portal/index.html$', 'portal.views.portal', name='home_index'),

然后在你的视图中使用这样的东西:

if user.is_active:
    login(request, user)
    return redirect('home')

redirect是一个快捷函数,但您也可以创建并返回一个HttpResponseRedirect对象。通常这样做是没有意义的。

于 2013-08-09T21:31:19.427 回答