Django Tutorial Part 1 : Django app

Django App

หลังจากที่เราทำการติดตั้ง และสร้างโปรเจค Django แล้ว ใน Tutorial part 1 นี้เราจะมาเรียนรู้วิธีการสร้าง Django App  และคำสั่งพื้นฐานของการสร้าง  Django App 

-  Set Time Zone

ทำได้โดยการเข้าไปแก้ไข Time zone ในไฟล์ setting.py  ของโปรเจค โดยเปลี่ยน TIME_ZONE เป็น Asia/Bangkok
   TIME_ZONE   =  ‘Asia/Bangkok’
การสร้าง  Django App
-  ไปยัง Directory ของ Project ที่เราสร้างไว้  ( เราจะสร้าง app ไว้ที่เดียวกับไฟล์ manage.py )
-  ใช้คำสั่ง  python manage.py syncdb  แล้วใส่ superuser username, e-mail และ password
-  เริ่ม start app โดยใช้คำสั่ง  python manage.py startapp polls
   จะพบว่ามีโฟล์เดอร์  Polls  เพิ่มเข้ามาใน  directory  ของโปรเจคและจะประกอบไปด้วยไฟล์ดังนี้
                    

-  แก้ไขไฟล์  model.py  ของ Polls  ให้เป็นดังต่อไปนี้

     from django.db import models
     class Poll(models.Model):
            question = models.CharField(max_length=200)
            pub_date = models.DateTimeField(’date published’)
     class Choice(models.Model):
            poll = models.ForeignKey(Poll)
            choice_text = models.CharField(max_length=200) 
            votes = models.IntegerField(default=0) 

      ทำการสร้าง class ขึ้นมา 2 class ได้แก่ class Poll และ class Choice 
      โดยแต่ละ class จะทำการเก็บค่าเป็นตาราง

-  ทำการเพิ่ม 'polls',  เข้าไปยัง INSTALLED_APPS ในไฟร์ settings.py 


-  ทำการ syncdb ด้วยคำสั่ง  python manage.py syncdb

-  ทดลองการใช้งานร่วมกับ API  โดยต้องเปิดการใช้งาน shell  ด้วยคำสั่ง  python manage.py shell  แล้วพิมพ์คำสั่งต่อไปนี้ 



หลังจากทดลองใช้คำสั่ง Poll.objects.all()  แล้ว จะได้ output ออกมาเป็น  [< Poll : Poll object >]
ซึ่งไม่สามารถดึงค่าที่อยู่ใน Object ออกมาได้  ดังนั้นจึงต้องทำการแก้ไขไฟล์ models.py ให้เป็นดังนี้

       from django.db import models
      class Poll(models.Model): # ...
             def __unicode__(self): # Python 3: def __str__(self): return self.question

      class Choice(models.Model): # ...
             def __unicode__(self): # Python 3: def __str__(self): return self.choice_text 

จากนั้นใช้คำสั่ง Poll.objects.all() อีกครั้ง  จะได้ผลเป็น [<Poll: What’s up?>] คือค่าที่ดึงค่าออกมา 


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


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

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