Django入門(1)

Django入門

項目建立和APP建立

  • 準備環境
python3 
virtualenv
pip3
pip3 install django==1.1
  • 項目建立,APP建立
django-admin startproject ops
cd ops
python3 manage.py startapp darshboard
cd darshboard #進入項目路徑
touch urls.py #建立路由文件
  • 項目結構以下:
ops/
|-- darshboard
| |-- admin.py
| |-- apps.py
| |-- __init__.py
| |-- migrations
| |-- models.py
| |-- tests.py
| |-- urls.py
| `-- views.py
|-- db.sqlite3
|-- manage.py
`-- ops
    |-- __init__.py
    |-- settings.py
    |-- urls.py
    `-- wsgi.py
  • 項目註冊
# vim ops/ops/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'darshboard.apps.DarshboardConfig' #在此處註冊darshboard項目
]
  • 路由註冊
# vim ops/ops/urls.py

from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^darshboard/',include("darshboard.urls")), #註冊app的urls
]
此時,一個完整的流程就行了

hello world

修改darshboard的路由

# vim ops/darshboard/urls.py

from django.conf.urls import url
from .views import index

urlpatterns = [
    url(r'^hello/', index,name='index'),
]

寫一個視圖函數

函數視圖的定義:
a. 就是一個普通函數
b. 接收一個HttpRequest實例做爲第一個參數
c. 而後返回一個HttpResponse的實例
# vim ops/darshboard/views.py

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return HttpResponse('hello world')

項目啓動&測試

  • 啓動項目
python manage.py runserver 0:8080
  • 訪問:

打開本地瀏覽器輸入:html

http://211.159.156.251:8080/darshboard/hello/

便可訪問!python

HttpRequest對象

  • 由Django建立

屬性以下:linux

HttpRequest.scheme
HttpRequest.body
HttpRequest.path
HttpRequest.method
HttpRequest.encoding
HttpRequest.GET
HttpRequest.POST
HttpRequest.META

方法以下:web

HttpRequest.get_host()
HttpRequest.get_port()
HttpRequest.get_full_path()
HttpRequest.is_secure()
HttpRequest.is_ajax()
  • 傳遞一個字符串做爲頁面的內容到HttpResponse構造函數
from django.http import HttpResponse
response = HttpResponse("here is the web page")
response = HttpResponse("Text only .please,content_type="text/plain")
  • 參考的views以下
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
import json
def index(request):
    data = {
        'name':'wanghui',
        'age':20
    }
    data_1 = ["devops","python"]
    #return HttpResponse(json.dumps(data),content_type="application/json")   #返回的content-typet
    #return HttpResponse(json.dumps(data_1),content_type="application/json")
    return JsonResponse(data_1,safe=False)
    # return HttpResponse("Hello World!!",status=599)

模板

爲了讓數據更加美觀。ajax

POST和GET請求

  • GET請求與傳參
- method
- GET
  • POST提交數據

QueryDict對象

方法練習sql

#  python manage.py shell
>>> from django.http import QueryDict
>>> data = QueryDict('a=12&a=123&b=233')
>>> data.urlencode()
'a=12&a=123&b=233'

數據庫同步

  • 官方給出的數據庫鏈接設置
https://docs.djangoproject.com/en/1.11/ref/settings/#databases
  • 數據庫同步相關命令
python manage.py showmigrations
python manage.py sqlmigrate sessions 0001
python manage.py dbshell   # 進入shell模式

建立用戶

  • django-shell建立用戶
# 方式一:
(venv3) [wanghui@www ops]$ python manage.py shell
Python 3.6.1 (default, Jun 22 2018, 18:25:52) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> User.objects.create_user('rock','12272@qq.com','123456')   #建立普通用戶
>>> u = User.objects.get(username='rock')     #查找用戶
>>> u.set_password('654321')       #修改密碼
>>> u.save()                                   #保存
-------------------------------------------------------------------------------------------------------------
# 方式二:
(venv3) [wanghui@www ops]$ python manage.py createsupperuser

用戶登陸小練習

重點在於對函數視圖的練習shell

  • darshboard/views.py
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse,QueryDict
from django.template import loader,Context,Template
from django.contrib.auth.models import User
from django.contrib.auth import login,authenticate

def user_login(request):
    # print(request.GET)
    # 獲取提交過來的用戶名&密碼
    if request.method == "GET":     #get請求的話,就直接返回頁面
        return render(request, 'user_login.html')
    elif request.method == "POST":  #post就要獲取用戶名和密碼
        username = request.POST.get("username")
        password = request.POST.get("password")
    # 根據用戶名取出這個記錄是否存在
        user_obj = authenticate(username=username,password=password)
        if user_obj:
            login(request,user_obj)
            print("登錄成功!")
        else:
            print("登錄失敗!")
    elif request.method == 'DELETE':      # 經過delete方法獲取請求體
        data = QueryDict(request.body)    # 獲取delete的請求體
        print(data)
    return HttpResponse("")
  • darshboard/urls.py #指定路由
from django.conf.urls import url,include
from django.contrib import admin
from .views import index,index_template,index_methods,user_login
urlpatterns = [
    url(r'^user_login',user_login)
]
  • darshboard/user_login.html
<ul>
    <form method="DELETE" action="#">   
        <li>用戶名:<input type="text" name="username"></li>
        <li>密碼:<input type="text" name="password"></li>
        <li><input type="submit"></li>
    </form>
</ul>

關於delete方法的請求方式數據庫

在linux本地機器上執行:
curl -XDELETE http://127.0.0.1:8080/darshboard/user_login/ -d username=rock -d password=654321
相關文章
相關標籤/搜索