1. 程式人生 > >Django基礎筆記

Django基礎筆記

src shortcuts cfi block repl div dir etag clas

模塊的使用:
對HTML內容的渲染的模板 :

1.render
  from django.shortcuts import render
  def r(request):
    return render(request,‘index.html‘)
2.render_to_string
  from django.template.loader import render_to_string
  from django.http import HttpResponse
  def r(request):  
    html = render_to_string(‘index.html‘)
    return HttpResponse(html)

  

模板查找路徑配置:
  settings.py 下的TEMPLATES配置,包含了模塊引擎的配置
  DIRS:一個列表,可以存放所有的模塊路徑,以後在視圖中使用render渲染模板的時候,會在這個列表的路徑中查找模板
  APP_DIRS:默認為True,設置為True,會在INSTALLED_APPS的安裝了的APP下的templates文件夾中查找模板
  INSTALLED_APPS:配置的作用是類似DIRS作用,讓他尋找當前apps下的templates文件下的模塊
DTL模塊語法:

模塊中變量的引用:

模塊中變量的引用:
1.直接傳遞字典

views.py
  def index(request):
    context = {
      ‘username‘ : ‘ziliao‘
     }
    return render(request,‘index.html‘,context=context)
index.html
  {{ username }}

2.通過函數方式

views.py
    class Person(object):
    def __init__(self,username):
      self.username = username
  def index(request):
    p = Person(‘ziliao‘)
    context = {
      ‘person‘ : p
    }
    return render(request,‘index.html‘,context=context)
index.py
  { person.username }}

  

3.字典中包含字典

views.py:
  def index(request):
    context = {
      ‘persion‘ : {
      ‘username‘ : ‘ziliao‘
       }
    }
    return render(request,‘index.html‘,context=context)
index.html
  {{ persion.username }}

  

4.字典中包含列表

views.py:
  def index(request):
    context = {
    ‘persion‘ : [
      ‘圖書館‘,
      ‘廣州‘
     ]
  }	
index.html
  {{ persion.0 }}	

從上述中,可以得到結論,無論後臺傳入的參數是字典,對象還是列表等
在前端的調用傳入參數,都是通過 xxx.xxx的方式進行調用

標簽的使用:if、for、url

if標簽:(判斷符 < = ... in )

views.py
  def index(request):
    context = {
    ‘age‘: 18
  }
  return render(request,‘index.html‘,context=context)	
index.html
  {% if age < 18 %}
    <p>未成年人</p>
  {% elif age > 18 %}
    <p>成年人</p>
  {% else %}
    <p>18歲騷年</p>
  {% endif %}

for標簽:

views.py
  def index(request):
  context = {
    ‘books‘:[
    ‘三國演義‘,
    ‘水滸傳‘,
    ‘紅樓夢‘,
    ]
  }
  return render(request,‘index.html‘,context=context)
index.html
  <ul>
    {% for book in books %} #在books 後加reversed代表翻轉輸出
      <li>{{ book }}</li>
    {% endfor %}
  </ul>

在for循環中,DTL提供一些變量可供使用,變量如下:


forloop.counter:當前循環的下標,以1作為其始值

{% for book in books %}
  <tr>
    <td>{{ forloop.counter }}</td>   #變量的例子
    <td>{{ book.name }}</td>
    <td>{{ book.author }}</td>
    <td>{{ book.price }}</td>
  </tr>
{% endfor %}

  

在for循環中其內容為空:可加 empty

{% for comment in comments %}
  <li>{{ comment }}</li>
{% empty %} 
  <li>沒有任何評論</li>
{% endfor %}

懵懂

url標簽:
views.py
  #登錄
  def login(request):
    next = request.GET.get(‘next‘)
    text = ‘登錄頁面,登錄完成後要跳轉的url是: %s‘ % next
    return HttpResponse(text)

  #首頁
  def index(request):
    return render(request, ‘index.html‘)

  #最火的一篇文章
  def book_detail(request,book_id):
    text = ‘您的圖書的id是:%s‘ % book_id
    return HttpResponse(text)
index.html
  <li><a href="{% url ‘city‘ %}">首頁</a></li>
  <li><a href="{% url ‘detail‘ book_id=‘1‘ %}">最火的一篇文章</a></li>
  <li><a href="{% url ‘login‘ %}?next=/">登錄</a></li>

  

解析:在登錄中的url為: http://127.0.0.1:8000/login/?next=/
在最火的一篇文章的url為: http://127.0.0.1:8000/book/detail/1/
兩個的不同之處在於,一個從前端獲取參數值,一個傳遞參數值給前端


DTL過濾器:
  在模板中,有時候需要對一些數據進行處理以後才能使用,一般在python中我們是通過函數的形式來實現,
  而在模板中,則通過過濾器來實現,過濾器使用是 | 來使用

add
  將傳進來的參數添加到原來的值上面,列表則是添加到一個列表中

views.py
  def index(request):
    context = {
    ‘value1‘:[‘1‘,‘2‘,‘3‘],
    ‘value2‘:[‘4‘,‘5‘,‘3‘]
    }
    return render(request,‘add.html‘, context=context)
index.html
  <p>{{ "1"|add:"2"}}</p>
  <p>{{ value1 | add:value2 }}</p>
結果為:3	
    [‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘]  

cut
  移除值中所有指定的字符串,類似於python中的replace(arg,‘‘)

views.py
  def index(request):
    return render(request,‘index.html‘)
index.html
    {{"hello / world"|cut:"/" }}
結果:hello world

date

views.py
  from datetime import datetime   def index(request):     context = {     ‘today‘:datetime.now()      }     return render(request,‘index.html‘, context=context) index.html   {{ today|date:"Y/m/d" }} 結果:2018/09/09

  

模板繼承

base.html
  <body>
    <li>公共部分</li>
    <li>
      {% block content %}
      {% endblock %}
    </li>
  </body>
index.html
  {% extends ‘base.html‘ %}
  {% block comment %}
    新添加的內容
  {{ block.super }} #繼承父模板在 block中寫的內容

  {% endblock %}

 

加載靜態文件

1.在setting設置 INSTALLED_APPS 添加 ‘django.contrib.staticfiles‘  

#在瀏覽器中請求靜態文件的url
    #127.0.0.1、static/xx.jpg

2.

STATIC_URL = ‘/static/‘ 


綁定在app下的靜態文件

3.

在調用某app中的靜態文件,需要在 INSTALLED_APPS 中添加 其app名

4.加載靜態文件
  

方式1、直接調用
      <img src=‘/static/1.jpg‘ alt=‘‘>
方式2、通過static方式調用
      {% load static %}
      <img src="{% static ‘1.jpg‘ %}" >
方式3、調用另一個app下同名的靜態文件
      可以通過在不同app下創建以下目錄結構
      --app1
        --static
          --app1	
            1.jpg
      --app2
        --static
          --app2
            1.jpg
      {% load static %}
      <img src="{% static ‘app1/1.jpg‘ %}" >

  

沒有和app綁定的靜態文件,在和app同級目錄下創建static目錄

5.重新在setting.py文件下指定配置

 STATICFILES_DIRS = [
   os.path.join(BASE_DIR,‘static‘)
  ]

6.在加載靜態文件時,需要頭添加{% load static %},如果不想在每一個文件都添加此內容,可以做以下操作   

在setting.py 文件下的TEMPLATES 配置下添加 ,可以把static添加到django內置中
    ‘builtins‘:[‘django.templatetags.static‘]

  




Django基礎筆記