วันพฤหัสบดีที่ 31 มกราคม พ.ศ. 2562

HTML Table

HTML Table
     เป็นการสร้างตารางด้วยภาษา html โดยมีองค์ประกอบคือ
<table> กำหนดให้สร้างตาราง
<th>        สร้างหัวข้อ
<tr>        ขึ้นบรรทัดใหม่
<td>       ขึ้นคอลัมน์ใหม่

ตัวอย่างการใช้งาน <table>


<table align="center" border="1" bgcolor="#FFFF99">
  <tr>
    <td>ลำดับที่</td>
    <td>คำถาม</td>
    <td>วันที่สร้าง</td>
    <td align="right">ตัวเลือก</td>
  </tr>
        {% for question in latest_question_list %}
        <tr>
            <td>{{question.id}}</td>
            <td>{{ question.question_text }}</td>
            <td>{{question.pub_date}}</td>
            <td >
            {% for choice in question.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 %}
            </td>
         </tr>
        {% endfor %}

</table>

---------------------------------------------------------------------------------------------------------
ผลลัพธ์ที่ได้


นอกจากนี้เรายังสามารถกำหนดคุณสมบัติต่างๆของตารางได้ดังนี้
align="..." กำหนดตำแหน่งของข้อความภายในตาราง
border="…" กำหนดความเข้มของเส้นขอบตาราง
width="…%" กำหนดความกว้างของตาราง
height="…%" กำหนดความยาวของตาราง
bgcolor="…" กำหนดสีของตาราง
rowspan=" ... " กำหนดการรวมแถว
colspan= " ... " กำหนดการรวมคอลัมน์

Cr : https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table

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

[Django] Form

Form คือ
- รูปแบบการจัดการเกี่ยวกับการรับค่าและแสดงค่าบนหน้าเว็บด้วยการจัดการร่วมกับการใช้งาน template
- เป็นตัวส่งข้อมูลไปประมวลผลฝั่ง server
- สามารถลดความซับซ้อนของงานได้

Form มีการใช้งานหลักๆ 2 แบบ คือ 
1 HTML Form
2 From class

HTML Form
       สร้างภายใต้ tag  <form>  … </form> เพื่อให้เกิดการทำงานต่างๆ เช่น การรับค่าแล้วส่งคืนไป
สำหรับส่วนที่ใช้ในการติดต่อเพื่อรับค่านั้นจะอนู่ใน tag <input> ซึ่งมีหลายรูปแบบด้วยกัน และต้องระบุ 2 สิ่งใน <input>
- ข้อมูลที่ได้รับมาจากผู้ใช้จะถูกส่งไปที่ไหน
- ใช้วิธีใดในการส่งข้อมูล

วิธีส่งข้อมูล มี 2 วิธี คือ GET และ POST

GET
- ไม่มีการเปลี่ยนแปลงที่ฐานข้อมูล
- ex. การเรียกผลลัพธ์ออกมาแสดง
- suitable for search form

POST
- มีการปลี่ยนแปลงข้อมูลที่ฐานข้อมูล
- ex. การรับผลโหวตเข้าไปเก็บไว้
- suitable for หลายๆรูปแบบ เช่น form ข้อสอบ , form การสั่งซื้อ

วิธีระบุปลายทาง
การระบุปลายทางคือ การระบุว่า HTML From ทีี่สร้างขึ้นจะถูกนำไปใช้ที่ใด โดยระบุในส่วนของ <form>

detail.html >>

<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.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>

หมายถึง เมื่อมีการเรียกใช้ฟังก์ชันที่ใช้งาน template detail.html จะทำการสร้าง from ตามที่กำหนด
และ ส่งค่าที่ได้จาก form ไปใช้งานที่ url 'polls:vote' question.id และใช้งานฟังก์ชันตามที่ระบุไว้ใน urls.py


Form class


     มีรูปแบบและโครงสร้างเหมือน models แต่ field ของ models จะ map ไปที่ field ของฐานข้อมูล 
ส่วน field ของ form จะ map ไปที่ <input> ของ HTML

froms.py >>

from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)

การใช้งาน from Django จะนำ form ที่เราสร้างไปแปลงเป็น html เอง ดังนี้

<label for="your_name">Your name: </label>
<input id="your_name" type="text" name="your_name" maxlength="100" required>



วันอาทิตย์ที่ 27 มกราคม พ.ศ. 2562

