====== 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''**
My Smart Home
{% for e in eqs %}
-
{{ e.name }}:
{% if e.is_on %}
เปิด
{% else %}
ปิด
{% endif %}
[toggle]
{% for l in e.togglelog_set.all %}
- {{ l }}
{% endfor %}
{% endfor %}