Source code for beat.web.databases.admin

#!/usr/bin/env python
# vim: set fileencoding=utf-8 :

###############################################################################
#                                                                             #
# Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/           #
# Contact: beat.support@idiap.ch                                              #
#                                                                             #
# This file is part of the beat.web module of the BEAT platform.              #
#                                                                             #
# Commercial License Usage                                                    #
# Licensees holding valid commercial BEAT licenses may use this file in       #
# accordance with the terms contained in a written agreement between you      #
# and Idiap. For further information contact tto@idiap.ch                     #
#                                                                             #
# Alternatively, this file may be used under the terms of the GNU Affero      #
# Public License version 3 as published by the Free Software and appearing    #
# in the file LICENSE.AGPL included in the packaging of this file.            #
# The BEAT platform is distributed in the hope that it will be useful, but    #
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY  #
# or FITNESS FOR A PARTICULAR PURPOSE.                                        #
#                                                                             #
# You should have received a copy of the GNU Affero Public License along      #
# with the BEAT platform. If not, see http://www.gnu.org/licenses/.           #
#                                                                             #
###############################################################################

from django import forms
from django.contrib import admin
from django.core.files.base import ContentFile
from django.utils import six

from .models import Database as DatabaseModel
from .models import DatabaseProtocol as DatabaseProtocolModel
from .models import DatabaseSet as DatabaseSetModel
from .models import DatabaseSetOutput as DatabaseSetOutputModel
from .models import DatabaseSetTemplate as DatabaseSetTemplateModel
from .models import DatabaseSetTemplateOutput as DatabaseSetTemplateOutputModel
from .models import validate_database

from ..ui.forms import CodeMirrorJSONFileField, CodeMirrorRSTFileField, \
    CodeMirrorPythonFileField, NameField

from ..common.texts import Messages
from ..common.admin import notify_by_email
from ..common.models import Shareable

import simplejson as json


#------------------------------------------------


[docs]class DatabaseModelForm(forms.ModelForm): name = NameField( widget=forms.TextInput(attrs=dict(size=80)), help_text=Messages['name'], ) declaration_file = CodeMirrorJSONFileField( label='Declaration', help_text=Messages['json'], ) source_code_file = CodeMirrorPythonFileField( label='Source code', help_text=Messages['code'], ) description_file = CodeMirrorRSTFileField( label='Description', required=False, allow_empty_file=True, help_text=Messages['description'], )
[docs] class Meta: model = DatabaseModel exclude = [] widgets = { 'short_description': forms.TextInput( attrs=dict(size=100), ), }
[docs] def clean_declaration_file(self): """Cleans-up the declaration_file data, make sure it is really new""" new_declaration = self.cleaned_data['declaration_file'].read() old_declaration = '' if self.instance and self.instance.declaration_file.name is not None: old_declaration = self.instance.declaration_string if new_declaration == old_declaration: self.changed_data.remove('declaration_file') content_file = ContentFile(old_declaration) content_file.name = self.instance.declaration_file.name return content_file # tries a simple validation try: database = validate_database(json.loads(new_declaration)) except Exception as e: raise forms.ValidationError(str(e)) if not database.valid: all_errors = [forms.ValidationError(k) for k in database.errors] raise forms.ValidationError(all_errors) # if that works out, then we return the passed file self.cleaned_data['declaration_file'].seek(0) #reset ContentFile readout return self.cleaned_data['declaration_file']
[docs] def clean(self): """Cleans-up the input data, make sure it overall validates""" if 'declaration_file' in self.data and \ isinstance(self.data['declaration_file'], six.string_types): mutable_data = self.data.copy() mutable_data['declaration_file'] = ContentFile(self.data['declaration_file'], name='unsaved') self.data = mutable_data
#----------------------------------------------------------
[docs]class DatabaseProtocolInline(admin.TabularInline): model = DatabaseProtocolModel can_delete = False extra = 0 max_num = 0 readonly_fields = ('name',) ordering = ('name',)
#----------------------------------------------------------
[docs]class Database(admin.ModelAdmin): list_display = ( 'id', 'name', 'version', 'short_description', 'creation_date', 'previous_version', 'sharing', ) search_fields = [ 'name', 'short_description', 'previous_version__author__username', 'previous_version__name' ] list_display_links = ( 'id', 'name', ) readonly_fields = ('short_description',) form = DatabaseModelForm inlines = [ DatabaseProtocolInline, ] filter_horizontal = [ 'shared_with', 'shared_with_team' ]
[docs] def new_version(self, request, queryset): """Creates a new version of a specific database""" count = 0 for olddb in queryset: newdb = DatabaseModel() newdb.name = olddb.name newdb.version = olddb.version + 1 newdb.sharing = Shareable.PRIVATE newdb.declaration = olddb.declaration newdb.source_code = olddb.source_code newdb.description = olddb.description newdb.previous_version = olddb newdb.save() count += 1 self.message_user(request, "Created %s new version(s) of selected " \ "databases." % count)
new_version.short_description = 'Create new version' actions = [ notify_by_email('database_notifications_enabled'), 'new_version', ] fieldsets = ( (None, dict( fields=('name',), ), ), ('Documentation', dict( classes=('collapse',), fields=('short_description', 'description_file'), ), ), ('Versioning', dict( classes=('collapse',), fields=('version', 'previous_version'), ), ), ('Sharing', dict( classes=('collapse',), fields=('sharing', 'shared_with', 'shared_with_team'), ), ), ('Source code', dict( fields=('declaration_file', 'source_code_file'), ), ), )
admin.site.register(DatabaseModel, Database) #------------------------------------------------
[docs]class DatabaseSetTemplateOutputInline(admin.TabularInline): model = DatabaseSetTemplateOutputModel extra = 0 ordering = ('name',) readonly_fields = ('name', 'dataformat')
[docs] def has_delete_permission(self, request, obj=None): return False
[docs] def has_add_permission(self, request): return False
[docs]class DatabaseSetTemplate(admin.ModelAdmin): list_display = ('id', 'name') search_fields = ['name'] list_display_links = ('id', 'name') readonly_fields = ('name',) inlines = [ DatabaseSetTemplateOutputInline, ]
[docs] def has_delete_permission(self, request, obj=None): return False
[docs] def has_add_permission(self, request): return False
admin.site.register(DatabaseSetTemplateModel, DatabaseSetTemplate) #------------------------------------------------
[docs]class DatabaseSetOutputInline(admin.TabularInline): model = DatabaseSetOutputModel extra = 0 ordering = ('template__name',) readonly_fields = ('template',)
[docs] def has_delete_permission(self, request, obj=None): return False
[docs] def has_add_permission(self, request): return False
[docs]class DatabaseSet(admin.ModelAdmin): list_display = ('id', 'protocol', 'name', 'template', 'hash') search_fields = ['name', 'template__name', 'protocol__database__name', 'protocol__name'] list_display_links = ('id', 'name') readonly_fields = ('name', 'template', 'protocol', 'hash') inlines = [ DatabaseSetOutputInline, ]
[docs] def has_delete_permission(self, request, obj=None): return False
[docs] def has_add_permission(self, request): return False
admin.site.register(DatabaseSetModel, DatabaseSet)