[Django] input type

input แบ่งเป้น 4 กลุ่ม ได้แก่
- Text
- checkboxes and selectors
- uploading files
- handling of multi-valued input.

Text จะมีการรับข้อความโดยการใช้ ช่องสี่เหลี่ยมเปล่าๆ ให้ผู้ใช้สามารถพิมพ์ลงไปในช่องได้ โดยแต่ละแบบมีเงื่อนไขที่แตกต่างกันออกไป เช่น

TextInput
Renders as: <input type="text" ...>
รับข้อความเป้นตัวหนังสือแบบ 1 บรรทัด สามารถกำหนดความยาวของข้อมูลที่รับได้ 

NumberInput
Renders as: <input type="number" ...>
รับข้อความที่เป็นตัวเลขเท่านั้น

EmailInput
Renders as: <input type="email" ...>
ในข้อความต้องประกอบด้วย @ ที่แสดงถึงการเป็น email

URLInput
Renders as: <input type="url" ...>
เป็นประเภท url เท่านั้น

PasswordInput
Renders as: <input type="password" ...>
เมื่อกรอกข้อความลงไปจะถูกแทนที่ด้วยสัญลักษณ์แทนข้อความ

checkboxes and selectors มีลักษณะเป็นการแสดงตัวเลือกให้เลือก โดย checkbox จะแสดงเป็นช่องสี่เหลี่ยมและสามารถเลือกได้หลายตัวเลือก ส่วน selector นั้น จะเป็นประเภท radio ที่สามารถเลือกได้เพียงตัวเลือกเดียว

การใช้แบบ chechbox


การใช้แบบ radio

uploading files เป็นการเลือกไฟล์ประเภทต่างๆ เพื่ออัพเดทขึ้นเว็บไซต์ เช่น ไฟล์เอกสาร ไฟล์ภาพ หรือไฟล์มัลติมีเดียต่างๆ เป็นต้น


การใช้งาน git

1 Download git ตามระบบปฏิบัติการที่ใช้งานจากเว็บไซต์
https://git-scm.com/downloads

2 ตั้งค่า Git Configurations โดย
     git config --global user.name " ตั้งชื่อ "
     git config --global user.email " ระบุ e-mail "
     git config --global --list  #จะแสดงชื่อและ e-mail ที่ตั้งค่าไว้

3.ใช้งานได้ 2 รูปแบบคือ
     1 สร้าง repository ใน GitHub และ ใช้การ git clone ตามด้วยลิ้งก์ของ repository ที่สร้างไว้ เพื่อทำการ clone ลงมาใช้งาน
     2 สร้าง repository ด้วยการใช้ git init หลังจากนั้นจึงใช้ git remote เพื่อทำงานเชื่อมต่อกับ repository ที่สร้างบน GitHub

ตัวอย่าง การสร้างผ่านการใช้ git init

>> สร้าง folder ชื่อ one

>> cd one                                  #เข้าไปใน folder

>> git init                                  # สร้าง repository

>> นำไฟล์ที่ต้องการอัพใส่ลงในโฟลเดอร์

>> git status                             # ตรวจสอบสถานะของโฟลเดอร์


-------------------------------------
On branch master

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)

        mysite/

nothing added to commit but untracked files present (use "git add" to track)
--------------------------------------
แสดงว่า เรานำ mysite มาใส่ลงในโฟลเดอร์แล้ว แต่ยังไม่ได้ทำการใดๆ ให้ use "git add" to track


>> git add mysite                                                    # add mysite

>> git status                                                            # ตรวจสอบสถานะอีกครั้ง

-----------------------------------------------------
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

        new file:   mysite/.vscode/settings.json
        new file:   mysite/db.sqlite3
------------------------------------------------------
ไฟล์ตามรายชื่อถูกเพิ่มแล้ว


>> git commit -m"add"                                           #ทำการ commit และ comment สิ่งที่ commit
-------------------------------------------------------
[master (root-commit) 77c1735] add
 31 files changed, 345 insertions(+)
 create mode 100644 mysite/.vscode/settings.json
 create mode 100644 mysite/db.sqlite3
 -------------------------------------------------------


>> git log                                     # เรียกเพื่อดูรหัสการ commit แต่ละครั้ง โดยใช้ 7 ตัวแรกในการอ้างอิง
-------------------------------------------------------
commit 77c173511046578a75194c6a0f96cb6fe7a8f1c4 (HEAD -> master)
Author: wanvipa <wanvipa1906@gmail.com>
Date:   Thu Jan 24 11:08:47 2019 +0700

    add
