iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 9
0
Modern Web

使用 Django 開發網頁系統系列 第 9

[Day 09] 顯示全部資料

今天講如何顯示全部資料

先用 http://localhost:8000/admin/ 的方式建幾筆 類別 資料吧

先把 路由 views 設定好
shop/urls.py 加上 store url

urlpatterns = [
    path('admin/', admin.site.urls),
    path('store/', include('store.urls')),
    ...
]

新增 store/urls.py

from django.urls import path
from store import views

urlpatterns = [
    path('category/', views.category)
]

store/views.py

from django.shortcuts import render

# Create your views here.
def category(request):
    return render(request, 'store/category.html')

store/templates/store/category.html

<!doctype html>
<html>
<head></head>
<body>
category page
</body>
</html>

http://localhost:8000/store/category/
確定頁面跟views.py隊的之後開始寫撈資料程式

django ORM(Object Relational Mapping)
功能是可以用類似物件的方式對應到資料表及欄位,來做到資料表的增刪修查
這裡就是使用models.py 定義的類別來做mapping

query all
https://docs.djangoproject.com/en/2.0/topics/db/queries/#retrieving-all-objects

<model_name>.objects.all() 撈全部資料
並且把結果傳到前端,是queryset型態類似list
可以用print()方式,印出來會比較好懂
store/views.py

from store.models import Category
def category(request):
    categorys = Category.objects.all()
    return render(request, 'store/category.html', {'categorys':categorys})

前端這裡用forloop class.label

<class>.<field> 點後是指欄位
這裡是show name欄位
store/templates/store/category.html

...
<body>
{% for category in categorys %}
  {{ category.name }}
{% endfor %}
</body>
...

可以再用 HTML 的 table顯示出來

store/templates/store/category.html

...
<body>
<table>
  <tr>
    <th>類別</th>
  </tr>
  {% for category in categorys %}
    <tr>
      <td>{{ category.name }}</td>
    </tr>
  {% endfor %}
</table>
</body>
...

結果圖
https://ithelp.ithome.com.tw/upload/images/20171227/20107183xX4bRQjFat.png

就完成了顯示多筆資料


上一篇
[Day 08] admin.py
下一篇
[Day 10] 新增資料
系列文
使用 Django 開發網頁系統30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言