วันอังคารที่ 14 มีนาคม พ.ศ. 2560

4. สร้างหน้าเว็บแสดงผล

สร้างหน้าเว็บ

การสร้างหน้าเว็บแสดงผล จะประกอบด้วย 3 ส่วน ได้แก่ url  view และ template

    url

    ทำการสร้าง URL ใน accounts/url.py เพื่อเรียกใช้ method ใน view ตามURL address ที่ได้รับ
app_name = 'accounts'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^(?P<account_id>[0-9]+)/$', views.detail, name='detail'),
]
    views.index และ views.detail จะเป็นการระบุปลายทางที่จะเรียกใช้ เช่น views.index จะเรียกใช้ method index ใน views
    r'^$' หมายถึงเมื่อ URL address ว่าง เช่น http://127.0.0.1:8000/accounts/
    r'^(?P<account_id>[0-9]+)/$' หมายถึงเมื่อ URL address ตามด้วยตัวเลขเท่านั้น และจะส่งตัวแปรชื่อ account_id เป็นเลขที่ระบุไปที่ปลายทาง เช่น  http://127.0.0.1:8000/accounts/1 และจะส่งตัวแปร account_id = 1 ไปเป็น argument

    view

    สร้าง method ใน account/view.py ตามที่ระบุไว้ใน url.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse

from .models import Account, Transaction

def index(request):
    account_list = Account.objects.order_by('-create')
    context = {'account_list':account_list}
    return render(request, 'accounts/index.html', context)

def detail(request, account_id):
    account = get_object_or_404(Account, pk=account_id)
    transaction = account.transaction_set.order_by('-date','-id')
    context = {'account':account, 'transaction':transaction}
    return render(request, 'accounts/detail.html', context)
    ใน view จะเป็นดึงข้อมูลจาก model และอาจทำการประมวลผลก่อนที่จะแสดงเป็นหน้าเว็บ
index : จะนำ object ของ Account ทั้งหมดมาใส่ในตัวแปรและส่งให้ template
detail : จะนำ object ของ Transaction ที่อยู่ใน Account เดียวกับ account_id ที่ได้รับมา แล้วส่งต่อให้ template

    template

    สร้างไฟล์ template เป็นไฟล์ html อยู่ใน mysite/accounts/templates/accounts/
    index.html :
<h1>Account Lists</h1>
    {% if account_list %}
        {% for account in account_list %}
        <a href = {% url 'accounts:detail' account.id %}>{{account.name}}</a>
        {% endfor %}
    {% endif %}
    detail.html :
<h1>{{ account.name }}'s account </h1>
    {% if transaction_list %}
        {% for action in transaction_list %}
        {{action.date}}-{{ action.description }}-{{action.actionType}}-{{action.value}}
        {% endfor %}
    {% endif %}
  เมื่อเข้าไปที่ http://127.0.0.1:8000/accounts/  จะพบกับหน้าแสดงรายชื่อบัญชี และเมื่อคลิกที่ชื่อบัญชีจะเข้าไปที่หน้าแสดงรายการของแต่ละบัญชี
index:
   
detail:

ไม่มีความคิดเห็น:

แสดงความคิดเห็น