-------------------------------------------------------


>> git remote add origin https://github.com/Freezzes/one.git   

#ตั้งค่าการ commit ให้ไฟล์ไปแสดงในโฟลเดอร์ตามลิ้งก์ https://github.com/Freezzes/one.git

>> git remote -v                                                 # เรียกดูความสามารถในการ remote

-------------------------------------------------------
origin  https://github.com/Freezzes/one.git (fetch)
origin  https://github.com/Freezzes/one.git (push)
fetch คือ remote address ที่จะให้ไปดึงจากฝั่ง remote มายังฝั่ง local
push คือ remote address ที่จะให้เอาจากฝั่ง local ไปรวมที่ฝั่ง remote ที่ไหน
-------------------------------------------------------


>> git push origin master                                    # push ไฟล์ขึ้น GitHub
-------------------------------------------------------
Enumerating objects: 41, done.
Counting objects: 100% (41/41), done.
Delta compression using up to 4 threads
Compressing objects: 100% (37/37), done.
Writing objects: 100% (41/41), 18.42 KiB | 419.00 KiB/s, done.
Total 41 (delta 2), reused 0 (delta 0)
remote: Resolving deltas: 100% (2/2), done.      #แสดงว่าการ push สำเร็จแล้ว
To https://github.com/Freezzes/one.git
 * [new branch]      master -> master
-------------------------------------------------------


Cr :
https://git-scm.com/downloads

วันอาทิตย์ที่ 20 มกราคม พ.ศ. 2562

W4 Update

สิ่งที่ได้ศึกษาเรียนรู้

     1.ได้ศึกษาเกี่ยวกับการทำเว็บไซต์ด้วยการใช้ Django ที่มีการอำนวยความสะดวกในการสร้างเว็บหลากหลายอย่าง เช่น ส่วนการจัดการของแอดมิน , การสร้างและจัดการฐานข้อมูลด้วยการสั่งงานผ่าน command เป็นต้น

      2.การสร้างโปรเจคของ Django สามารถสร้างผ่าน command ด้วยการใช้งานคำสั่ง

django-admin startproject mysite   >> mysite คือชื่อโปรเจคที่เราต้องการสร้าง

โปรเจคที่สร้างขึ้นมาภายในจะประกอบไปด้วยโฟลเดอร์ชื่อเดียวกันกับโปรเจคและไฟล์ manage.py ซึ่งเป็นไฟล์ที่ใช้ในการสั่งให้โปรเจคทำงานต่างๆ โดยปกติแล้วจะไม่มีการแก้ไขไฟล์นี้ แต่จะมีการเรียกใช้งานเสมอๆ เช่น การสร้าง app , การ run server 

     3.การสร้าง app สามารถสร้างได้มากเท่าที่เราต้องการในโปรเจคของเรา โดยการ เปิดโปรเจคใน command และใช้คำสั่ง 
py manage.py startapp polls           >> polls คือชื่อของแอพลิเคชันที่อยู่ในโปรเจคที่เราทำการสร้างขึ้น

ภายในโปรเจคจะมีไฟล์ที่สร้างขึ้นมาพร้อมกันเพื่อให้เรานำไปใช้งานต่างๆ ต่อไป เช่น

views.py
     สำหรับสร้างฟังก์ชันการทำงานของเว็บ เช่น ฟังก์ชันให้แสดงผล ฟังก์ชันดึงค่าจากฐานข้อมูล ฟังก์ชันการคำนวณค่าต่างๆ โดยที่การทำงานจะทำตามเงื่อนไขแรกที่สำคัญคือ มีการ request เข้ามาเพื่อทำฟังก์ชันที่กำหนด เช่น ให้แสดงคำว่า  Hello World เป็นแบบหัวเรื่อง

def index(request):
     return HttpResponse("<h1>Hello World</h1>")

