Add validation to transductor fields in new/edit methods and refactored transductor model

parent d96289ce
...@@ -14,8 +14,7 @@ copies or substantial portions of the Software. ...@@ -14,8 +14,7 @@ copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
SOFTWARE.
from django.contrib import admin from django.contrib import admin
from .models import Transductor, TransductorManager
class TransductorInLine(admin.StackedInline):
model = Transductor
extra = 0
class TransductorManagerAdmin(admin.ModelAdmin):
fieldset = [
(None, {'fields': ['description']}),
]
inlines = [TransductorInLine]
admin.site.register(TransductorManager, TransductorManagerAdmin)
from django import forms from django import forms
from .models import EnergyTransductor
from .models import Transductor
class EnergyForm(forms.ModelForm):
class PostForm(forms.ModelForm):
class Meta: class Meta:
model = Transductor model = EnergyTransductor
fields = ('serie_number', 'ip_address', 'description',) fields = ('serie_number', 'ip_address', 'description',)
from __future__ import unicode_literals from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.db.models.signals import post_save from django.db.models.signals import post_save
from django.dispatch import receiver from django.dispatch import receiver
from django.db import models from django.db import models
...@@ -10,24 +11,33 @@ import sys ...@@ -10,24 +11,33 @@ import sys
import thread import thread
class TransductorManager(models.Model):
description = models.CharField(max_length=150)
def __str__(self):
return self.description
class Transductor(models.Model): class Transductor(models.Model):
transductor_manager = models.ForeignKey(TransductorManager)
serie_number = models.IntegerField(default=None) serie_number = models.IntegerField(default=None)
ip_address = models.CharField(max_length=15) ip_address = models.CharField(max_length=15)
description = models.TextField(max_length=150) description = models.TextField(max_length=150)
creation_date = models.DateTimeField('date published') creation_date = models.DateTimeField('date published')
data_collection = models.BooleanField(default=False) data_collection = models.BooleanField(default=False)
class Meta:
abstract = True
class EnergyTransductor(Transductor):
def __str__(self): def __str__(self):
return self.description return self.description
def validate_unique_ip_address(self, exclude=None):
energy_transductors = EnergyTransductor.objects.filter(ip_address=self.ip_address)
if energy_transductors.filter(ip_address=self.ip_address).exists():
raise ValidationError('Ip address must be unique per Energy Transductor')
def save(self, *args, **kwargs):
self.validate_unique_ip_address()
super(EnergyTransductor, self).save(*args, **kwargs)
class Observer(): class Observer():
_observers = [] _observers = []
...@@ -45,12 +55,12 @@ class VoltageObserver(Observer): ...@@ -45,12 +55,12 @@ class VoltageObserver(Observer):
Observer.__init__(self) Observer.__init__(self)
def verify_voltage(self, voltage): def verify_voltage(self, voltage):
low_voltage = False high_voltage = False
if voltage < 220.0: if voltage > 230.0:
low_voltage = True high_voltage = True
return low_voltage return high_voltage
class Event(): class Event():
...@@ -67,7 +77,7 @@ class Event(): ...@@ -67,7 +77,7 @@ class Event():
class CommunicationProtocol(models.Model): class CommunicationProtocol(models.Model):
transductor = models.ForeignKey(Transductor) transductor = models.ForeignKey(EnergyTransductor)
protocol_type = models.CharField(max_length=50) protocol_type = models.CharField(max_length=50)
port = models.IntegerField(default=1001) port = models.IntegerField(default=1001)
timeout = models.FloatField(default=30.0) timeout = models.FloatField(default=30.0)
...@@ -128,21 +138,21 @@ class CommunicationProtocol(models.Model): ...@@ -128,21 +138,21 @@ class CommunicationProtocol(models.Model):
data.transductor = self.transductor data.transductor = self.transductor
data.voltage_a = float("{0:.3f}".format(self._get_float_value_from_response_message(messages[0]))) data.voltage_a = float("{0:.3f}".format(self._get_float_value_from_response(messages[0])))
data.voltage_b = float("{0:.3f}".format(self._get_float_value_from_response_message(messages[1]))) data.voltage_b = float("{0:.3f}".format(self._get_float_value_from_response(messages[1])))
data.voltage_c = float("{0:.3f}".format(self._get_float_value_from_response_message(messages[2]))) data.voltage_c = float("{0:.3f}".format(self._get_float_value_from_response(messages[2])))
data.current_a = float("{0:.3f}".format(self._get_float_value_from_response_message(messages[3]))) data.current_a = float("{0:.3f}".format(self._get_float_value_from_response(messages[3])))
data.current_b = float("{0:.3f}".format(self._get_float_value_from_response_message(messages[4]))) data.current_b = float("{0:.3f}".format(self._get_float_value_from_response(messages[4])))
data.current_c = float("{0:.3f}".format(self._get_float_value_from_response_message(messages[5]))) data.current_c = float("{0:.3f}".format(self._get_float_value_from_response(messages[5])))
data.active_power_a = float("{0:.3f}".format(self._get_float_value_from_response_message(messages[6]))) data.active_power_a = float("{0:.3f}".format(self._get_float_value_from_response(messages[6])))
data.active_power_b = float("{0:.3f}".format(self._get_float_value_from_response_message(messages[7]))) data.active_power_b = float("{0:.3f}".format(self._get_float_value_from_response(messages[7])))
data.active_power_c = float("{0:.3f}".format(self._get_float_value_from_response_message(messages[8]))) data.active_power_c = float("{0:.3f}".format(self._get_float_value_from_response(messages[8])))
data.reactive_power_a = float("{0:.3f}".format(self._get_float_value_from_response_message(messages[9]))) data.reactive_power_a = float("{0:.3f}".format(self._get_float_value_from_response(messages[9])))
data.reactive_power_b = float("{0:.3f}".format(self._get_float_value_from_response_message(messages[10]))) data.reactive_power_b = float("{0:.3f}".format(self._get_float_value_from_response(messages[10])))
data.reactive_power_c = float("{0:.3f}".format(self._get_float_value_from_response_message(messages[11]))) data.reactive_power_c = float("{0:.3f}".format(self._get_float_value_from_response(messages[11])))
data.apparent_power_a = float("{0:.3f}".format(sqrt(data.active_power_a**2 + data.reactive_power_a**2))) data.apparent_power_a = float("{0:.3f}".format(sqrt(data.active_power_a**2 + data.reactive_power_a**2)))
data.apparent_power_b = float("{0:.3f}".format(sqrt(data.active_power_b**2 + data.reactive_power_b**2))) data.apparent_power_b = float("{0:.3f}".format(sqrt(data.active_power_b**2 + data.reactive_power_b**2)))
...@@ -152,7 +162,7 @@ class CommunicationProtocol(models.Model): ...@@ -152,7 +162,7 @@ class CommunicationProtocol(models.Model):
data.save() data.save()
def _get_float_value_from_response_message(self, message_received_data): def _get_float_value_from_response(self, message_received_data):
n_bytes = struct.unpack("1B", message_received_data[2])[0] n_bytes = struct.unpack("1B", message_received_data[2])[0]
msg = bytearray(message_received_data[3:-2]) msg = bytearray(message_received_data[3:-2])
...@@ -194,7 +204,15 @@ class CommunicationProtocol(models.Model): ...@@ -194,7 +204,15 @@ class CommunicationProtocol(models.Model):
class Measurements(models.Model): class Measurements(models.Model):
transductor = models.ForeignKey(Transductor, on_delete=models.CASCADE) collection_date = models.DateTimeField('date published')
class Meta:
abstract = True
class EnergyMeasurements(Measurements):
transductor = models.ForeignKey(EnergyTransductor, on_delete=models.CASCADE)
voltage_a = models.FloatField(default=None) voltage_a = models.FloatField(default=None)
voltage_b = models.FloatField(default=None) voltage_b = models.FloatField(default=None)
...@@ -216,8 +234,6 @@ class Measurements(models.Model): ...@@ -216,8 +234,6 @@ class Measurements(models.Model):
apparent_power_b = models.FloatField(default=None) apparent_power_b = models.FloatField(default=None)
apparent_power_c = models.FloatField(default=None) apparent_power_c = models.FloatField(default=None)
collection_date = models.DateTimeField('date published')
def __str__(self): def __str__(self):
return '%s' % self.collection_date return '%s' % self.collection_date
......
...@@ -5,20 +5,20 @@ ...@@ -5,20 +5,20 @@
{% endblock %} {% endblock %}
{% block body %} {% block body %}
<p><a href="{% url 'data_reader:new' %}" class="btn btn-primary">Create Transductor</a></p>
<div class="col-md-6"> <div class="col-md-6">
<table class="table table-striped"> <table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Description</th>
<th>IP Address</th>
<th>Serie Number</th>
<th>Options</th>
</tr>
</thead>
{% if transductors_list %} {% if transductors_list %}
<p><a href="{% url 'data_reader:new' %}" class="btn btn-primary">Create Transductor</a></p>
<thead>
<tr>
<th>#</th>
<th>Description</th>
<th>IP Address</th>
<th>Serie Number</th>
<th>Options</th>
</tr>
</thead>
{% for transductor in transductors_list %} {% for transductor in transductors_list %}
<tbody> <tbody>
<tr> <tr>
...@@ -37,7 +37,7 @@ ...@@ -37,7 +37,7 @@
<div class="container"> <div class="container">
<div class="starter-template"> <div class="starter-template">
<h1>No Registered Transducer</h1> <h1>No Registered Transducer</h1>
<p class="lead">To register a new transductor click here.</p> <p class="lead">To create a new transductor click <a href="{% url 'data_reader:new' %}" >here</a></p>
</div> </div>
</div> </div>
{% endif %} {% endif %}
......
...@@ -5,7 +5,12 @@ ...@@ -5,7 +5,12 @@
{% endblock %} {% endblock %}
{% block body %} {% block body %}
<h1>Edit Transductor</h1> <h1>New Transductor</h1>
{% if errors %}
<p style="color: #ff0000;">{{errors}}</p>
{% endif %}
<form method="post" class="post-form"> <form method="post" class="post-form">
{% csrf_token %} {% csrf_token %}
{{form.as_p}} {{form.as_p}}
......
from django.views import generic from django.views import generic
from .models import Transductor, TransductorManager from .models import EnergyTransductor
from django.shortcuts import get_object_or_404, render, redirect from django.shortcuts import get_object_or_404, render, redirect
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from django.core.exceptions import ValidationError
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from .forms import PostForm from .forms import EnergyForm
from django.utils import timezone from django.utils import timezone
...@@ -13,13 +14,16 @@ class IndexView(generic.ListView): ...@@ -13,13 +14,16 @@ class IndexView(generic.ListView):
context_object_name = 'transductors_list' context_object_name = 'transductors_list'
def get_queryset(self): def get_queryset(self):
return Transductor.objects.all() return EnergyTransductor.objects.all()
def detail(request, transductor_id): def detail(request, transductor_id):
template_name = 'data_reader/detail.html' template_name = 'data_reader/detail.html'
transductor = get_object_or_404(Transductor, pk=transductor_id) transductor = get_object_or_404(EnergyTransductor, pk=transductor_id)
data_list = Transductor.objects.get(id=transductor_id).measurements_set.all()
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# trocar por measurements
data_list = EnergyTransductor.objects.get(id=transductor_id).energymeasurements_set.all()
paginator = Paginator(data_list, 4) paginator = Paginator(data_list, 4)
page = request.GET.get('page') page = request.GET.get('page')
...@@ -35,39 +39,52 @@ def detail(request, transductor_id): ...@@ -35,39 +39,52 @@ def detail(request, transductor_id):
def new(request): def new(request):
if request.method == "POST": if request.POST:
form = PostForm(request.POST) form = EnergyForm(request.POST)
if form.is_valid(): if form.is_valid():
transductor = form.save(commit=False) transductor = EnergyTransductor()
transductor.serie_number = form.cleaned_data['serie_number']
transductor.ip_address = form.cleaned_data['ip_address']
transductor.description = form.cleaned_data['description']
transductor.creation_date = timezone.now() transductor.creation_date = timezone.now()
transductor.transductor_manager = TransductorManager.objects.all().first()
transductor.save()
# Fix communication protocol try:
# cp = CommunicationProtocol.all().first() transductor.save()
except ValidationError, err:
errors = '; '.join(err.messages)
return render(request, 'data_reader/new.html', {'form': form, 'errors': errors})
return redirect('data_reader:detail', transductor_id=transductor.id) return redirect('data_reader:detail', transductor_id=transductor.id)
else: else:
form = PostForm() form = EnergyForm()
return render(request, 'data_reader/new.html', {'form': form}) return render(request, 'data_reader/new.html', {'form': form})
def edit(request, pk): def edit(request, pk):
post = get_object_or_404(Transductor, pk=pk) transductor = get_object_or_404(EnergyTransductor, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance=post) if request.POST:
form = EnergyForm(request.POST, instance=transductor)
if form.is_valid(): if form.is_valid():
transductor = form.save(commit=False) edited_transductor = form.save(commit=False)
transductor.transductor_manager = TransductorManager.objects.all().first()
transductor.save() try:
return redirect('/data_reader') edited_transductor.save()
except ValidationError, err:
errors = '; '.join(err.messages)
return render(request, 'data_reader/new.html', {'form': form, 'errors': errors})
return redirect('data_reader:index')
else: else:
form = PostForm(instance=post) form = EnergyForm(instance=transductor)
return render(request, 'data_reader/new.html', {'form': form}) return render(request, 'data_reader/new.html', {'form': form})
def delete(request, pk): def delete(request, pk):
transductor = get_object_or_404(Transductor, pk=pk) transductor = get_object_or_404(EnergyTransductor, pk=pk)
transductor.delete() transductor.delete()
return HttpResponseRedirect(reverse('data_reader:index')) return HttpResponseRedirect(reverse('data_reader:index'))
...@@ -6,12 +6,12 @@ from djangoplugins.fields import PluginField ...@@ -6,12 +6,12 @@ from djangoplugins.fields import PluginField
from plugins.plugins import BasePlugin from plugins.plugins import BasePlugin
from data_reader.models import Transductor from data_reader.models import EnergyTransductor
class Report(models.Model): class Report(models.Model):
title = models.CharField(max_length=255) title = models.CharField(max_length=255)
transductor = models.ForeignKey(Transductor, on_delete=models.CASCADE) transductor = models.ForeignKey(EnergyTransductor, on_delete=models.CASCADE)
plugin = PluginField(BasePlugin, editable=False) plugin = PluginField(BasePlugin, editable=False)
......
...@@ -45,5 +45,5 @@ def content_read(request, pk, plugin): ...@@ -45,5 +45,5 @@ def content_read(request, pk, plugin):
return render(request, 'content/detail.html', { return render(request, 'content/detail.html', {
'plugin': plugin, 'plugin': plugin,
'content': content, 'content': content,
'data_list': content.transductor.measurements_set.all(), 'data_list': content.transductor.energymeasurements_set.all(),
}) })
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment