django 3.post接口開發


如果有了一個項目,還想創建一個項目,那么就是進入項目的路徑下,運行命令,比如:

cd /Users/newcomer/PycharmProjects/djangoProject

python3 manage.py startapp api(如果是python版本是2.7的話,直接用python就好,因為我的是python3的)

刷新項目之后,就有一個api的項目產生

 接下來寫一個登陸的界面,在templates里面創建一個login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<form action="/login/" method="POST">
    <h1>用戶名:<input name="username"></h1>
    <h1>密碼:<input name="password"></h1>
    <input type="submit" value="登陸">
</form>

</body>
</html>

在views.py里面寫入方法,urls.py里面寫入映射。

#views.py
from django.http.response import HttpResponse
from django.shortcuts import render,render_to_response

# Create your views here.

def Login1(request):
    return HttpResponse('這是一個頁面')

def Index(request):
    return HttpResponse('Hello world!')

def Login(request):
    if request.method == 'POST':
        username = request.POST.get("username")
        return HttpResponse(username)
    else:
        return render_to_response('login.html')

urls.py

from django.urls import path
from appName.views import *
urlpatterns = [
    path('', Index),
    path('login/',Login)
]

直接啟動,然后瀏覽器輸入網址,如果python版本是2.7的,需要在settings.py里面的 'DIRS': [os.path.join(BASE_DIR, 'templates')] 補充完整

輸入用戶名密碼點擊登陸之后顯示禁止登陸:

那么需要去settings.py設置一下:注釋掉這一行認證的代碼

再次提交,就會返回要的結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM