Django--初始化


1、Django介紹

它是一個WEB框架

  • Django--大而全

  • tornado、flask--小而精


2、Django安裝

    https://www.djangoproject.com/download/


3、創建django程序

  • 手動創建

file--new project--Django--Location--create(打開后最好不要有上層目錄)

  • 命令創建

cmd>django-admin startproject sitename


4、程序目錄


各文件作用:
  • settings.py--配置文件

  • urls.py--路由

  • wsgi.py--用那種wsgi方式(wsgi或者uwsgi)

  • templates--html模板

  • manage.py--主程序,啟動程序

注意:不要輕易更改項目的名稱,涉及的地方太多。
還有其他目錄:

app--項目里的一個擴展,可以有多個,如前台和后台



5、 創建app目錄

cmd> python manage.py startapp app01

app目錄--項目里的一個擴展,可以有多個,如前台和后台

--models.py,對數據庫進行操作

--views.py,視圖,函數

--tests.py,測試用

--admin.py,后台管理程序  http://127.0.0.1:8000/admin/


6、生成超級用戶

沒有數據庫要先創建表,不然生成用戶會報錯:no such table:auth_user

cmd> python manage.py syncdb

cmd> yes

此時創建的用戶就能進入后台管理,另外生成了一個db.sqlite3數據庫文件,用sqlite工具能看到具體信息,如navicat等。

如果要生成到mysql數據庫,需要在settings.py里配置。

創建超級用戶:

cmd> python manage.py createsuperuser

在后台的用戶表里就能看到用戶user和group了


7、啟動服務

cmd> python manage.py runserver 127.0.0.1:8000


8、第一個Django程序

路由--urls.py
1
2
3
4
5
from app01 import views
urlpatterns = [
     url(r '^admin/' , admin.site.urls),
     url(r '^home/' , views.home),
]
請求處理--views.py

1
2
3
from django.shortcuts import HttpResponse     
def home(request):                          //必要參數request,包含請求的全部信息。
     return HttpResponse( "ok" )               //Django返回的字符串需要用HttpResponse()包裝,不能直接返回字符串。


9、模板渲染

路由--urls.py

同上

請求處理--views.py
1
2
3
4
from django.shortcuts import render
dic={ 'arg' : 'home1' ,}
def home(request):
     return render(request, 'home.html' ,dic)  #讀取home.html,並返回給請求者,dic是參數,傳到頁面中
模板--templates/home.html
1
2
3
4
from django.shortcuts import render
dic={ 'arg' : 'home1' , 'user_list' :[ 'user1' , 'user2' ]}
def home(request):
     return render(request, 'home.html' ,dic)  #讀取home.html,並返回給請求者,dic是參數,傳到頁面中


10、render的原理

  1. 打開html文件--open()

  2. 渲染模板和內容--Template()

  3. 返回字符串--HttpResponse()

1
2
3
4
5
6
7
8
9
10
import datetime
from django import template
import DjangoDemo.settings
  
now = datetime.datetime.now()
fp = open(settings.BASE_DIR+ '/templates/Home/Index.html' )
t = template.Template(fp.read())
fp.close()
html = t.render(template.Context({ 'current_date' : now}))
return HttpResponse(html)


11、模板語言

模板中也有自己的語言,該語言可以實現數據展示

  • {{ item }}

  • {% for item in item_list %}  <a>{{ item }}</a>  {% endfor %}
      forloop.counter
      forloop.first
      forloop.last 

  • {% if ordered_warranty %}  {% else %} {% endif %}

  • 母板:{% block title %}{% endblock %}
    子板:{% extends "base.html" %}
       {% block title %}{% endblock %}

  • 幫助方法:
    {{ item.event_start|date:"Y-m-d H:i:s"}}
    {{ bio|truncatewords:"30" }}
    {{ my_list|first|upper }}
    {{ name|lower }}

方法有限,如果想使用跟多模板方法,需要自定義,看下面一節。


12、自定義方法--simple_tag

  1. 在app中創建templatetags模塊

  2. 創建任意 .py 文件,如:xx.py

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    from django import template
    from django.utils.safestring import mark_safe
    from django.template.base import resolve_ var iable, Node, TemplateSyntaxError
       
    register = template.Library()
       
    @register.simple_tag
    def my_simple_time(v1,v2,v3):
         return  v1 + v2 + v3
       
    @register.simple_tag
    def my_input(id,arg):
         result = "<input type='text' id='%s' class='%s' />" %(id,arg,)
         return mark_safe(result)
  3. 在使用自定義simple_tag的html文件開頭導入之前創建的 xx.py 文件名

    1
    {% load xx %}
  4. html中使用simple_tag

    1
    2
    3
    4
    <body>
         {% my_simple_time 1 2 3 %}
         {% my_input 'id_username' 'hide' %}
    </body>
  5. 在settings中配置當前app,不然django無法找到自定義的simple_tag 

    1
    2
    3
    4
    5
    6
    7
    8
    9
    INSTALLED_APPS = [
         'django.contrib.admin' ,
         'django.contrib.auth' ,
         'django.contrib.contenttypes' ,
         'django.contrib.sessions' ,
         'django.contrib.messages' ,
         'django.contrib.staticfiles' ,
         'app01' ,
    ]
效果:
  • 第一個函數是算加法,1、2、3是參數;

  • 第二個函數是寫一個標簽,'id_username' 'hide'是參數。


13、母版,子版,include

templates里創建一個目錄:master,目錄里創建文件mother.html和son.html


母版mother.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<head>
     <meta charset= "UTF-8" >
     <title>{% block title %}{% endblock %}</title>
     <style>
         .header{
             height: 48px;
             background-color: red;
         }
         .body{
             background-color: antiquewhite;
         }
         .body .menu{
             background-color: aqua;
             width: 20 %;
             float: left;
         }
         .body .content{
             background-color: aquamarine;
             width: 80 %;
             float: left;
         }
     </style>
</head>
<body>
     <div class = "header" >LOGO</div>
     <div class = "body" >
         <div class = "menu" >左側菜單</div>
         <div class = "content" >{% block content %}{% endblock %}</div>
     </div>
</body>
</html>
子版son.html

1
2
3
4
5
6
7
8
9
10
{% extends "master/mother.html" %}
 
{% block title %}
     母版子版
{% endblock %}
 
{% block content %}
     <h1>Son的右側內容</h1>
     {% include "include/input_group.html" %}
{% endblock %}
路由urls.py
1
2
3
4
5
from app01 import views
urlpatterns = [
     url(r '^admin/' , admin.site.urls),
     url(r '^son/' , views.son),
]
視圖views.py
1
2
3
from django.shortcuts import render
def son(request):
     return render(request, 'master/son.html' )
給son添加include內容,include功能


input_group.html
1
2
3
4
5
<h1>Include輸入組合</h1>
<input type= "text" />
<input type= "text" />
<input type= "text" />
<input type= "text" />
效果:


注意點:
  • 母版只能繼承一個。

  • 當某一小塊功能用在很多頁面中,用include。

  • son加css樣式,{% block css %}{% endblock %}

  • son加js,{% block js %}{% endblock %}


14、Django中的靜態文件

創建目錄


配置文件settings​.py
1
2
3
4
STATIC_URL = '/static/'
STATICFILES_DIRS = (
     os.path.join(BASE_DIR, 'static' ),
)
調用
1
<link ref= "stylesheet" href= "/static/css/common.css" >

















免責聲明!

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



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