models.py 
     เป็นส่วนของการสร้างฐานข้อมูลด้วยการระบุองค์ประกอบต่างๆ ของฐานข้อมูล เช่น ชื่อฐานข้อมูล ชื่อ field ที่เก็บข้อมูลต่างๆ ประเภทของแต่ละ field และ การเชื่อมโยงของแต่ละ feild เป็นต้น ซึ่งแต่ละ feild จะต้องสร้างขึ้นใน class นั้นๆ เช่น ต้องการสร้างฐานข้อมูลเก็บคำถามที่เป็นตัวอักษร และให้ feild ชื่อว่า Question ให้เราทำการสร้าง class Question(models.Model) และระบุรายละเอียดของรูปแบบข้อมูลที่ต้องการลงใน class
ตัวอย่างการสร้างฐานข้อมูลของตัวเลือก โดยให้ตัวเลือกที่สร้างเป็นของคำถามแต่ละคำถามโดยมี field ชื่อ question เก็บคำถามที่ทำการเชื่อมโยงมาจากฐานข้อมูลคำถาม และสร้าง choice ของคำถามต่างๆ นั้นเป็น field ที่ชื่อว่า choice_text และมีประเภทเป็น CharField และเก็บผลคะแนนการโหวตเป็น IntegerField

class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):
        return self.choice_text

admin.py
    เป็นการระบุคำสั่งให้ส่วน แอดมินมีความสามารถอะไรข้าง เช่น

admin.site.register(Question)        >> ให้แอดมินสามารถจัดการคำถามได้

urls.py
     เป็นส่วนที่ทำการตรวจสอบระหว่าง url ที่ user ทำการพิมพ์ลงในช่องและส่ง request เข้ามา ว่าตรงกันกับ url ที่ตั้งไว้หรือไม่ หากตรงกันก็ให้ทำงานตามฟังก์ชันนั้นๆที่ได้ผูกติดอยู่กับลิ้งก์นั้น 

urlpatterns = [
    path('', views.index, name='index'),                                               >>ทำฟังก์ชัน views.index
    path('<int:question_id>/', views.detail, name='detail'),                 >>ทำฟังก์ชัน views.detail
    path('<int:question_id>/results/', views.results, name='results'),  >>ทำฟังก์ชัน views.results
    path('<int:question_id>/vote/', views.vote, name='vote'),             >>ทำฟังก์ชัน views.vote
    ]
 
     4.ทดลองสร้าง app ตาม tutorial ของเว็บไซต์ Django ซึ่งเป็น app ที่ใช้ในการสร้างโพลสำรวจและลงคะแนนโหวต

     5. ทดลองสร้าง template


ปัญหา / วิธีการแก้ไข
     1.พิมพ์ชื่อไม่ตรงกัน ทำให้เกิด error เมื่อทดลอง runserver

วิธีการแก้ไข >> อ่าน error ที่และดูไล่ลำดับจากบรรทัดที่เกิด error ตามการทำงาน เช่น
ไม่รู้จักฟังก์ชัน result ในไฟล์ views.py ก็จะเริ่มดูที่ไฟล์ views.py ซึ่งเรียก template มาใช้ และมีการเรียกฟังก์ชันที่ไฟล์ urls.py ก็จะไปดูที่ไฟล์ template และ urls.py ตามลำดับ

     2.ลืม import

วิธีการแก้ไข >> import สิ่งที่ลืมเข้ามาใช้งาน เช่น
การใช้งาน get_object_or_404( ) ต้องมีการ import ด้วย from django.shortcuts import get_object_or_404

     3.ทำข้ามขั้นตอน tutorial ทำให้เกิด error

วิธีการแก้ไข >> ย้อนกลับไปอ่าน tutorial ตรงจุดที่เกิด error ทำความเข้าใจใหม่ และ แก้ไข code


----------------------------------------------------
Cr :
https://docs.djangoproject.com/en/2.1/intro/tutorial01/
https://docs.djangoproject.com/en/2.1/intro/tutorial02/
https://docs.djangoproject.com/en/2.1/intro/tutorial03/
https://docs.djangoproject.com/en/2.1/intro/tutorial04/
https://docs.djangoproject.com/en/2.1/topics/templates/
http://www.tangowithdjango.com/book/chapters/models_templates.html
https://www.youtube.com/watch?v=l2YDT3fVv9k
https://medium.com/@9coding/

วันศุกร์ที่ 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,)))

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




วันอังคารที่ 15 มกราคม พ.ศ. 2562

[Django] Admin Vs API


