วันเสาร์ที่ 2 มีนาคม พ.ศ. 2562

django==1.10 ตอน 2

การสร้าง Model

แก้ไขไฟล์ models.py ที่ Application
from django.db import models

# Create your models here.
class Topic(models.Model):
   top_name = models.CharField(max_length=264, unique=True)

   def __str__(self):
      return self.top_name

class Webpage(models.Model):
   topic = models.ForeignKey(Topic)
   name = models.CharField(max_length=264, unique=True)
   url = models.URLField(unique=True)

   def __str__(self):
      return self.name

class AccessRecord(models.Model):
   name = models.ForeignKey(Webpage)
   date = models.DateField()

   def __str__(self):
      return str(self.date)

# return value on admin interface

เสร็จแล้วสั่ง migrate และ makemigrations และ migrate อีกรอบ
python manage.py migrate
python manage.py makemigrations first_app
python manage.py migrate

ทดสอบ Model โดยการใช้ Python Shell
python manage.py shell
from first_app.models import Topic
print(Topic.objects.all())
t = Topic(top_name="Social Network")
t.save()

print(Topic.objects.all())
quit()



การใช้งาน Admin Interface ของ django 1.10
แก้ไขไฟล์ admin ที่ Application
from django.contrib import admin
from first_app.models import AccessRecord, Topic, Webpage

# Register your models here.
admin.site.register(AccessRecord)
admin.site.register(Topic)
admin.site.register(Webpage)
python manager.py createsuperuser
python manager.py runserver
#http://localhost:8000/admin



การเรียกขึ้นมาใช้ใน Template (Model Template View)

แก้ไขไฟล์ urls.py เพื่อเพิ่ม url และแก้ไขไฟล์ views.py โดยจะดึงค่าจากไฟล์นี้
...
urlpatterns = [
   ...
   url(r'^model', views.model, name='model')
]
...
from first_app.models import AccessRecord, Topic, Webpage

...
def model(request):
   webpages_list = AccessREcord.objects.order_by('date')
   data_dict = {'access_records': webpage_list}

   return render(request, 'first_app/model.html', context=data_dict)
...
   <div class="django">
      {% if access_records %}
         <table>
            <thead>
               <th>Site Name</th>
               <th>Date Accessed</th>
            </thead>
            <tbody>
               {% for acc in access_records %}
                  <tr>
                     <td>{{ acc.name }}</td>
                     <td>{{ acc.date }}</td>
                  </tr>
               {% endfor %}  
            </tbody>
         </table>
      {% else %}
         <p>No Access Records Found!</p>
      {% endif %}
   </div>
...

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

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