1. 程式人生 > >Python之路58-Django安裝配置及一些基礎知識點

Python之路58-Django安裝配置及一些基礎知識點

python

目錄

一、安裝Django

二、創建工程

三、創建app

四、靜態文件

五、模板路徑

六、設置settings

七、定義路由

八、定義視圖

九、渲染模板

十、運行


Django是一款Python的web框架


一、安裝Django

pip3 install django

安裝完成後C:\Python35\Script下面會生成django-admin


二、創建工程

django-admin startproject 工程名

如django-admin startproject mysite

mysite

- mysite

__init__.py

settings.py # 配置文件

urls.py # url對應關系

wsgi.py # 遵循wsgi規範,實際生產環境uwsgi+nginx

manage.py # 管理django程序


三、創建app

python manage.py startapp cmdb

python manage.py startapp xxoo...

app目錄

- migrations 數據修改表結構記錄

admin.py django為我們提供的後臺管理

apps.py 配置當前app

models.py ORM,寫指定的類,通過命令可以創建數據結構

tests.py 單元測試

views.py 業務邏輯代碼


四、靜態文件

配置靜態文件目錄

STATICFILES_DIRS = (
    os.path.join(BASE_DIR,"static"),
)

五、模板路徑

配置模板的路徑

TEMPLATES = [
    {
        ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
        ‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)]
        ,
        ‘APP_DIRS‘: True,
        ‘OPTIONS‘: {
            ‘context_processors‘: [
                ‘django.template.context_processors.debug‘,
                ‘django.template.context_processors.request‘,
                ‘django.contrib.auth.context_processors.auth‘,
                ‘django.contrib.messages.context_processors.messages‘,
            ],
        },
    },
]


六、設置settings

註釋掉

‘django.middleware.csrf.CsrfViewMiddleware‘


七、定義路由

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

from cmdb import views

urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    # url(r‘^index/‘, views.index),
    url(r‘^login‘, views.login),
    url(r‘^home‘, views.home),
]

八、定義視圖

from django.shortcuts import render

# Create your views here.
from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect


def index(request):
    return HttpResponse("<h1>CMDB</h1>")


def login(request):
    # request包含用戶提交的所有信息
    # 獲取用戶提交方法
    # print(request.method)

    error_msg = ""

    if request.method == "POST":
        # 獲取用戶通過POST提交的數據
        username = request.POST.get("username", None)
        password = request.POST.get("password", None)
        if username == "root" and password == "123":
            # 去跳轉到百度
            # return redirect("http://www.baidu.com")
            # 跳轉到home
            return redirect("/home")
        else:
            # 用戶名密碼不匹配
            error_msg = "用戶名或密碼錯誤"
    return render(request, "login.html", {"error_msg": error_msg})

USER_LIST = [
    {"username": "alex", "email": "sdasda", "gender": "男"},
    {"username": "eric", "email": "sdasda", "gender": "男"},
    {"username": "seven", "email": "sdasda", "gender": "男"},
]
# for index in range(20):
#     temp = {"username": "alex" + str(index), "email": "sdasda", "gender": "男"}
#     USER_LIST.append(temp)


def home(request):
    if request.method == "POST":
        # 獲取用戶提交的數據 POST請求中
        username = request.POST.get("username")
        email = request.POST.get("email")
        gender = request.POST.get("gender")
        temp = {"username": username, "email": email, "gender": gender}
        USER_LIST.append(temp)
    return render(request, "home.html", {"user_list": USER_LIST})

 def func(request):
    # request.method    GET/POST
    # request.GET.get("", None) 獲取請求發來的數據
    # request.POST.get("", None)    獲取請求提交的數據

    return HttpResponse("字符串")
    return render(request, "html模板路徑")
    return redirect("/url路徑")

九、渲染模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body style="margin: 0;">
    <div style="height: 48px;background-color: #dddddd;"></div>
    <div>
        <form action="/home" method="POST">
            <input type="text" name="username" placeholder="用戶名"/>
            <input type="text" name="email" placeholder="郵箱"/>
            <input type="text" name="gender" placeholder="性別"/>
            <input type="submit" value="添加"/>
        </form>
    </div>
    <div>
        <table>
            {%  for row in user_list %}
            <tr>
                <td>{{ row.username }}</td>
                <td>{{ row.gender }}</td>
                <td>{{ row.email }}</td>
            </tr>
            {% endfor %}
        </table>
    </div>
</body>
</html>


模板渲染

變量 {{ 變量名 }}

def func(request):
    return render(request, "html模板", {"current_user": "alex"})
<!-- 模板 -->
<html>
<body>
    <div>{{ current_user }}</div>
</body>
</html>

<!-- 渲染後生成的頁面 -->
<html>
<body>
    <div>alex</div>
</body>
</html>


條件判斷 {% if 條件 %}{% else %}{% endif %}

def func(request):
       return render(request, "html模板路徑", {"current_user": "alex",
        "user_list": ["alex", "eric"],
        "age": 18})
{% if age %}
   <a>有年齡</a>
   {% if age > 16 %}
       <a>老男人</a>
   {% else %}
       <a>小鮮肉</a>
   {% endif %}
{% else %}
   <a>無年齡</a>
{% endif %}


for循環 {% for row in user_list %}{% endfor %}

def func(request):
       return render(request, "html模板路徑", {"current_user": "alex",
        "user_list": ["alex", "eric"]})
<html>
<body>
    <div>{{ current_user }}</div>
    <ul>
        {% for row in user_list%}
        <li>{{ row }}</li>
        {% endfor %}
    </ul>
</body>
</html>



十、運行

python manage.py runserver 127.0.0.1:8000

本文出自 “八英裏” 博客,請務必保留此出處http://5921271.blog.51cto.com/5911271/1926729

Python之路58-Django安裝配置及一些基礎知識點