Admin หรือ Administration 
     เป็นส่วนเสริมที่ Django ให้มาพร้อมกับการสร้างโปรเจค ทำให้เราสามารถปรับแต่ง และจัดการเว็บได้สะดวกมากยิ่งขึ้น โดยการสั่งการทำงานของ admin สามารถเข้าไปตั้งค่าได้ที่ admin.py และเพิ่มคำสั่ง admin.site.register( model ที่ต้องการจัดการ ) ก็จะทำให้ สามารถจัดการตัว model นั้นๆ ผ่านหน้า admin ได้

หน้าการจัดการของ admin แสดงการจัดการ การเพิ่มคำถามและตัวเลือก


API
          API ย่อมาจาก Application Programming Interface เป็นช่องทางการเชื่อมต่อ ที่จะเชื่อมต่อกับเว็บไซต์ผู้ให้บริการ API จากที่อื่น เป็นตัวกลางที่ทำให้โปรแกรมประยุกต์เชื่อมต่อกับโปรแกรมประยุกต์อื่น หรือเชื่ิอมการทำงานเข้ากับระบบปฏิบัติการ ซึ่ง ณ ที่นี้ เราใช้ API เพื่อติดต่อกันระหว่าง command กับ โปรแกรมภาษา python ที่เราได้สร้างขึ้น 

หลังจากที่เราได้สร้าง model question และ choice ไว้เรียบร้อยแล้ว เราก็จะทำการใช้งาน API ผ่าน command 

C:\Users\user\Documents\cleverkuma>python manage.py migrate
     เป็นการบอกว่ามีการเปลี่ยนแปลงกับ model 

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK


C:\Users\user\Documents\cleverkuma>python manage.py makemigrations pageone
Migrations for 'pageone':
  pageone\migrations\0001_initial.py
    - Create model Choice
    - Create model Question
    - Add field question to choice

               ทำการ migrations

C:\Users\user\Documents\cleverkuma>python manage.py sqlmigrate pageone 0001
BEGIN;

               สร้างฐานข้อมูล
--
-- Create model Choice
--
CREATE TABLE "pageone_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "score" integer NOT NULL);
--
-- Create model Question
--
CREATE TABLE "pageone_question" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "question_text" varchar(200) NOT NULL, "pub_date" datetime NOT NULL);
--
-- Add field question to choice
--
ALTER TABLE "pageone_choice" RENAME TO "pageone_choice__old";
CREATE TABLE "pageone_choice" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "choice_text" varchar(200) NOT NULL, "score" integer NOT NULL, "question_id" integer NOT NULL REFERENCES "pageone_question" ("id") DEFERRABLE INITIALLY DEFERRED);
INSERT INTO "pageone_choice" ("id", "choice_text", "score", "question_id") SELECT "id", "choice_text", "score", NULL FROM "pageone_choice__old";
DROP TABLE "pageone_choice__old";
CREATE INDEX "pageone_choice_question_id_b8c7a7bf" ON "pageone_choice" ("question_id");
COMMIT;


C:\Users\user\Documents\cleverkuma>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, pageone, sessions
Running migrations:
  Applying pageone.0001_initial... OK

C:\Users\user\Documents\cleverkuma>python manage.py shell   #เรียกใช้ API
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

>>> from pageone.models import Choice, Question      #import Choice, Question 
>>> Question.objects.all()                                               #เรียกดู object ทั้งหมดที่มีอยู่ใน Question
<QuerySet []>                                                                  #ใน set ยังไม่มีข้อมูล
>>> from django.utils import timezone
>>> q = Question(question_text="What's up?", pub_date=timezone.now())   #create new object
>>> q.save()                                                                     #บันทึก
>>> q.id                                                                            #เรียกดูลำดับที่
1
>>> q.question_text                                                          #ดูข้อมูลใน field ที่ชื่อว่า question_text 
"What's up?"
>>> q.pub_date
datetime.datetime(2019, 1, 12, 16, 57, 21, 106777, tzinfo=<UTC>)
>>> q.question_text = "What's up?"
>>> q.save()
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>

>>> q = Question(question_text="What's new?", pub_date=timezone.now())  #เพิ่มคำถามที่ 3
>>> q.save()
>>> q.id
3
>>> Question.objects.filter(id=1)                                                  #ดูคำถามแรก
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')   #ดูคำถามที่ขึ้นด้วย What
<QuerySet [<Question: What's up?>, <Question: What's new?>]>
>>> q.choice_set.all()                                                                    #ดูตัวเลือกทั้งหมด 
<QuerySet []>                                                                                #แสดงเป็น set ว่าง
>>> q.choice_set.create(choice_text='Not much', score=0)          #เพิ่มตัวเลือก
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', score=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', score=0)
>>> q.choice_set.all()                                                                     #ดูตัวเลือกทั้งหมด 
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()                                                                #นับตัวเลือกทั้งหมด
3


