django登录功能(简单在POST请求)

 

第一  先在templates中创立index.html

!DOCTYPE html>

<head>
    <meta charset="UTF-8">
    <title>Django Page</title>
</head>
<body>
    <h1>登录页面</h1>
    <form method="post" action="/login_submit/">
        <input name="username" type="text" placeholder="username"><br>
        <input name="password" type="password" placeholder="password"><br>
        {{ error }}<br>
        <button id="btn" type="submit">登录</button>
        {% csrf_token %}

    </form>
</body>
</html>

第二步  关联相关路径 这里路径为http://127.0.0.1:8000/login_submit/

在url.py中

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/$', views.index),
    url(r'^login_submit/$', views.login_submit),

第三步 定义动作(POST处理登录请求)

在view.py

 1 def index(request):
 2     return render(request, 'index.html')
 3 def login_submit(request):
 4     if request.method == 'POST':
 5         username = request.POST.get('username', '')
 6         password =request.POST.get('password', '')
 7         if username == 'admin' and password == 'admin123':
 8             return HttpResponse('login success!')
 9         else:
10             return render(request,'index.html',{'error':'username or password error'})

 

posted @ 2017-05-09 21:37  金牛小子  阅读(847)  评论(0编辑  收藏  举报