Added network edition (easy also.... :-) )

This commit is contained in:
Adolfo Gómez 2013-12-12 07:23:22 +00:00
parent 895ef25b77
commit dbc001ea22
5 changed files with 47 additions and 9 deletions

View File

@ -32,10 +32,11 @@
'''
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext_lazy as _, ugettext
from uds.models import Network
from uds.core.util import net
from uds.REST.model import ModelHandler
from uds.REST.model import ModelHandler, SaveException
import logging
@ -45,17 +46,39 @@ logger = logging.getLogger(__name__)
class Networks(ModelHandler):
model = Network
save_fields = ['name', 'net_string']
table_title = _('Current Networks')
table_fields = [
{ 'name': {'title': _('Name'), 'visible': True, 'type': 'icon', 'icon': 'fa fa-globe text-success' } },
{ 'net_string': {'title': _('Networks')}},
{ 'net_string': {'title': _('Range')}},
{ 'networks_count': {'title': _('Used by'), 'type': 'numeric', 'width': '8em'}}
]
def beforeSave(self, fields):
logger.debug('Before {0}'.format(fields))
try:
nr = net.networksFromString(fields['net_string'], False)
fields['net_start'] = nr[0]
fields['net_end'] = nr[1]
except Exception as e:
raise SaveException(ugettext('Invalid network: ') + unicode(e))
logger.debug('Processed {0}'.format(fields))
def getGui(self, type_):
return self.addField(self.addDefaultFields([], ['name']),{
'name': 'net_string',
'value': True,
'label': ugettext('Network range'),
'tooltip': ugettext('Network range. Accepts most network definitions formats (range, subnet, host, etc...'),
'type': 'text',
'order': 100, # At end
})
def item_as_dict(self, item):
return { 'id': item.id,
'name': item.name,
'net_string': item.net_string,
'networks_count': item.transports.count(),
}

View File

@ -50,6 +50,10 @@ TABLEINFO = 'tableinfo'
GUI = 'gui'
LOG = 'log'
# Exception to "rethrow" on save error
class SaveException(Exception):
pass
# Base for Gui Related mixins
class BaseModelHandler(Handler):
@ -328,7 +332,7 @@ class ModelHandler(BaseModelHandler):
table_fields = []
table_title = ''
# This method must be override, depending on what is provided
# This methods must be override, depending on what is provided
# Data related
def item_as_dict(self, item):
@ -374,6 +378,10 @@ class ModelHandler(BaseModelHandler):
def checkSave(self, item):
pass
# Invoked to possibily fix fields (or add new one, or check
def beforeSave(self, fields):
pass
# Invoked right after saved an item (no matter if new or edition)
def afterSave(self, item):
pass
@ -422,6 +430,8 @@ class ModelHandler(BaseModelHandler):
return list(self.getTypes())
elif self._args[0] == TABLEINFO:
return self.processTableFields(self.table_title, self.table_fields)
elif self._args[0] == GUI:
return self.getGui(None)
# get item ID
try:
@ -485,6 +495,7 @@ class ModelHandler(BaseModelHandler):
try:
# Extract fields
args = self.readFieldsFromParams(self.save_fields)
self.beforeSave(args)
deleteOnError = False
if len(self._args) == 0: # create new
item = self.model.objects.create(**args)
@ -497,6 +508,8 @@ class ModelHandler(BaseModelHandler):
raise NotFound('Item not found')
except IntegrityError: # Duplicate key probably
raise RequestError('Element already exists (duplicate key error)')
except SaveException as e:
raise RequestError(unicode(e))
except Exception:
raise RequestError('incorrect invocation to PUT')

View File

@ -73,7 +73,7 @@
success_fnc = success_fnc || function(){};
api.doLog('Getting template ' + name);
if (name.indexOf('?') == -1) {
if ($this.cache.get(name) ) {
if ($this.cache.get(name+'------') ) {
success_fnc($this.cache.get(name));
return;
// Let's check if a "preloaded template" exists
@ -105,7 +105,7 @@
// Simple JavaScript Templating, using HandleBars
api.templates.evaluate = function(str, context) {
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
// load the template - and be sure to cache the result (compiled template).
var cached;
if( !/\W/.test(str) ) {
cached = this.cache.get('_'+str);

View File

@ -26,9 +26,12 @@ gui.connectivity.link = function(event) {
onDelete: gui.methods.del(gui.connectivity.transports, gettext('Delete transport'), gettext('Error deleting transport')),
});
gui.connectivity.networks.table({
rowSelect : 'multi',
rowSelect : 'single',
container : 'networks-placeholder',
buttons : [ 'new', 'edit', 'delete', 'xls' ],
onNew : gui.methods.typedNew(gui.connectivity.networks, gettext('New network'), gettext('Error creating network')),
onEdit: gui.methods.typedEdit(gui.connectivity.networks, gettext('Edit network'), gettext('Error processing network')),
onDelete: gui.methods.del(gui.connectivity.networks, gettext('Delete network'), gettext('Error deleting network')),
});
});

View File

@ -320,13 +320,12 @@
};
gui.methods.del = function(parent, modalTitle, modalErrorMsg) {
var self = parent;
return function(value, event, table, refreshFnc) {
var content = gettext('Are you sure do you want to delete ') + '<b>' + value.name + '</b>';
var modalId = gui.launchModal(modalTitle, content, { actionButton: '<button type="button" class="btn btn-danger button-accept">' + gettext('Delete') + '</button>'});
$(modalId + ' .button-accept').click(function(){
$(modalId).modal('hide');
self.rest.del(value.id, function(){
parent.rest.del(value.id, function(){
refreshFnc();
gui.notify(gettext('Item deleted'), 'success');
}, gui.failRequestModalFnc(modalErrorMsg) );