def index(request):
sensors = Sensor.objects.all()
return render(request,
'tempindex.html',
{'sensors': sensors})
def show_temperatures(request, sensor=0):
temperatures = Reading.objects.filter \
(sensor_id = sensor).order_by('-time')
return render(request,
'tempreadings.html',
{'temperatures': temperatures})
The first is the index page which will just list our sensors, and the second is the page that will show the readings for a sensor based on the id passed in as a parameter. We'll return the readings in reverse order to get the most recent first.urlpatterns = [
url(r'^temperature/api/record/$',
views.record_temperature,
name='temperature_record'),
url(r'^temperature/$',
views.index, name='temperature'),
url(r'^temperature/(?P[0-9]+)/$',
views.show_temperatures,
name='show_temperatures')
]
The first pattern was the one we created to receive data.{% extends "tempbase.html" %}
{% block contents %}
<ul>
{% for sensor in sensors %}
<li>
<a href="{% url 'temperature:show_temperatures'sensor.id %}">
{{ sensor.name }}</a>
</li>
{% endfor %}
</ul>
{% endblock %}
tempreadings.html shows a table of readings for an individual sensor:{% extends "tempbase.html" %}
{% block contents %}
<table>
<thead>
<tr>
<th>Sensor</th>
<th>Time</th>
<th>Temperature</th>
<tr>
</thead>
<tbody>
<tr>
{% for temperature in temperatures %}
<tr>
<td>{{ temperature.sensor.name }}</td>
<td>{{ temperature.time }}</td>
<td>{{ temperature.value }}</td>
{% endfor %}
</tr>
</tbody>
</table>
{% endblock %}
Both are extending tempbase.html. This is where we'll start and end the page and later on add links to stylesheets. For now, let's keep it minimal:<html>
<body>
{% block contents %}{% endblock %}
</body>
</html>
All it defines is the contents block that we fill in through our individual page templates above.<html> <body> <ul> <li> <a href="/temperature/2/">Front Door</a> </li> <li> <a href="/temperature/5/">Bedroom</a> </li> <li> <a href="/temperature/6/">Back Door</a> </li> <li> <a href="/temperature/7/">Test</a> </li> </ul> </body> </html>If we click on a sensor, we get the readings:
Labels: Django, Home Server, SmartThings