--------------------------------------------------------------------
models.py


from django.db import models
from django.utils import timezone

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

def __str__(self):
return self.question_text

def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
score = models.IntegerField(default=0)

def __str__(self):
return self.choice_text

------------------------------------------------------------------
จะเห็นได้ว่า การใช้ API ผ่าน command จะทำให้เราเห็นการทำงานและมีความเข้าใจการทำงานของการจัดการ model แต่การใช้ admin จะเพิ่มความสะดวกให้กับเรา

สามารถศึกษาเพิ่มเติมได้ที่ https://docs.djangoproject.com/en/2.1/intro/tutorial02/

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

[Django] models

models

- ประกอบไปด้วย database table ในรูปแบบของ class ในภาษา Python โดยผู้ใช้จะสามารถใช้ในการสร้าง, เรียกดูข้อมูล,อัพเดตข้อมูล, และ ลบข้อมูลที่อยู่ใน database โดยสามารถใช้งานผ่าน Python code ที่ใช้งานได้ง่าย
- เป็นการเชื่อมต่อกับฐานข้อมูลเพื่อจัดการการจัดเก็บข้อมูล
- มีการระบุ Field เช่น
     CharField ข้อมูลเป็นตัวอักษร
     DateTimeField ข้อมูลเป็นวันที่

ทดลองใช้งาน
1.สร้าง class ใน models.py


from django.db import models
class Poll(models.Model):
       question_text = models.CharField(max_length=200)
       pub_date = models.DateTimeField('date published')

class Choice(models.Model):
       question = models.ForeignKey(Poll)
       choice_text = models.CharField(max_length=200)



       votes = models.IntegerField(default=0)

-------------
models.Model     เรียกใช้ความสามารถของ models.Model
question_text = models.CharField    สร้างเขตข้อมูลที่ชื่อว่า question_text ในรูปแบบของเขตข้อมูลที่เป็นตัวอักษร
max_length=200     มีความยาวไม่เกิน 200 ตัวอักษร
question = models.ForeignKey(Poll)    บอกว่า choice ที่สร้างขึ้นเป็นของ Poll ไหน
-------------

2. แก้ไข settings.py

INSTALLED_APPS = [
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'hello.apps.HelloConfig',
     ]

เพิ่ม app ของเราลงไปในส่วน INSTALLED_APPS เพื่อเป็นการบอกให้โปรเจครู้จัก app

3. เปิด command และ run คำสั่งเพื่อให้ class ที่สร้างขึ้นถูกเรียกใช้งาน

Run >> python manage.py makemigrations
  บอก Django ว่ามีการเปลี่ยนแปลงใน models
Run >> python manage.py migrate
ทำให้ฐานข้อมูลเกิดการเปลี่ยนแปลง

4. ทดสอบการทำงานผ่าน command

Run >>  python manage.py shell
  เป็นการใช้ API ออกคำสั่งกับ Django ให้ทำการติดต่อกับ database
Run >>  from polls.models import Poll, Choice 
  เป็นการเรียกใช้ class Poll,Choice
Run >>  Poll.objects.all()
  เรียกค่าที่อยู่ใน objects ของ Poll ในตอนแรกจะไม่แสดงค่าใดๆ เนื่องจากยังไม่มีการใส่ข้อมูลลงไป

ทดลองทำการใส่ค่าลงไป
            from django.utils import timezone                    # import timezone
            p = Poll(question="What’s new?", pub_date=timezone.now())   #ทำการ set ค่า question และ pub_date ใน class Poll
            p.save()                                                              #จัดเก็บค่า p
            p.id                                                                     #คำสั่งแสดงค่า id ของ p                  
            p.question                                                          #แสดงค่า question ที่ได้ทำการ set                                  p.pub_date                                                         #แสดง pub_date ที่ได้ทำการ set               
            p.question = "What’s up?"                                #เปลี่ยนค่า question
            p.save()                                                             #บันทึกข้อมูล

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

[Django] template

Template

