วันอาทิตย์ที่ 8 ธันวาคม พ.ศ. 2556

การจัดการและการใช้งาน Form (Tutorial part 4)

    ใน tutorial part 4 นี้จะเป็นเนื้อหาเกี่ยวกับการใช้งาน form ซึ่ง form จะถูกใช้งานก็ต่อเมื่อต้องการจะเก็บข้อมูลจากผู้ใช้ ไม่ว่าจะเป็น ประวัติ การเข้าชมเว็บไซต์ และ อื่นๆอีกมากมาย

เริ่มต้นเราจะแก้ไขไฟล์ detail.html ที่อยู่ใน polls/templates/polls/ ตามนี้

<h1>{{ poll.question }}</h1>

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}

<form action="{% url 'polls:vote' poll.id %}" method="post">
{% csrf_token %}
{% for choice in poll.choice_set.all %}
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
    จาก code html ข้างบนจะเป็นการใช้ form สร้าง action โดยการเรียกใช้ฟังก์ชั่น vote จาก app polls และจะมีการวน for เพื่อทำการดึงค่า choice ทั้งหมดออกมา


<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
เป็นการสร้าง input แบบให้เลือกติ๊ก


<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
label คือ text ที่ใช้แสดงข้อมูลของ string 


<input type="submit" value="Vote" />
เป็นการสร้างปุ่มกด โดยจะมีข้อความบนปุ่มกดว่า Vote

จากนั้นให้ทำการแก้ไขฟังก์ชั่น vote ที่อยู่ใน polls/views.py ๖ามนี้

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from polls.models import Choice, Poll
# ...
def vote(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the poll voting form.
        return render(request, 'polls/detail.html', {
            'poll': p,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
จาก code
p = get_object_or_404(Poll, pk=poll_id)
เป็นการใช้ shortcut 404 error

selected_choice = p.choice_set.get(pk=request.POST['choice'])
เป็นการดึงค่า object จาก choice โดย request.POST เป็น dictionary โดยรับ key คือ choice ไปแล้วจะ return string ของ value กลับมา

selected_choice.votes += 1
selected_choice.save()
เป็นการเพิ่มค่า vote ไป 1 แล้วทำการ save ข้อมูล


return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
เป็นการ ส่งข้อมูลโดยตรงไปยังฟังก์ชั่น results

เมื่อลองเทสจะได้ผลลัพธ์ดังนี้
ต่อไปจะทำการแก้ไขฟังก์ชั่น results ใน polls/views.py ตามนี้

from django.shortcuts import get_object_or_404, render

def results(request, poll_id):
    poll = get_object_or_404(Poll, pk=poll_id)
    return render(request, 'polls/results.html', {'poll': poll})
จาก code ข้างบน จะสังเกตุได้ว่าเหมือนตอนแก้ไขฟังก์ชั่น detail ใน Tutorial part 3 

จากนั้นให้ทำการสร้างไฟล์ results.html ไว้ใน polls/templates/polls/ แล้วเขียน code ตามนี้

<h1>{{ poll.question }}</h1>

<ul>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' poll.id %}">Vote again?</a>
จาก code html ข้างบน จะเป็นการวน for เพื่อจะดึงข้อมูล choice ทั้งหมดออกมา เพื่อแสดงค่า โหวตของ choice


<a href="{% url 'polls:detail' poll.id %}">Vote again?</a>
เป็นการแสดง link ชื่อว่า Vote again? เมื่อทำการคลิก จะเรียกใช้ฟังก์ชั่น detail เพื่อทำการโหวตอีกครั้ง เมื่อทำการเทส จะได้ผลลัพธ์ดังนี้

ต่อไปจะเป็นการใช้ generic views
    การใช้ generic views นั้นจะทำให้ code สั้นลงมาก โดยการเปลี่ยนฟังก์ชั่นใน views.py ทั้งหมดเป็น class โดยเริ่มต้นเราจะทำการแก้ไขไฟล์ polls/urls.py ตามนี้

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
    url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
    url(r'^(?P<poll_id>\d+)/vote/$', views.vote, name='vote'),
)
    จาก code ข้างต้น จะเปลี่ยนจาก view.index เป็น view.IndexView.as_view() เพื่อจะทำการเรียกใช้ class IndexView และเปลี่ยนจาก poll_id เป็น pk ในส่วนของ detail และ result เพราะว่าทั้งสอง class นี้จะใช้ generic views แบบ DetailView ซึ่งสามารถรองรับข้อมูลเป็น pk(primary key) ได้เลย ในส่วนของ vote นั้นเราจะไม่ทำการเปลี่ยนแปลงใดๆเพราะว่ายังใช้เป็น ฟังก์ชั่นเหมือนเดิม

ต่อไปเราจะทำการแก้ไขไฟล์ polls/views.py ตามนี้

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic

from polls.models import Choice, Poll

class IndexView(generic.ListView):
    template_name = 'polls/index.html'
    context_object_name = 'latest_poll_list'

    def get_queryset(self):
        """Return the last five published polls."""
        return Poll.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    model = Poll
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    model = Poll
    template_name = 'polls/results.html'

def vote(request, poll_id):
    ....

    จาก code จะเห็นได้ว่าจะเปลี่ยนจาก def index, def detail, def results มาเป็น class IndexView, class DetailView, class ResultsView และภายใน class นั้นจะสั้นลงมากโดย

template_name = 'polls/index.html'
เป็นการระบุไฟล์ template 

context_object_name = 'latest_poll_list'
เป็นการกำหนดชื่อ tag ของ template ที่ต้องการ context 

def get_queryset(self):
        """Return the last five published polls."""
        return Poll.objects.order_by('-pub_date')[:5]
ฟังก์ชั่นนี้สร้างมาเพื่อแสดงค่าของ object ในเวลา 5 ลำดับล่าสุด

model = Poll
เป็นการกำหนดเลือกใช้ Model ที่ต้องการ 

class IndexView(generic.ListView):
เป็นการระบุว่าใช้ generic views แบบ ListView


class DetailView(generic.DetailView):
class ResultsView(generic.DetailView):
เป็นการระบุว่าใช้ generic views แบบ DetailView

    จากบทความนี้ จะสอนให้รู้จักการใช้ form ได้เข้าใจเกี่ยวกับ generic views ที่ทำให้ code สั้นลง

ข้อมูลอ้างอิง : Tutorial part 4

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

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