Save sensor data in a Django database

Im doing a Django app that tries to show data taken from an ultrasonic sensor.

What I want is to take the distance from the sensor and save it in its Django table. Normally this is done with a form, but i want it to be done in the backend for each sensor object.

This is the code that i have for the moment:

Ultrasonicsensor.py

import time
from grove.grove_ultrasonic_ranger import GroveUltrasonicRanger

def main():
# Grove - Ultrasonic Ranger connected to port D16
sensor = GroveUltrasonicRanger(16)
counter = 10

while (counter < 10):
  distance = sensor.get_distance() #This is the distance i want to save for each sensor object
  distance = (float(distance) / 100) 
  print('{:.4f} m'.format(distance))
  if distance < 1:
    print('Cerca')
  elif 1 <= distance <= 1.9:
    print('Medio')
  else:
    print('Lejos')
  time.sleep(1)
  counter = counter + 1

Models.py

class UltrasonicSensor(models.Model):

  name = models.CharField(max_length=50, default="HC-SR04")
  description = models.TextField()
  pin = models.IntegerField()
  distance = models.DecimalField(max_digits=20, decimal_places=4)
  date = models.DateTimeField(auto_now_add=True)

Views.py

class uSensorDetailView(DetailView):
  template_name = 'sensor_detail.html'
  context_object_name = 'sensor'

def get_queryset(self):
    return UltrasonicSensor.objects.all()

You could try importing the model into your Ultrasonicsensor.py file, if the Python file is part of your Django Project.

from app_name.models import UltrasonicSensor

And then creating your object for each Sensor as it comes in.

new_sensor = UltrasonicSensor()
new_sensor.name = data_here
new_sensor.description = data_here
new_sensor.pin = data_here
new_sensor.distance = data_here

And then save the Object.

new_sensor.save()

Your new Sensor Object has been created!

Back to Top