-การออกแบบหน้าต่างเว็บไซต์ด้วย HTML หรือ Javascript แล้วนำมาใช้งาน
-เป็นการทำงานในส่วนการ design ไม่เกี่ยวข้องกับ logic
-เรียกใช้งานผ่านไฟล์ views.py
-แก้ไข ส่วน DIRS ของ TEMPLATES ใน setting.py


การใช้งาน template
1.สร้างไฟล์ html ชื่อว่า hello.html


<!DOCTYPE html>
<html>

  <head>
     <meta charset="utf-8">
     <title>Django</title>
  </head>

  <body>
     <h1>Hello world</h1>
     <h2>Welcome to my world</h2>
  </body>

</html>


2.ระบุตำแหน่งที่อยู่ของไฟล์ในส่วน TEMPLATES ที่อยู่ในไฟล์ settings.py เพื่อเป็นการบอกกับ Django ว่าเราเสร้าง template ไว้ที่ใด

hello.html อยู่ในโฟลเดอร์ template ภายใน app hello

3. การนำมาใช้งาน

กรณีที่เราไม่ได้ใช้งาน template ที่สร้างไว้จะมีการสั่งให้แสดงโดยตรง

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):

return HttpResponse("<h1>Hello World</h1>")

แต่ในกรณีที่มีการใช้งาน template จะต้องทำการโหลดไฟล์เข้ามาก่อน ซึ่งการโหลดไฟล์ทำได้หลายวิธี เช่น
get_template(template_name)
  โหลดมาใช้งาน 1 template
select_template(template_name_list)
  โหลดมาใช้งานหลายๆ template
Template.render(context=None, request=None)
  มีการเก็บข้อมูลเป็นแบบ dictionary และในการใช้งานจะต้องเรียก context และ request
(context หมายถึง dictionary ที่มี key เป็น ชื่อตัวแปร และ value เป็น ค่าของตัวแปรนั้นๆ ที่จะนำมาใช้งาน )

from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
# Create your views here.
def index(request):
template = loader.get_template("hello.html")



return HttpResponse(template.render())

การแสดงผลจากการใช้งาน template

ทดลองใช้งาน Tag ในไฟล์ html
          ทดลองแก้ไขส่วน body ในไฟล์ html

<body>
<h1>Hello everybody</h1>
<h2>welcome to my world</h2>
<hr>
<h2>name : {{name}}</h2>
<h2>Age : {{age}}</h2>
{% if age <= 15%}
<h3>Group : younger</h3>
{% elif age <= 30%}
<h3>Group : adult</h3>
{%else%}
<h3>Group : Older</h3>
{%endif%}
</body>

          ใช้ {{name}} ให้รับค่าจากตัวแปร name มาแทนค่าลงในตำแหน่ง
           ใช้ {% if age <= 15%} เพื่อเป็นการทดสอบเงื่อนไข เมื่อเข้าเงื่อนไขใดให้ทำตามคำสั่งนั้นๆ

ไฟล์ one.html
<! DOCTYPE html>
<html>

    <head>
<meta charset="UTF-8">
<title>Django</title>
<style media="screen">
      body{
            background-color:rgb(192, 237, 255)
            }
         </style>
    </head>

    <body>
<h1>Hello everybody</h1>
<h2>welcome to my world</h2>
<hr>
<h2>name : {{name}}</h2>
<h2>Age : {{age}}</h2>
{% if age <= 15%}
<h3>Group : younger</h3>
{% elif age <= 30%}
<h3>Group : adult</h3>
{%else%}
<h3>Group : Older</h3>
{%endif%}
     </body>




</html>

--------------------------------------------------------------------
def profile(request):
template1 = loader.get_template("one.html")
info = {
'name':"iceiceice",
'age':19,
}
return HttpResponse(template1.render(info,request))



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

[Django] views & urls




     urls 

คือ ไฟล์การตั้งค่าลิงค์(การเรียกใช้งาน)ของเว็บเพจใน Django โดยตรวจสอบจาก Regular Expression (^$)ของ url ที่อยู่ใน urlpatterns ที่นำมาใช้ match กับ URL ที่ผู้ใช้กรอกมาใน Web Browser


( url ที่กำหนดไว้ )


( url ที่ผู้ใช้งานกรอกลง web browser)


     views

คือ ไฟล์ที่กำหนดการแสดงผลลัพธ์บน webpage คอยควบคุมสิ่งที่รับมาจาก client web browser และควบคุมสิ่งที่จะตอบกลับไป เมื่อมีการร้องขอเข้ามา


