0

网址.py

from django.conf.urls.defaults import patterns, include, url
import myproject.views

urlpatterns = patterns('', (r'^$', myproject.views.home), (r'^login$', apolla.views.login))

视图.py

import django.http
import django.template
import django.shortcuts

def home(request):
    return django.http.HttpResponse("Welcome home!")

def login(request):
    un = request.POST.get('username')
    pa = request.POST.get('password')
    di = {'unam': un, 'pass': pa}   
    if un and pa:
        di['act'] = "/"
    else:
        di['act'] = "/login"
    return django.shortcuts.render_to_response('login.html', di, 
      context_instance=django.template.RequestContext(request))    
    # Why does this code not send me immediately to "/" with 
    # username and password filled in?

登录.html

<html>
<head>
</head>
<body>
<form name="input" method="post" action="{{ act }}">
{% csrf_token %}
Username: 
<input type="text" name="username"><br>
Password: 
<input type="password" name="password"><br> 
<input id="su" type="submit" value="Submit"><br>
</form>
</body>
</html>

当我运行开发服务器并进入localhost:8000/login并填写 ausernamepassword按下提交按钮时,我没有localhost:8000/像我预期的那样从我的登录功能发送到views.py,我只是返回到localhost:8000/login. 但是当我填写任何字段并第二次提交时,我会被定向到localhost:8000.

我还使用print unand来查看帖子是否从and字段print pa中捕获了数据,并且它从第一次开始就这样做了,那么为什么我没有从第一次提交时被定向到并同时填写了and字段呢?usernamepasswordlocalhost:8000/loginusernamepassword

4

1 回答 1

3

您可以通过以下方式将重定向添加到您的视图:

from django.http import HttpResponseRedirect

def foo_view(request):
    # ...
    return HttpResponseRedirect('/')
于 2012-10-02T21:08:11.353 回答