Table of Contents

Model

ctrl/models.py

from django.db import models
 
class Equipment(models.Model):
    name = models.CharField(max_length=100)
    is_on = models.BooleanField()
 
    def __unicode__(self):
        return self.name
 
    def toggle(self):
        self.is_on = not self.is_on
 
class ToggleLog(models.Model):
    equipment = models.ForeignKey(Equipment)
    toggled_at = models.DateTimeField(auto_now=True)
 
    def __unicode__(self):
        return str(self.toggled_at)

Views

ctrl/views.py

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from models import Equipment, ToggleLog
 
def index(request):
    eqs = Equipment.objects.all()
    return render_to_response('ctrl/index.html',
                              { 'eqs': eqs })
 
def toggle(request,eq_id):
    eq = Equipment.objects.get(pk=eq_id)
    eq.toggle()
    eq.save()
 
    log = ToggleLog()
    log.equipment = eq
    log.save()
 
    return HttpResponseRedirect('/')

Template

templates/ctrl/index.html

<html>
<head>
 
<style type="text/css">
h1 {
  background: green;
  color: white;
  text-align: center;
  -moz-border-radius: 5px;
  border-radius: 5px;
}
li { margin: 10px; color: black; text-align: center; }
li.on { background: #a0ffa0; }
li.off { background: #ffa0a0; }
</style>
 
</head>
<body>
<h1>My Smart Home</h1>
<ul>
  {% for e in eqs %}
    <li class="{% if e.is_on %}on{% else %}off{% endif %}">
      {{ e.name }}:
      {% if e.is_on %}
        เปิด
      {% else %}
        ปิด
      {% endif %}
      [<a href="/toggle/{{ e.id }}/">toggle</a>]<br/>
 
      <ul>
      {% for l in e.togglelog_set.all %}
        <li>{{ l }}</li>
      {% endfor %}
      </ul>
    </li>
  {% endfor %}
</ul>
</body>
</html>
204223-52/การเชื่อมโยงระหว่างโมเดล.txt · Last modified: 2009/08/24 05:05 by jittat
 
 
©2008 Another cool website by 80KV