Source code for beat.web.dataformats.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/.           #
#                                                                             #
###############################################################################

import simplejson as json
from django import forms
from django.contrib import admin
from django.core.files.base import ContentFile

from ..common.texts import Messages
from ..ui.forms import CodeMirrorJSONFileField
from ..ui.forms import CodeMirrorRSTFileField
from ..ui.forms import NameField
from .models import DataFormat as DataFormatModel
from .models import validate_format

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


[docs]class DataFormatModelForm(forms.ModelForm): name = NameField( widget=forms.TextInput(attrs=dict(size=80)), help_text=Messages["name"], ) declaration_file = CodeMirrorJSONFileField( label="Declaration", help_text=Messages["format"], ) description_file = CodeMirrorRSTFileField( label="Description", required=False, allow_empty_file=True, help_text=Messages["description"], )
[docs] class Meta: model = DataFormatModel exclude = [] widgets = { "short_description": forms.TextInput(attrs=dict(size=100),), "extend": forms.Select(attrs=dict(disabled=1),), "referenced_formats": forms.SelectMultiple(attrs=dict(disabled=1),), }
[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 # we validate the dataformat to present errors close to the field # on the form. try: core_format, referenced_formats, extend, errors = validate_format( json.loads(new_declaration) ) except SyntaxError as e: raise forms.ValidationError(str(e)) if errors: # it is a list with possibly many entries raise forms.ValidationError([forms.ValidationError(k) for k in errors]) if referenced_formats: self.cleaned_data["referenced_formats"] = referenced_formats self.data["referenced_formats"] = referenced_formats # set on form self.changed_data.append("referenced_formats") if extend is not None: self.cleaned_data["extend"] = extend self.data["extend"] = extend # set on form self.changed_data.append("extend") # 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"], str ): mutable_data = self.data.copy() mutable_data["declaration_file"] = ContentFile( self.data["declaration_file"], name="unsaved" ) self.data = mutable_data
# ----------------------------------------------------------
[docs]def rehash_dataformat(modeladmin, request, queryset): """Recalculates the hash of an dataformat""" for q in queryset: q.save()
rehash_dataformat.short_description = "Rehash selected dataformats" # ----------------------------------------------------------
[docs]class DataFormat(admin.ModelAdmin): list_display = ( "id", "author", "name", "version", "short_description", "creation_date", "extend", "previous_version", "fork_of", "sharing", "hash", ) search_fields = [ "author__username", "name", "short_description", ] list_display_links = ("id", "name") list_filter = ("sharing",) readonly_fields = ("hash", "short_description") actions = [ rehash_dataformat, ] form = DataFormatModelForm filter_horizontal = ["shared_with", "shared_with_team"] fieldsets = ( (None, dict(fields=("name", "author"),),), ( "Documentation", dict( classes=("collapse",), fields=("short_description", "description_file"), ), ), ( "Versioning", dict( classes=("collapse",), fields=("version", "previous_version", "fork_of"), ), ), ( "Sharing", dict( classes=("collapse",), fields=("sharing", "shared_with", "shared_with_team"), ), ), ( "Referenced objects (read-only)", dict(classes=("collapse",), fields=("extend", "referenced_formats",),), ), ("Source code", dict(fields=("hash", "declaration_file"),),), )
admin.site.register(DataFormatModel, DataFormat)