ทดสอบการทำงาน

- สร้าง app hello
                 

แก้ไขหน้า views.py เป็น

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
       return HttpResponse("<h1>Hello World</h1>")  # return hello world to webpage

แก้ไขหน้า urls.py เป็น

from django.conf.urls import url
from . import views

urlpatterns = [
      url(r'^$',views.index),  #urls of app hello call to function index of views.py

      ]

และในส่วนของโปรเจค mysite  แก้ไขหน้า urls.py ดังนี้


from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
       url(r'^admin/', admin.site.urls),
       url(r'^hello/$', include("hello.urls")),  #when call url/hello  it will call to hello.urls
       ]

เมื่อ runserver และ open web จะได้ผลลัพธ์ดังนี้



         ทดลองทำการเพิ่ม function ใน hello.views

from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse


def one(request): #function 1
return HttpResponse("Hello every one")


def two(request): #function 2
return HttpResponse("one two three")


แก้ไข urls.py ใน app hello

from django.conf.urls import url
from . import views


urlpatterns = [
url(r'greeting/',views.one), # return Hello every one
url(r'contact/',views.two) # return one two three


]
และเมื่อเรียกใช้งานจะได้ผลลัพธ์ดังนี้

เรียกผ่าน /greeting
เรียกผ่าน /contact

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

Django

Django คือ Web Framework ที่ใช้ภาษา Python เพื่อเป็นตัวช่วยในการทำ Web Application โดยมีเครื่องมือช่วยในการจัดการที่หลากหลาย สามารถปรับขนาดได้ และ มีความปลอดภัยในการใช้งาน


การติดตั้ง Django
ติดตั้งด้วยคำสั่ง python -m pip install django

การสร้างโปรเจค

>>Open Command
>>django-admin startproject mysite
>>cd mysite
>>python manage.py runserver
>>open link http://127.0.0.1:8000/

จะได้หน้าเว็บดังภาพ ซึ่งแสดงว่าทำการติดตั้งสำเร็จแล้ว

จากนั้นก็จะสามารถทำการสร้าง app ใหม่ลงในโปรเจคได้ด้วยคำสั่ง

     py manage.py startapp ชื่อแอพลิเคชั่น

ก็จะได้โฟลเดอร์ใหม่มาอยู่ในโปรเจคของเรา โดยที่ใน 1 โปรเจคนั้นจะสร้างกี่แอพก็ได้ โดยข้อดีของแอพก็คือเมื่อสร้างแล้วสามารถคัดลอกโฟลเดอร์ไปใช้งานต่อในโปรเจคอื่นได้เลย

ทดลองสร้าง app ชื่อ hello 
>> py manage.py startapp hello

เพิ่ม url ให้ app hello
- สร้างไฟล์ urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
url(r'^$',views.index),
]
      
- แก้ไขไฟล์ urls ใน project

from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^hello/', include("hello.urls")),
]

เราก็จะได้หน้า app hello ที่ต้องเรียกด้วย url/hello/

แก้ไขไฟล์ views
เพื่อให้ทำการแสดงหน้าต่างที่ต้องการ โดยการเพิ่มคำสั่งในไฟล์ views.py ใน app hello ให้ทำการคืนค่าหน้าที่แสดงตัวอักษร ดังนี้

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("<h1>Hello World</h1>")

ซึ่งเมื่อเรา run http://127.0.0.1:8000/hello/ จะได้ผลลัพธ์ดังนี้

แต่ถ้าหากว่าเรารันด้วย http://127.0.0.1:8000/ จะได้ผลลัพธ์

เนื่องจากไม่ได้มีการกำหนด url ไว้ว่าค่าเริ่มต้นให้แสดงผลลัพธ์แบบใด ซึ่งสามารถกำหนดได้โดยการกำหนดใน urls.py ของโปรเจคให้เป็นดังนี้

urlpatterns = [
path(r'admin/', admin.site.urls),
url(r'^$',include("hello.urls")),
]

จะเห็นได้ว่า เปลี่ยน url ที่เรียกไปยัง hello.urls จาก url(r'^hello/', include("hello.urls")) เป็น url(r'^$',include("hello.urls"))
เมื่อเปิดหน้าเว็บอีกครั้งผลลัพธ์จะเป็นดังนี้