วันศุกร์ที่ 18 มกราคม พ.ศ. 2562

[Django] continue tutorial

Raising a 404 error

         เป็นการกำหนดค่าที่จะแสดง error เมื่อมีข้อผิดพลาดเกิดขึ้นจากการกำหนดเลขใน url ที่เรียกไม่ถูกต้อง หรือไม่มีเลขข้อนั้นๆ อยู่ในฐานข้อมูล

def detail(request, question_id):
try:    #เรียกฟังก์ชัน
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:   #รีเทิร์นเมื่อเกิด error
raise Http404("Question does not exist")
return render(request, 'polls/detail.html',{'question': question})

แบบย่อ
       ใช้คำสั่งเฉพาะในการใช้งาน 
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})

----------------------------------------------------------------------------------------

Namespacing URL names

ในกรณีที่ในโปรเจคมีการสร้างหลาย app และมีหลาย template การตั้งชื่อ app ทำให้ง่ายกับการเรียกใช้งาน

from django.urls import path
from . import views

app_name = 'polls’
urlpatterns = [
  path('', views.index, name='index'),
  path('<int:question_id>/', views.detail, name='detail'),
  path('<int:question_id>/results/',views.results,name='results'),
  path('<int:question_id>/vote/', views.vote, name='vote'),
]

------------------------------------------------------------------------------------------

views.py

#เรียกทุกคำถามที่มีในฐานข้อมูลออกมาแสดงบนหน้าเว็บ
def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

#แสดงคำถามและตัวเลือกตามเลขข้อ โดยใช้ template detail.html
def detail(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/detail.html', {'question': question})

#แสดงผลลัพธ์คะแนนการโหวตที่แต่ละตัวเลือกได้รับไป
def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})

#จะมีการเรียก template detail.html มาแสดงและเมื่อมีการโหวต ตัวเลือกที่ถูกเลือกก็จะมีการบวกผลโหวตเพ่มขึ้นไปและแสดงหน้าผลลัพธ์ของการโหวต และ บันทึกผลโหวตลงฐานข้อมูลด้วยคำสั่ง  selected_choice.save() แต่หากไม่มีการเลือกโหวตตัวเลือกใดๆ จะแสดง error_message เป็น You didn't select a choice.

def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

---------------------------------------------------------------------------------------------------




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

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