Top

telemeta.views.item module

# -*- coding: utf-8 -*-

# Copyright (C) 2010-2015 Parisson SARL
# Copyright (C) 2007-2010 Samalyse SARL

# This file is part of Telemeta.

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program 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.  See the
# GNU Affero General Public License for more details.

# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Authors: Olivier Guilyardi <olivier@samalyse.com>
#          Guillaume Pellerin <yomguy@parisson.com>
import telemeta

from telemeta.views.core import *
from telemeta.views.core import serve_media
from telemeta.views.core import TelemetaBaseMixin
from telemeta.views.marker import *
import timeside.core
import timeside.server as ts
import sys
import time


class ItemBaseMixin(TelemetaBaseMixin):

    graphers = timeside.core.processor.processors(timeside.core.api.IGrapher)
    decoders = timeside.core.processor.processors(timeside.core.api.IDecoder)
    encoders = timeside.core.processor.processors(timeside.core.api.IEncoder)
    analyzers = timeside.core.processor.processors(timeside.core.api.IAnalyzer)
    value_analyzers = timeside.core.processor.processors(timeside.core.api.IValueAnalyzer)

    export_enabled = getattr(settings, 'TELEMETA_DOWNLOAD_ENABLED', True)
    export_formats = getattr(settings, 'TELEMETA_DOWNLOAD_FORMATS', ('mp3', 'wav'))
    default_grapher_id = getattr(settings, 'TIMESIDE_DEFAULT_GRAPHER_ID', ('waveform_simple'))
    default_grapher_sizes = getattr(settings, 'TIMESIDE_DEFAULT_GRAPHER_SIZES', ['346x130', ])
    auto_zoom = getattr(settings, 'TIMESIDE_AUTO_ZOOM', False)

    public_graphers  = ['waveform_centroid' ,'waveform_simple',
                        'spectrogram', 'spectrogram_log']

    def get_graphers(self):
        graphers = []
        user = self.request.user
        graphers_access = (user.is_staff
                           or user.is_superuser
                           or user.has_perm('can_run_analysis'))

        for grapher in self.graphers:
            if (not graphers_access
                and grapher.id() not in self.public_graphers):
                continue
            if grapher.id() == self.default_grapher_id:
                graphers.insert(0, {'name': grapher.name(), 'id': grapher.id()})
            elif not hasattr(grapher, '_staging'):
                graphers.append({'name': grapher.name(), 'id': grapher.id()})
            elif not grapher._staging:
                graphers.append({'name': grapher.name(), 'id': grapher.id()})
        return graphers

    def get_grapher(self, id):
        for grapher in self.graphers:
            if grapher.id() == id:
                break
        return grapher

    def get_export_formats(self):
        formats = []
        for encoder in self.encoders:
            if encoder.file_extension() in self.export_formats:
                formats.append({'name': encoder.format(),
                                'extension': encoder.file_extension()})
        return formats

    def get_is_transcoded_flag(self, item, mime_type):
        try:
            is_transcoded_flag, c = MediaItemTranscodingFlag.objects.get_or_create(
                item=item,
                mime_type=mime_type,
                defaults={'value': False})
        except MediaItemTranscodingFlag.MultipleObjectsReturned:
            flags = MediaItemTranscodingFlag.objects.filter(
                item=item,
                mime_type=mime_type)
            value = all([f.value for f in flags])
            is_transcoded_flag = flags[0]
            is_transcoded_flag.value = value
            is_transcoded_flag.save()
            for f in flags[1:]:
                f.delete()
        return is_transcoded_flag

    def item_previous_next(self, item):
        """Get previous and next items inside the collection of the item"""

        pks = []
        items = MediaItem.objects.filter(collection=item.collection)
        items = items.order_by('code', 'old_code')

        if len(items) > 1:
            for it in items:
                pks.append(it.pk)
            for pk in pks:
                if pk == item.pk:
                    if pk == pks[0]:
                        previous_pk = pks[-1]
                        next_pk = pks[1]
                    elif pk == pks[-1]:
                        previous_pk = pks[-2]
                        next_pk = pks[0]
                    else:
                        previous_pk = pks[pks.index(pk) - 1]
                        next_pk = pks[pks.index(pk) + 1]
                    for it in items:
                        if it.pk == previous_pk:
                            previous = it
                        if it.pk == next_pk:
                            next = it
                    previous = previous.public_id
                    next = next.public_id
        else:
            previous = item.public_id
            next = item.public_id
        return previous, next

    @jsonrpc_method('telemeta.get_item_export_url')
    def get_item_file_url(request, public_id, extension):
        return reverse('telemeta-item-export', kwargs={'public_id': public_id, 'extension': extension})


class ItemView(ItemBaseMixin):
    """Provide Item web UI methods"""

    def item_detail(self, request, public_id=None, marker_id=None, width=None, height=None,
                    template='telemeta/mediaitem_detail.html'):
        """Show the details of a given item"""

        # get item with one of its given marker_id
        if not public_id and marker_id:
            marker = get_object_or_404(MediaItemMarker, public_id=marker_id)
            item_id = marker.item_id
            item = MediaItem.objects.get(id=item_id)
        else:
            item = get_object_or_404(MediaItem, public_id=public_id)

        access = get_item_access(item, request.user)

        if access == 'none':
            mess = ugettext('Access not allowed')
            title = ugettext('Item') + ' : ' + public_id + ' : ' + mess
            description = ugettext('Please login or contact the website administator to get a private access.')
            messages.error(request, title)
            return render(request, 'telemeta/messages.html', {'description': description})

        previous, next = self.item_previous_next(item)

        mime_type = item.mime_type
        if mime_type and mime_type != 'none':
            if 'quicktime' in mime_type:
                mime_type = 'video/mp4'

        playlists = get_playlists_names(request)
        related_media = MediaItemRelated.objects.filter(item=item)
        check_related_media(related_media)
        revisions = Revision.objects.filter(element_type='item', element_id=item.id).order_by('-time')
        if revisions:
            last_revision = revisions[0]
        else:
            last_revision = None

        format = ''
        if Format.objects.filter(item=item):
            format = item.format.get()

        return render(request, template,
                      {'item': item, 'export_formats': self.get_export_formats(),
                       'visualizers': self.get_graphers(), 'auto_zoom': self.auto_zoom,
                       'audio_export_enabled': self.export_enabled,
                       'previous': previous, 'next': next, 'marker': marker_id, 'playlists': playlists,
                       'access': access, 'width': width, 'height': height,
                       'related_media': related_media, 'mime_type': mime_type, 'last_revision': last_revision,
                       'format': format,
                       })

    def related_media_item_stream(self, request, item_public_id, media_id):
        item = get_object_or_404(MediaItem, code=item_public_id)
        media = get_object_or_404(MediaItemRelated, item=item, id=media_id)
        if media.file:
            response = serve_media(media.file.path, content_type=media.mime_type)
        else:
            raise Http404
        return response

    def related_media_item_download(self, request, item_public_id, media_id):
        item = get_object_or_404(MediaItem, code=item_public_id)
        media = get_object_or_404(MediaItemRelated, item=item, id=media_id)
        if media.file:
            response = serve_media(media.file.path, content_type=media.mime_type)
        else:
            raise Http404
        return response

    @method_decorator(permission_required('telemeta.change_mediaitem'))
    def related_media_edit(self, request, public_id, template):
        item = get_object_or_404(MediaItem, code=public_id)
        MediaItemRelatedFormSet = inlineformset_factory(MediaItem, MediaItemRelated, form=MediaItemRelatedForm)
        if request.method == 'POST':
            formset = MediaItemRelatedFormSet(data=request.POST, files=request.FILES, instance=item)
            if formset.is_valid():
                formset.save()
                item.set_revision(request.user)
                return redirect('telemeta-item-edit', public_id)
        else:
            formset = MediaItemRelatedFormSet(instance=item)
        return render(request, template, {'item': item, 'formset': formset, })

    @method_decorator(permission_required('telemeta.delete_mediaitem'))
    def item_delete(self, request, public_id):
        """Delete a given item"""
        item = MediaItem.objects.get(public_id=public_id)
        revisions = Revision.objects.filter(element_type='item', element_id=item.id)
        for revision in revisions:
            revision.delete()
        collection = item.collection
        item.delete()
        return redirect('telemeta-collection-detail', collection.code)

    def item_analyze_xml(self, request, public_id):
        item = MediaItem.objects.get(public_id=public_id)
        analyses = item.analysis.all()
        analyzers = []
        for analysis in analyses:
            analyzers.append(analysis.to_dict())
        mime_type = 'text/xml'
        response = HttpResponse(self.cache_data.get_analyzer_xml(analyzers), content_type=mime_type)
        response['Content-Disposition'] = 'attachment; filename=' + public_id + '.xml'
        return response

    def item_visualize(self, request, public_id, grapher_id, width, height):
        try:
            width = int(width)
            height = int(height)
        except:
            pass

        if not isinstance(width, int) or not isinstance(height, int):
            size = self.default_grapher_sizes[0]
            width = int(size.split('x')[0])
            height = int(size.split('x')[1])

        item = MediaItem.objects.get(public_id=public_id)
        mime_type = 'image/png'

        source, source_type = item.get_source()
        # if source:
        #     ts_item, c = ts.models.Item.objects.get_or_create(**{source_type: source})
        #     if c:
        #         ts_item.title = item.title
        #         ts_item.save()
        #
        # ts_grapher, c = ts.models.Processor.objects.get_or_create(pid=grapher_id)
        # ts_preset, c = ts.models.Preset.objects.get_or_create(processor=ts_grapher,
        #                                                       parameters={'width': width, 'height': height})
        # ts_experience = ts_preset.get_single_experience()
        # ts_selection = ts_item.get_single_selection()
        # ts_task, c = ts.models.Task.objects.get_or_create(experience=ts_experience,
        #                                            selection=ts_selection)
        # ts_task.run()

        grapher = self.get_grapher(grapher_id)

        if grapher.id() != grapher_id:
            raise Http404

        size = str(width) + '_' + str(height)
        image_file = '.'.join([public_id, grapher_id, size, 'png'])

        # FIX waveform grapher name change
        old_image_file = '.'.join([public_id, 'waveform', size, 'png'])
        if 'waveform_centroid' in grapher_id and self.cache_data.exists(old_image_file):
            image_file = old_image_file

        if not self.cache_data.exists(image_file):
            source, _ = item.get_source()
            if source:
                path = self.cache_data.dir + os.sep + image_file
                decoder = timeside.core.get_processor('file_decoder')(source)
                graph = grapher(width=width, height=height)
                (decoder | graph).run()
                graph.watermark('timeside', opacity=.6, margin=(5, 5))
                #f = open(path, 'w')
                graph.render(output=path)
                # f.close()
                self.cache_data.add_file(image_file)

        response = StreamingHttpResponse(self.cache_data.read_stream_bin(image_file), content_type=mime_type)
        return response

    def list_export_extensions(self):
        "Return the recognized item export file extensions, as a list"
        list = []
        for encoder in self.encoders:
            list.append(encoder.file_extension())
        # FIXME: MP4
        list.append('mp4')
        return list

    def item_transcode(self, item, extension):
        for encoder in self.encoders:
            if encoder.file_extension() == extension:
                break

        if encoder.file_extension() != extension:
            raise Http404('Unknown export file extension: %s' % extension)

        mime_type = encoder.mime_type()
        file = item.public_id + '.' + encoder.file_extension()
        source, source_type = item.get_source()

        is_transcoded_flag = self.get_is_transcoded_flag(item=item, mime_type=mime_type)

        format = item.mime_type
        dc_metadata = dublincore.express_item(item).to_list()
        mapping = DublinCoreToFormatMetadata(extension)
        if not extension in mapping.unavailable_extensions:
            metadata = mapping.get_metadata(dc_metadata)
        else:
            metadata = None

        if mime_type in format and source_type == 'file':
            # source > stream
            if metadata:
                proc = encoder(source, overwrite=True)
                proc.set_metadata(metadata)
                try:
                    # FIXME: should test if metadata writer is available
                    proc.write_metadata()
                except:
                    pass
            return (source, mime_type)
        else:
            media = self.cache_export.dir + os.sep + file
            if not is_transcoded_flag.value:
                try:
                    progress_flag = MediaItemTranscodingFlag.objects.get(
                        item=item,
                        mime_type=mime_type + '/transcoding')
                    if progress_flag.value:
                        # The media is being transcoded
                        # return None
                        return (None, None)

                    else:
                        # wait for the transcode to begin
                        time.sleep(1)
                        return (None, None)  # self.item_transcode(item, extension)

                except MediaItemTranscodingFlag.DoesNotExist:
                    pass
                # source > encoder > stream
                from telemeta.tasks import task_transcode
                # Sent the transcoding task synchronously to the worker
                task_transcode.apply_async(kwargs={'source': source,
                                                   'media': media,
                                                   'encoder_id': encoder.id(),
                                                   'item_public_id': item.public_id,
                                                   'mime_type': mime_type,
                                                   'metadata': metadata})

                self.cache_export.add_file(file)
                if not os.path.exists(media):
                    return (None, None)
            else:
                # cache > stream
                if not os.path.exists(media):
                    is_transcoded_flag.value = False
                    is_transcoded_flag.save()
                    return self.item_transcode(item, extension)

        return (media, mime_type)

    def item_export(self, request, public_id, extension, return_availability=False):
        """Export a given media item in the specified format (OGG, FLAC, ...)"""

        item = MediaItem.objects.get(public_id=public_id)
        public_access = get_item_access(item, request.user)

        if not extension:
            extension = item.file.path.split('.')[-1]

        if (not public_access == 'full' or not extension in settings.TELEMETA_STREAMING_FORMATS) and \
                not (request.user.has_perm('telemeta.can_play_all_items') or request.user.is_superuser):
            mess = ugettext('Access not allowed')
            title = 'Item file : ' + public_id + '.' + extension + ' : ' + mess
            description = ugettext('Please login or contact the website administator to get a private access.')
            messages.error(request, title)
            return render(request, 'telemeta/messages.html', {'description': description})

        # FIXME: MP4 handling in TimeSide
        if 'mp4' in extension:
            mime_type = 'video/mp4'
            video = item.file.path
            response = serve_media(video, content_type=mime_type)
            # response['Content-Disposition'] = 'attachment'
            # TF : I don't know why empty attachment was set
            # TODO: remove if useless
            if return_availability:
                data = json.dumps({'available': True})
                return HttpResponse(data, content_type='application/json')
            return response

        if 'webm' in extension:
            mime_type = 'video/webm'
            video = item.file.path
            response = serve_media(video, content_type=mime_type)
            # response['Content-Disposition'] = 'attachment'
            # TF : I don't know why empty attachment was set,
            # TODO: remove if useless
            if return_availability:
                data = json.dumps({'available': True})
                return HttpResponse(data, content_type='application/json')
            return response

        (media, mime_type) = self.item_transcode(item, extension)
        #media  = None
        if media:
            if return_availability:
                data = json.dumps({'available': True})
                return HttpResponse(data, content_type='application/json')
            response = serve_media(media, content_type=mime_type)
            return response
        else:
            if return_availability:
                data = json.dumps({'available': False})
                return HttpResponse(data, content_type='application/json')

            mess = ugettext('Transcoding in progress')
            title = ugettext('Item') + ' : ' + public_id + ' : ' + mess
            description = ugettext('The media transcoding is in progress. '
                                   'Please wait for the trancoding process to complete.')
            messages.info(request, title)
            response = render(request, 'telemeta/messages.html', {'description': description})
            from django.utils.cache import patch_cache_control
            #patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)
            return response

    def item_export_available(self, request, public_id, extension):
        return self.item_export(request, public_id, extension, return_availability=True)

    def item_playlist(self, request, public_id, template, mimetype):
        try:
            item = MediaItem.objects.get(public_id=public_id)
        except ObjectDoesNotExist:
            raise Http404

        template = loader.get_template(template)
        context = RequestContext(request, {'item': item, 'host': request.META['HTTP_HOST']})
        return HttpResponse(template.render(context), content_type=mimetype)

    @method_decorator(permission_required('telemeta.change_mediaitem'))
    def item_performances_edit(self, request, public_id, template):
        item = MediaItem.objects.get(public_id=public_id)
        PerformanceFormSet = inlineformset_factory(MediaItem, MediaItemPerformance, form=MediaItemPerformanceForm)
        if request.method == 'POST':
            formset = PerformanceFormSet(data=request.POST, instance=item)
            if formset.is_valid():
                formset.save()
                return redirect('telemeta-item-edit', item.public_id)
        else:
            formset = PerformanceFormSet(instance=item)
        return render(request, template, {'item': item, 'formset': formset, })

    @method_decorator(permission_required('telemeta.change_mediaitem'))
    def item_keywords_edit(self, request, public_id, template):
        item = MediaItem.objects.get(public_id=public_id)
        FormSet = inlineformset_factory(MediaItem, MediaItemKeyword)
        if request.method == 'POST':
            formset = FormSet(data=request.POST, instance=item)
            if formset.is_valid():
                formset.save()
                return redirect('telemeta-item-edit', item.public_id)
        else:
            formset = FormSet(instance=item)
        return render(request, template, {'item': item, 'formset': formset, })


class ItemListView(ListView):

    model = MediaItem
    template_name = "telemeta/mediaitem_list.html"
    queryset = MediaItem.objects.enriched().order_by('code', 'old_code')

    def get_paginate_by(self, queryset):
        return self.request.GET.get('results_page', 20)

    def get_context_data(self, **kwargs):
        context = super(ItemListView, self).get_context_data(**kwargs)
        context['count'] = self.object_list.count()
        context['results_page'] = int(self.request.GET.get('results_page', 20))
        return context


class ItemListViewFullAccess(ListView):

    model = MediaItem
    template_name = "telemeta/mediaitem_list.html"
    paginate_by = 20
    queryset = MediaItem.objects.enriched().filter(Q(collection__public_access="full") | Q(public_access="full")).sound().exclude(collection__public_access="none").order_by('code', 'old_code')

    def get_context_data(self, **kwargs):
        context = super(ItemListViewFullAccess, self).get_context_data(**kwargs)
        context['count'] = self.object_list.count()
        return context


class ItemUnpublishedListView(ItemListView):

    queryset = MediaItem.objects.filter(collection__code__contains='_I_').order_by('code', 'old_code')


class ItemPublishedListView(ItemListView):

    queryset = MediaItem.objects.filter(collection__code__contains='_E_').order_by('code', 'old_code')


class ItemSoundListView(ItemListView):

    queryset = MediaItem.objects.sound().order_by('code', 'old_code')


class ItemInstrumentListView(ItemListView):

    template_name = "telemeta/media_item_instrument_list.html"

    def get_queryset(self):
        return MediaItem.objects.filter(performances__instrument__id=self.kwargs['value_id'])

    def get_context_data(self, **kwargs):
        context = super(ItemInstrumentListView, self).get_context_data(**kwargs)

        context['nom'] = Instrument.objects.get(id=self.kwargs['value_id']).name
        context['id'] = self.kwargs['value_id']

        return context


class ItemInstrumentPublishedListView(ItemInstrumentListView):

    def get_queryset(self):
        return super(ItemInstrumentPublishedListView, self).get_queryset().filter(collection__code__contains='_E_').order_by('code', 'old_code')


class ItemInstrumentUnpublishedListView(ItemInstrumentListView):

    def get_queryset(self):
        return super(ItemInstrumentUnpublishedListView, self).get_queryset().filter(collection__code__contains='_I_').order_by('code', 'old_code')


class ItemInstrumentSoundListView(ItemInstrumentListView):

    def get_queryset(self):
        return super(ItemInstrumentSoundListView, self).get_queryset().sound().order_by('code', 'old_code')


class ItemAliasListView(ItemListView):

    template_name = "telemeta/media_item_alias_list.html"

    def get_queryset(self):
        return MediaItem.objects.filter(performances__alias__id=self.kwargs['value_id'])

    def get_context_data(self, **kwargs):
        context = super(ItemAliasListView, self).get_context_data(**kwargs)

        context['nom'] = InstrumentAlias.objects.get(id=self.kwargs['value_id']).name
        context['id'] = self.kwargs['value_id']

        return context


class ItemAliasPublishedListView(ItemAliasListView):

    def get_queryset(self):
        return super(ItemAliasPublishedListView, self).get_queryset().filter(collection__code__contains='_E_').order_by('code', 'old_code')


class ItemAliasUnpublishedListView(ItemAliasListView):

    def get_queryset(self):
        return super(ItemAliasUnpublishedListView, self).get_queryset().filter(collection__code__contains='_I_').order_by('code', 'old_code')


class ItemAliasSoundListView(ItemAliasListView):

    def get_queryset(self):
        return super(ItemAliasSoundListView, self).get_queryset().sound().order_by('code', 'old_code')


class ItemViewMixin(ItemBaseMixin):

    model = MediaItem
    form_class = MediaItemForm
    inlines = [ItemPerformanceInline, ItemKeywordInline, ItemRelatedInline, ItemIdentifierInline]
    # inlines = [ItemPerformanceInline, ItemKeywordInline, ItemRelatedInline,
    #             ItemFormatInline, ItemIdentifierInline]

    def get_object(self):
        obj = self.model.objects.filter(code=self.kwargs['public_id'])
        if not obj:
            if self.kwargs['public_id'].isdigit():
                try:
                    obj = self.model.objects.get(id=self.kwargs['public_id'])
                except self.model.DoesNotExist:
                    raise Http404
            else:
                raise Http404
        else:
            obj = obj[0]
        return obj


class ItemEditView(ItemViewMixin, UpdateWithInlinesView):

    template_name = 'telemeta/mediaitem_edit.html'

    def get_form_class(self):
        if self.request.user.is_staff:
            return MediaItemForm
        else:
            return RestrictedMediaItemForm

    def forms_valid(self, form, inlines):
        messages.info(self.request, ugettext_lazy("You have successfully updated your item."))
        item = form.save()
        self.code = item.code
        if form.files:
            self.cache_data.delete_item_data(item.code)
            self.cache_export.delete_item_data(item.code)
            flags = MediaItemTranscodingFlag.objects.filter(item=item)
            analyses = MediaItemAnalysis.objects.filter(item=item)
            for flag in flags:
                flag.delete()
            for analysis in analyses:
                analysis.delete()
        item.set_revision(self.request.user)
        return super(ItemEditView, self).forms_valid(form, inlines)

    def get_success_url(self):
        return reverse_lazy('telemeta-item-detail', kwargs={'public_id': self.code})

    def get_context_data(self, **kwargs):
        context = super(ItemEditView, self).get_context_data(**kwargs)
        item = self.get_object()
        context['item'] = item
        context['access'] = get_item_access(item, self.request.user)
        context['previous'], context['next'] = self.item_previous_next(item)
        # FIXME
        context['mime_type'] = 'audio/mp3'
        context['export_formats'] = self.get_export_formats()
        context['visualizers'] = self.get_graphers()
        context['audio_export_enabled'] = self.export_enabled
        context['auto_zoom'] = True
        return context

    @method_decorator(permission_required('telemeta.change_mediaitem'))
    def dispatch(self, *args, **kwargs):
        return super(ItemEditView, self).dispatch(*args, **kwargs)


class ItemAddView(ItemViewMixin, CreateWithInlinesView):

    form_class = MediaItemForm
    template_name = 'telemeta/mediaitem_add.html'

    def get_initial(self):
        item = self.model()
        # new item for a specific collection
        if 'public_id' in self.kwargs:
            public_id = self.kwargs['public_id']
            collections = MediaCollection.objects.filter(code=public_id)
            if collections:
                collection = collections[0]
                item.collection = collection
                items = MediaItem.objects.filter(collection=collection)
                item.code = auto_code(collection)
        return model_to_dict(item)

    def forms_valid(self, form, inlines):
        messages.info(self.request, ugettext_lazy("You have successfully added your item."))
        obj = form.save()
        obj.set_revision(self.request.user)
        return super(ItemAddView, self).forms_valid(form, inlines)

    def get_success_url(self):
        return reverse_lazy('telemeta-item-detail', kwargs={'public_id': self.object.code})

    @method_decorator(permission_required('telemeta.add_mediaitem'))
    def dispatch(self, *args, **kwargs):
        return super(ItemAddView, self).dispatch(*args, **kwargs)


class ItemCopyView(ItemAddView):

    form_class = MediaItemForm
    template_name = 'telemeta/mediaitem_edit.html'

    def get_initial(self):
        item = self.get_object()
        item.code = auto_code(item.collection)
        return model_to_dict(item)

    def forms_valid(self, form, inlines):
        messages.info(self.request, ugettext_lazy("You have successfully updated your item."))
        item = form.save()
        item.set_revision(self.request.user)
        if not MediaItemPerformance.objects.filter(media_item=item):
            for performance in MediaItemPerformance.objects.filter(media_item=self.get_object()):
                performance.pk = None
                performance.id = None
                performance.media_item = item
                performance.save()
        if not MediaItemKeyword.objects.filter(item=item):
            for keyword in MediaItemKeyword.objects.filter(item=self.get_object()):
                keyword.pk = None
                keyword.id = None
                keyword.item = item
                keyword.save()
        return super(ItemCopyView, self).forms_valid(form, inlines)

    def get_success_url(self):
        return reverse_lazy('telemeta-item-detail', kwargs={'public_id': self.object.code})

    def get_context_data(self, **kwargs):
        context = super(ItemCopyView, self).get_context_data(**kwargs)
        item = self.get_object()
        context['item'] = item
        context['access'] = get_item_access(item, self.request.user)
        context['previous'], context['next'] = self.item_previous_next(item)
        # FIXME
        context['mime_type'] = 'audio/mp3'
        context['export_formats'] = self.get_export_formats()
        context['visualizers'] = self.get_graphers()
        context['audio_export_enabled'] = self.export_enabled
        context['auto_zoom'] = True
        return context

    @method_decorator(permission_required('telemeta.add_mediaitem'))
    def dispatch(self, *args, **kwargs):
        return super(ItemCopyView, self).dispatch(*args, **kwargs)


class ItemDetailView(ItemViewMixin, DetailView):

    template_name = 'telemeta/mediaitem_detail.html'

    def item_analyze(self, item):
        analyses = item.analysis.all()
        encoders_id = ['mp3_encoder']  # , 'vorbis_encoder']
        mime_type = ''

        if analyses:
            for analysis in analyses:
                if not item.approx_duration and analysis.analyzer_id == 'duration':
                    value = analysis.value
                    time = value.split(':')
                    time[2] = time[2].split('.')[0]
                    time = ':'.join(time)
                    item.approx_duration = time
                    item.save()
                if analysis.analyzer_id == 'mime_type':
                    mime_type = analysis.value
        else:
            analyzers = []
            analyzers_sub = []
            graphers_sub = []
            encoders_sub = []

            source = item.get_source()[0]

            if source:

                decoder = timeside.core.get_processor('file_decoder')(source)
                pipe = decoder

                for analyzer in self.value_analyzers:
                    subpipe = analyzer()
                    analyzers_sub.append(subpipe)
                    pipe = pipe | subpipe

                default_grapher = self.get_grapher(self.default_grapher_id)
                for size in self.default_grapher_sizes:
                    width = size.split('x')[0]
                    height = size.split('x')[1]
                    image_file = '.'.join([item.public_id, self.default_grapher_id, size.replace('x', '_'), 'png'])
                    path = self.cache_data.dir + os.sep + image_file
                    graph = default_grapher(width=int(width), height=int(height))
                    graphers_sub.append({'graph': graph, 'path': path})
                    pipe |= graph

                for proc_id in encoders_id:
                    encoder_cls = timeside.core.get_processor(proc_id)
                    mime_type = encoder_cls.mime_type()
                    cache_file = item.public_id + '.' + encoder_cls.file_extension()
                    media = self.cache_export.dir + os.sep + cache_file
                    encoder = encoder_cls(output=media, overwrite=True)
                    encoders_sub.append(encoder)
                    pipe |= encoder

                pipe.run()

                for grapher in graphers_sub:
                    grapher['graph'].watermark('timeside', opacity=.6, margin=(5, 5))
                    f = open(grapher['path'], 'w')
                    grapher['graph'].render(grapher['path'])
                    f.close()

                if os.path.exists(source):
                    mime_type = mimetypes.guess_type(source)[0]
                    analysis = MediaItemAnalysis(item=item, name='MIME type',
                                                 analyzer_id='mime_type', unit='', value=mime_type)
                    analysis.save()
                    analysis = MediaItemAnalysis(item=item, name='Size',
                                                 analyzer_id='size', unit='', value=item.size())
                    analysis.save()

                analysis = MediaItemAnalysis(item=item, name='Channels',
                                             analyzer_id='channels',
                                             unit='', value=decoder.input_channels)
                analysis.save()
                analysis = MediaItemAnalysis(item=item, name='Samplerate',
                                             analyzer_id='samplerate', unit='Hz',
                                             value=unicode(decoder.input_samplerate))
                analysis.save()
                analysis = MediaItemAnalysis(item=item, name='Resolution',
                                             analyzer_id='resolution', unit='bits',
                                             value=unicode(decoder.input_width))
                analysis.save()
                analysis = MediaItemAnalysis(item=item, name='Duration',
                                             analyzer_id='duration', unit='s',
                                             value=unicode(datetime.timedelta(0, decoder.input_duration)))
                analysis.save()

                for analyzer in analyzers_sub:
                    for key in analyzer.results.keys():
                        result = analyzer.results[key]
                        value = result.data_object.value
                        if value.shape[0] == 1:
                            value = value[0]
                        analysis = MediaItemAnalysis(item=item, name=result.name,
                                                     analyzer_id=result.id, unit=result.unit, value=unicode(value))
                        analysis.save()

                for encoder in encoders_sub:
                    is_transcoded_flag = self.get_is_transcoded_flag(item=item, mime_type=mime_type)
                    is_transcoded_flag.value = True
                    is_transcoded_flag.save()

#                FIXME: parse tags on first load
#                tags = decoder.tags

        self.mime_type = mime_type

    def get_context_data(self, **kwargs):
        context = super(ItemDetailView, self).get_context_data(**kwargs)

        public_id = get_kwargs_or_none('public_id', self.kwargs)
        marker_id = get_kwargs_or_none('marker_id', self.kwargs)
        width = get_kwargs_or_none('width', self.kwargs)
        height = get_kwargs_or_none('height', self.kwargs)

        # get item with one of its given marker_id
        if not public_id and marker_id:
            marker = MediaItemMarker.objects.get(public_id=marker_id)
            item_id = marker.item_id
            item = MediaItem.objects.get(id=item_id)
        else:
            item = self.get_object()

        access = get_item_access(item, self.request.user)

        previous, next = self.item_previous_next(item)

        # Corresponding TimeSide Item
        source, source_type = item.get_source()
        # if source:
        #     ts_item, c = ts.models.Item.objects.get_or_create(**{source_type: source})
        #     if c:
        #         ts_item.title = item.title
        #         ts_item.save()

        self.item_analyze(item)

        # FIXME: use mimetypes.guess_type
        if 'quicktime' in self.mime_type:
            self.mime_type = 'video/mp4'

        playlists = get_playlists_names(self.request)

        rang = []
        for i in range(len(playlists)):
            for resource in playlists[i]['playlist'].resources.all():
                if int(resource.resource_id) == item.id:
                    rang.append(i)
                    break
        related_media = MediaItemRelated.objects.filter(item=item)
        check_related_media(related_media)
        revisions = Revision.objects.filter(element_type='item', element_id=item.id).order_by('-time')
        if revisions:
            last_revision = revisions[0]
        else:
            last_revision = None

        item_format = ''
        if Format.objects.filter(item=item):
            item_format = item.format.get()

        context['item'] = item
        context['export_formats'] = self.get_export_formats()
        context['visualizers'] = self.get_graphers()
        context['auto_zoom'] = self.auto_zoom
        context['audio_export_enabled'] = self.export_enabled
        context['previous'] = previous
        context['next'] = next
        context['marker'] = marker_id
        context['playlists'] = playlists
        context['access'] = access
        context['width'] = width
        context['height'] = height
        context['related_media'] = related_media
        context['mime_type'] = self.mime_type
        context['last_revision'] = last_revision
        context['format'] = item_format
        context['private_extra_types'] = private_extra_types.values()
        context['site'] = 'http://' + Site.objects.all()[0].name
        context['rang_item_playlist'] = rang
        # if ts_item:
        #     context['ts_item_id'] = ts_item.pk
        # else:
        #     context['ts_item_id'] = None

        return context


class DublinCoreToFormatMetadata(object):
    """a mapping class to get item DublinCore metadata dictionaries
    in various audio metadata format (MP3, OGG, etc...)"""

    # FIXME: should be given by timeside
    unavailable_extensions = ['wav', 'aiff', 'aif', 'flac', 'webm']

    metadata_mapping = {
        'mp3': {
            'title': 'TIT2',  # title2
            'creator': 'TCOM',  # composer
            'creator': 'TPE1',  # lead
            'identifier': 'UFID',  # unique ID
            'relation': 'TALB',  # album
            'type': 'TCON',  # genre
            'publisher': 'TPUB',  # publisher
                         'date': 'TDRC',  # year
            #                         'coverage': 'COMM',  #comment
        },
        'ogg': {
            'creator': 'artist',
            'relation': 'album',
                        'all': 'all',
        },
        'flac': {
            'creator': 'artist',
            'relation': 'album',
                        'all': 'all',
        },
        'wav': {
            'creator': 'artist',
            'relation': 'album',
                        'all': 'all',
        },
        'webm': {
            'creator': 'artist',
            'relation': 'album',
                        'all': 'all',
        },
    }

    def __init__(self, format):
        self.format = format

    def get_metadata(self, dc_metadata):
        mapp = self.metadata_mapping[self.format]
        metadata = {}
        keys_done = []
        for data in dc_metadata:
            key = data[0]
            value = data[1].encode('utf-8')
            if value:
                if key == 'date':
                    value = value.split(';')[0].split('=')
                    if len(value) > 1:
                        value = value[1]
                        value = value.split('-')[0]
                    else:
                        value = value[0].split('-')[0]
                if key in mapp:
                    metadata[mapp[key]] = value.decode('utf-8')
                elif 'all' in mapp.keys():
                    metadata[key] = value.decode('utf-8')
                keys_done.append(key)
        return metadata


class ItemMarkerJsonView(View):

    model = MediaItem

    def get(self, request, *args, **kwargs):
        code = self.kwargs['public_id']
        marker_view = MarkerView()
        item = MediaItem.objects.get(code=code)
        markers = marker_view.get_markers(item.id)
        if markers:
            data = json.dumps(markers)
        else:
            data = ''
        response = HttpResponse(data, content_type='application/json')
        response['Content-Disposition'] = "attachment; filename=%s.%s" % \
            (item.code, 'json')
        return response


class ItemPlayerDefaultView(ItemDetailView):

    template_name = 'telemeta/mediaitem_player.html'


class ItemDetailDCView(ItemDetailView):

    template_name = 'telemeta/mediaitem_detail_dc.html'


class ItemVideoPlayerView(ItemDetailView):

    template_name = 'telemeta/mediaitem_video_player.html'


class ItemEnumListView(ItemListView):
    template_name = 'telemeta/media_item_enum_list.html'

    def get_context_data(self, **kwargs):
        context = super(ItemListView, self).get_context_data(**kwargs)
        context['enum'] = self.request.path.split('/')[3]
        context['id'] = self.request.path.split('/')[4]
        context['count'] = self.object_list.count()
        context['keyword'] = False
        context['enum_name'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name
        context['enum_value'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4])
        context['url_all'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item/list"
        context['url_unpublished'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item_unpublished/list/"
        context['url_published'] = "/admin/enumerations/" + context['enum'] +"/"+context['id'] + "/item_published/list/"
        context['url_sound'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item_sound/list/"
        return context

    def get_queryset(self):
        enumeration = self.get_enumeration(self.request.path.split('/')[3])
        queryset = self.get_item(enumeration.objects.filter(id=self.request.path.split('/')[4]).get())
        print type(queryset)
        return queryset

    def get_item(self, enum):
        f = MediaItem._meta.get_all_field_names()
        for field in f:
            if field in enum._meta.db_table.replace(" ", "_"):
                atr = field;
        atr = atr + "_id"
        lookup = "%s__exact" % atr
        return MediaItem.objects.filter(**{lookup: enum.__getattribute__("id")})

    def get_enumeration(self, id):
        from django.db.models import get_models
        models = get_models(telemeta.models)
        for model in models:
            if model._meta.module_name == id:
                break
        if model._meta.module_name != id:
            return None
        return model

class ItemPublishedEnumListView(ItemEnumListView):
    def get_queryset(self):
        c = ItemEnumListView()
        #id of value of enumeration
        i = self.request.path.split('/')[4]
        enumeration = c.get_enumeration(self.request.path.split('/')[3])
        queryset = self.get_item(enumeration.objects.filter(id=i).get(), c)
        return queryset

    def get_item(self, enum, c):
        return c.get_item(enum).filter(code__contains='_E_')


class ItemUnpublishedEnumListView(ItemEnumListView):
    def get_queryset(self):
        c = ItemEnumListView()
        #id of value of enumeration
        i= self.request.path.split('/')[4]
        enumeration = c.get_enumeration(self.request.path.split('/')[3])
        queryset = self.get_item(enumeration.objects.filter(id=i).get(), c)
        return queryset

    def get_item(self, enum, c):
        return c.get_item(enum).filter(code__contains='_I_')


class ItemSoundEnumListView(ItemEnumListView):
    def get_queryset(self):
        c = ItemEnumListView()
        #id of value of enumeration
        i= self.request.path.split('/')[4]
        enumeration = c.get_enumeration(self.request.path.split('/')[3])
        queryset = self.get_item(enumeration.objects.filter(id=i).get(), c)
        return queryset

    def get_item(self, enum, c):
        return c.get_item(enum).sound().order_by('code', 'old_code')


class ItemKeywordListView(ItemListView):
    template_name = 'telemeta/media_item_enum_list.html'


    def get_context_data(self, **kwargs):
        context = super(ItemListView, self).get_context_data(**kwargs)
        context['enum'] = self.request.path.split('/')[3]
        context['id'] = self.request.path.split('/')[4]
        context['count'] = self.object_list.count()
        context['keyword'] = True
        context['enum_name'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name
        context['enum_value'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4])
        context['url_all'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item/list"
        context['url_unpublished'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_unpublished/list/"
        context['url_published'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_published/list/"
        context['url_sound'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_published/list/"

        context['argument'] = [context['enum'], context['id']]

        return context

    def get_queryset(self):
        queryset = self.get_item(self.request.path.split('/')[4])
        return queryset

    def get_item(self, id):
        c = []
        for m  in MediaItemKeyword.objects.filter(keyword_id=id):
            c.append(m.__getattribute__("item_id"))
        return  MediaItem.objects.filter(id__in=c)


    def get_enumeration(self, id):
        from django.db.models import get_models
        models = get_models(telemeta.models)
        for model in models:
            if model._meta.module_name == id:
                break
        if model._meta.module_name != id:
            return None
        return model

class ItemKeywordPublishedListView(ItemKeywordListView):

    def get_queryset(self):
        c=ItemKeywordListView()
        queryset = self.get_item(self.request.path.split('/')[4],c)
        return queryset

    def get_item(self, id,c):
        return c.get_item(id).filter(code__contains='_E_')

class ItemKeywordUnpublishedListView(ItemKeywordListView):

    def get_queryset(self):
        c=ItemKeywordListView()
        queryset = self.get_item(self.request.path.split('/')[4],c)
        return queryset

    def get_item(self, id,c):
        return c.get_item(id).filter(code__contains='_I_')

class ItemKeywordSoundListView(ItemKeywordListView):

    def get_queryset(self):
        c = ItemKeywordListView()
        queryset = self.get_item(self.request.path.split('/')[4], c)
        return queryset

    def get_item(self, id, c):
        return c.get_item(id).sound().order_by('code', 'old_code')

Module variables

var ITEM_PUBLIC_ACCESS_CHOICES

var ITEM_TRANSODING_STATUS

var PUBLIC_ACCESS_CHOICES

var SCOPE_CHOICES

var TYPE_CHOICES

var app_name

var code_linesep

var collection_code_regex

var collection_published_code_regex

var collection_unpublished_code_regex

var default_decoding

var default_encoding

var engine

var eol

var ext

var item_code_regex

var item_published_code_regex

var item_unpublished_code_regex

var mime_type

var mods

var private_extra_types

var public_extra_types

var resource_code_regex

var strict_code

Classes

class DublinCoreToFormatMetadata

a mapping class to get item DublinCore metadata dictionaries in various audio metadata format (MP3, OGG, etc...)

class DublinCoreToFormatMetadata(object):
    """a mapping class to get item DublinCore metadata dictionaries
    in various audio metadata format (MP3, OGG, etc...)"""

    # FIXME: should be given by timeside
    unavailable_extensions = ['wav', 'aiff', 'aif', 'flac', 'webm']

    metadata_mapping = {
        'mp3': {
            'title': 'TIT2',  # title2
            'creator': 'TCOM',  # composer
            'creator': 'TPE1',  # lead
            'identifier': 'UFID',  # unique ID
            'relation': 'TALB',  # album
            'type': 'TCON',  # genre
            'publisher': 'TPUB',  # publisher
                         'date': 'TDRC',  # year
            #                         'coverage': 'COMM',  #comment
        },
        'ogg': {
            'creator': 'artist',
            'relation': 'album',
                        'all': 'all',
        },
        'flac': {
            'creator': 'artist',
            'relation': 'album',
                        'all': 'all',
        },
        'wav': {
            'creator': 'artist',
            'relation': 'album',
                        'all': 'all',
        },
        'webm': {
            'creator': 'artist',
            'relation': 'album',
                        'all': 'all',
        },
    }

    def __init__(self, format):
        self.format = format

    def get_metadata(self, dc_metadata):
        mapp = self.metadata_mapping[self.format]
        metadata = {}
        keys_done = []
        for data in dc_metadata:
            key = data[0]
            value = data[1].encode('utf-8')
            if value:
                if key == 'date':
                    value = value.split(';')[0].split('=')
                    if len(value) > 1:
                        value = value[1]
                        value = value.split('-')[0]
                    else:
                        value = value[0].split('-')[0]
                if key in mapp:
                    metadata[mapp[key]] = value.decode('utf-8')
                elif 'all' in mapp.keys():
                    metadata[key] = value.decode('utf-8')
                keys_done.append(key)
        return metadata

Ancestors (in MRO)

Class variables

var metadata_mapping

var unavailable_extensions

Instance variables

var format

Methods

def __init__(

self, format)

def __init__(self, format):
    self.format = format

def get_metadata(

self, dc_metadata)

def get_metadata(self, dc_metadata):
    mapp = self.metadata_mapping[self.format]
    metadata = {}
    keys_done = []
    for data in dc_metadata:
        key = data[0]
        value = data[1].encode('utf-8')
        if value:
            if key == 'date':
                value = value.split(';')[0].split('=')
                if len(value) > 1:
                    value = value[1]
                    value = value.split('-')[0]
                else:
                    value = value[0].split('-')[0]
            if key in mapp:
                metadata[mapp[key]] = value.decode('utf-8')
            elif 'all' in mapp.keys():
                metadata[key] = value.decode('utf-8')
            keys_done.append(key)
    return metadata

class ItemAddView

class ItemAddView(ItemViewMixin, CreateWithInlinesView):

    form_class = MediaItemForm
    template_name = 'telemeta/mediaitem_add.html'

    def get_initial(self):
        item = self.model()
        # new item for a specific collection
        if 'public_id' in self.kwargs:
            public_id = self.kwargs['public_id']
            collections = MediaCollection.objects.filter(code=public_id)
            if collections:
                collection = collections[0]
                item.collection = collection
                items = MediaItem.objects.filter(collection=collection)
                item.code = auto_code(collection)
        return model_to_dict(item)

    def forms_valid(self, form, inlines):
        messages.info(self.request, ugettext_lazy("You have successfully added your item."))
        obj = form.save()
        obj.set_revision(self.request.user)
        return super(ItemAddView, self).forms_valid(form, inlines)

    def get_success_url(self):
        return reverse_lazy('telemeta-item-detail', kwargs={'public_id': self.object.code})

    @method_decorator(permission_required('telemeta.add_mediaitem'))
    def dispatch(self, *args, **kwargs):
        return super(ItemAddView, self).dispatch(*args, **kwargs)

Ancestors (in MRO)

  • ItemAddView
  • ItemViewMixin
  • ItemBaseMixin
  • telemeta.views.core.TelemetaBaseMixin
  • extra_views.advanced.CreateWithInlinesView
  • django.views.generic.detail.SingleObjectTemplateResponseMixin
  • extra_views.advanced.BaseCreateWithInlinesView
  • extra_views.advanced.ModelFormWithInlinesMixin
  • django.views.generic.edit.ModelFormMixin
  • extra_views.advanced.ProcessFormWithInlinesView
  • django.views.generic.edit.FormView
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.edit.BaseFormView
  • django.views.generic.edit.FormMixin
  • django.views.generic.detail.SingleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.edit.ProcessFormView
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var CACHE_DIR

Inheritance: ItemViewMixin.CACHE_DIR

var MEDIA_ROOT

Inheritance: ItemViewMixin.MEDIA_ROOT

var analyzers

Inheritance: ItemViewMixin.analyzers

var auto_zoom

Inheritance: ItemViewMixin.auto_zoom

var cache_data

Inheritance: ItemViewMixin.cache_data

var cache_export

Inheritance: ItemViewMixin.cache_export

var cache_tmp

Inheritance: ItemViewMixin.cache_tmp

var content_type

var context_object_name

var decoders

Inheritance: ItemViewMixin.decoders

var default_grapher_id

Inheritance: ItemViewMixin.default_grapher_id

var default_grapher_sizes

Inheritance: ItemViewMixin.default_grapher_sizes

var encoders

Inheritance: ItemViewMixin.encoders

var export_enabled

Inheritance: ItemViewMixin.export_enabled

var export_formats

Inheritance: ItemViewMixin.export_formats

var fields

var form_class

Inheritance: ItemViewMixin.form_class

var graphers

Inheritance: ItemViewMixin.graphers

var http_method_names

var initial

var inlines

Inheritance: ItemViewMixin.inlines

var model

Inheritance: ItemViewMixin.model

var pk_url_kwarg

var prefix

var public_graphers

Inheritance: ItemViewMixin.public_graphers

var queryset

var response_class

var slug_field

var slug_url_kwarg

var success_url

var template_name

var template_name_field

var template_name_suffix

var value_analyzers

Inheritance: ItemViewMixin.value_analyzers

Methods

def __init__(

self, **kwargs)

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def construct_inlines(

self)

Returns the inline formset instances

def construct_inlines(self):
    """
    Returns the inline formset instances
    """
    inline_formsets = []
    for inline_class in self.get_inlines():
        inline_instance = inline_class(self.model, self.request, self.object, self.kwargs, self)
        inline_formset = inline_instance.construct_formset()
        inline_formsets.append(inline_formset)
    return inline_formsets

def dispatch(

self, *args, **kwargs)

def _wrapper(self, *args, **kwargs):
    @decorator
    def bound_func(*args2, **kwargs2):
        return func(self, *args2, **kwargs2)
    # bound_func has the signature that 'decorator' expects i.e.  no
    # 'self' argument, but it is a closure over self so it can call
    # 'func' correctly.
    return bound_func(*args, **kwargs)

def form_invalid(

self, form)

If the form is invalid, re-render the context data with the data-filled form and errors.

def form_invalid(self, form):
    """
    If the form is invalid, re-render the context data with the
    data-filled form and errors.
    """
    return self.render_to_response(self.get_context_data(form=form))

def form_valid(

self, form)

If the form is valid, save the associated model.

def form_valid(self, form):
    """
    If the form is valid, save the associated model.
    """
    self.object = form.save()
    return super(ModelFormMixin, self).form_valid(form)

def forms_invalid(

self, form, inlines)

If the form or formsets are invalid, re-render the context data with the data-filled form and formsets and errors.

def forms_invalid(self, form, inlines):
    """
    If the form or formsets are invalid, re-render the context data with the
    data-filled form and formsets and errors.
    """
    return self.render_to_response(self.get_context_data(form=form, inlines=inlines))

def forms_valid(

self, form, inlines)

def forms_valid(self, form, inlines):
    messages.info(self.request, ugettext_lazy("You have successfully added your item."))
    obj = form.save()
    obj.set_revision(self.request.user)
    return super(ItemAddView, self).forms_valid(form, inlines)

def get(

self, request, *args, **kwargs)

def get(self, request, *args, **kwargs):
    self.object = None
    return super(BaseCreateWithInlinesView, self).get(request, *args, **kwargs)

def get_context_data(

self, **kwargs)

Insert the single object into the context dict.

def get_context_data(self, **kwargs):
    """
    Insert the single object into the context dict.
    """
    context = {}
    if self.object:
        context['object'] = self.object
        context_object_name = self.get_context_object_name(self.object)
        if context_object_name:
            context[context_object_name] = self.object
    context.update(kwargs)
    return super(SingleObjectMixin, self).get_context_data(**context)

def get_context_object_name(

self, obj)

Get the name to use for the object.

def get_context_object_name(self, obj):
    """
    Get the name to use for the object.
    """
    if self.context_object_name:
        return self.context_object_name
    elif isinstance(obj, models.Model):
        return obj._meta.model_name
    else:
        return None

def get_export_formats(

self)

Inheritance: ItemViewMixin.get_export_formats

def get_export_formats(self):
    formats = []
    for encoder in self.encoders:
        if encoder.file_extension() in self.export_formats:
            formats.append({'name': encoder.format(),
                            'extension': encoder.file_extension()})
    return formats

def get_form(

self, form_class)

Returns an instance of the form to be used in this view.

def get_form(self, form_class):
    """
    Returns an instance of the form to be used in this view.
    """
    return form_class(**self.get_form_kwargs())

def get_form_class(

self)

Returns the form class to use in this view.

def get_form_class(self):
    """
    Returns the form class to use in this view.
    """
    if self.form_class:
        return self.form_class
    else:
        if self.model is not None:
            # If a model has been explicitly provided, use it
            model = self.model
        elif hasattr(self, 'object') and self.object is not None:
            # If this view is operating on a single object, use
            # the class of that object
            model = self.object.__class__
        else:
            # Try to get a queryset and extract the model class
            # from that
            model = self.get_queryset().model
        if self.fields is None:
            warnings.warn("Using ModelFormMixin (base class of %s) without "
                          "the 'fields' attribute is deprecated." % self.__class__.__name__,
                          PendingDeprecationWarning)
        return model_forms.modelform_factory(model, fields=self.fields)

def get_form_kwargs(

self)

Returns the keyword arguments for instantiating the form.

def get_form_kwargs(self):
    """
    Returns the keyword arguments for instantiating the form.
    """
    kwargs = super(ModelFormMixin, self).get_form_kwargs()
    kwargs.update({'instance': self.object})
    return kwargs

def get_grapher(

self, id)

Inheritance: ItemViewMixin.get_grapher

def get_grapher(self, id):
    for grapher in self.graphers:
        if grapher.id() == id:
            break
    return grapher

def get_graphers(

self)

Inheritance: ItemViewMixin.get_graphers

def get_graphers(self):
    graphers = []
    user = self.request.user
    graphers_access = (user.is_staff
                       or user.is_superuser
                       or user.has_perm('can_run_analysis'))
    for grapher in self.graphers:
        if (not graphers_access
            and grapher.id() not in self.public_graphers):
            continue
        if grapher.id() == self.default_grapher_id:
            graphers.insert(0, {'name': grapher.name(), 'id': grapher.id()})
        elif not hasattr(grapher, '_staging'):
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
        elif not grapher._staging:
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
    return graphers

def get_initial(

self)

def get_initial(self):
    item = self.model()
    # new item for a specific collection
    if 'public_id' in self.kwargs:
        public_id = self.kwargs['public_id']
        collections = MediaCollection.objects.filter(code=public_id)
        if collections:
            collection = collections[0]
            item.collection = collection
            items = MediaItem.objects.filter(collection=collection)
            item.code = auto_code(collection)
    return model_to_dict(item)

def get_inlines(

self)

Returns the inline formset classes

def get_inlines(self):
    """
    Returns the inline formset classes
    """
    return self.inlines

def get_is_transcoded_flag(

self, item, mime_type)

Inheritance: ItemViewMixin.get_is_transcoded_flag

def get_is_transcoded_flag(self, item, mime_type):
    try:
        is_transcoded_flag, c = MediaItemTranscodingFlag.objects.get_or_create(
            item=item,
            mime_type=mime_type,
            defaults={'value': False})
    except MediaItemTranscodingFlag.MultipleObjectsReturned:
        flags = MediaItemTranscodingFlag.objects.filter(
            item=item,
            mime_type=mime_type)
        value = all([f.value for f in flags])
        is_transcoded_flag = flags[0]
        is_transcoded_flag.value = value
        is_transcoded_flag.save()
        for f in flags[1:]:
            f.delete()
    return is_transcoded_flag

def get_item_file_url(

*a, **kw)

Inheritance: ItemViewMixin.get_item_file_url

@jsonrpc_method('telemeta.get_item_export_url')
def get_item_file_url(request, public_id, extension):
    return reverse('telemeta-item-export', kwargs={'public_id': public_id, 'extension': extension})

def get_object(

self)

Inheritance: ItemViewMixin.get_object

def get_object(self):
    obj = self.model.objects.filter(code=self.kwargs['public_id'])
    if not obj:
        if self.kwargs['public_id'].isdigit():
            try:
                obj = self.model.objects.get(id=self.kwargs['public_id'])
            except self.model.DoesNotExist:
                raise Http404
        else:
            raise Http404
    else:
        obj = obj[0]
    return obj

def get_prefix(

self)

Returns the prefix to use for forms on this view

def get_prefix(self):
    """
    Returns the prefix to use for forms on this view
    """
    return self.prefix

def get_queryset(

self)

Get the queryset to look an object up against. May not be called if get_object is overridden.

def get_queryset(self):
    """
    Get the queryset to look an object up against. May not be called if
    `get_object` is overridden.
    """
    if self.queryset is None:
        if self.model:
            return self.model._default_manager.all()
        else:
            raise ImproperlyConfigured("%(cls)s is missing a queryset. Define "
                                       "%(cls)s.model, %(cls)s.queryset, or override "
                                       "%(cls)s.get_queryset()." % {
                                            'cls': self.__class__.__name__
                                    })
    return self.queryset._clone()

def get_slug_field(

self)

Get the name of a slug field to be used to look up by slug.

def get_slug_field(self):
    """
    Get the name of a slug field to be used to look up by slug.
    """
    return self.slug_field

def get_success_url(

self)

def get_success_url(self):
    return reverse_lazy('telemeta-item-detail', kwargs={'public_id': self.object.code})

def get_template_names(

self)

Return a list of template names to be used for the request. May not be called if render_to_response is overridden. Returns the following list:

  • the value of template_name on the view (if provided)
  • the contents of the template_name_field field on the object instance that the view is operating upon (if available)
  • <app_label>/<model_name><template_name_suffix>.html
def get_template_names(self):
    """
    Return a list of template names to be used for the request. May not be
    called if render_to_response is overridden. Returns the following list:
    * the value of ``template_name`` on the view (if provided)
    * the contents of the ``template_name_field`` field on the
      object instance that the view is operating upon (if available)
    * ``<app_label>/<model_name><template_name_suffix>.html``
    """
    try:
        names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
        # If self.template_name_field is set, grab the value of the field
        # of that name from the object; this is the most specific template
        # name, if given.
        if self.object and self.template_name_field:
            name = getattr(self.object, self.template_name_field, None)
            if name:
                names.insert(0, name)
        # The least-specific option is the default <app>/<model>_detail.html;
        # only use this if the object in question is a model.
        if isinstance(self.object, models.Model):
            names.append("%s/%s%s.html" % (
                self.object._meta.app_label,
                self.object._meta.model_name,
                self.template_name_suffix
            ))
        elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model):
            names.append("%s/%s%s.html" % (
                self.model._meta.app_label,
                self.model._meta.model_name,
                self.template_name_suffix
            ))
        # If we still haven't managed to find any template names, we should
        # re-raise the ImproperlyConfigured to alert the user.
        if not names:
            raise
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def item_previous_next(

self, item)

Inheritance: ItemViewMixin.item_previous_next

Get previous and next items inside the collection of the item

def item_previous_next(self, item):
    """Get previous and next items inside the collection of the item"""
    pks = []
    items = MediaItem.objects.filter(collection=item.collection)
    items = items.order_by('code', 'old_code')
    if len(items) > 1:
        for it in items:
            pks.append(it.pk)
        for pk in pks:
            if pk == item.pk:
                if pk == pks[0]:
                    previous_pk = pks[-1]
                    next_pk = pks[1]
                elif pk == pks[-1]:
                    previous_pk = pks[-2]
                    next_pk = pks[0]
                else:
                    previous_pk = pks[pks.index(pk) - 1]
                    next_pk = pks[pks.index(pk) + 1]
                for it in items:
                    if it.pk == previous_pk:
                        previous = it
                    if it.pk == next_pk:
                        next = it
                previous = previous.public_id
                next = next.public_id
    else:
        previous = item.public_id
        next = item.public_id
    return previous, next

def options(

self, request, *args, **kwargs)

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def post(

self, request, *args, **kwargs)

def post(self, request, *args, **kwargs):
    self.object = None
    return super(BaseCreateWithInlinesView, self).post(request, *args, **kwargs)

def put(

self, *args, **kwargs)

def put(self, *args, **kwargs):
    return self.post(*args, **kwargs)

def render_to_response(

self, context, **response_kwargs)

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemAliasListView

class ItemAliasListView(ItemListView):

    template_name = "telemeta/media_item_alias_list.html"

    def get_queryset(self):
        return MediaItem.objects.filter(performances__alias__id=self.kwargs['value_id'])

    def get_context_data(self, **kwargs):
        context = super(ItemAliasListView, self).get_context_data(**kwargs)

        context['nom'] = InstrumentAlias.objects.get(id=self.kwargs['value_id']).name
        context['id'] = self.kwargs['value_id']

        return context

Ancestors (in MRO)

  • ItemAliasListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemListView.allow_empty

var content_type

Inheritance: ItemListView.content_type

var context_object_name

Inheritance: ItemListView.context_object_name

var http_method_names

Inheritance: ItemListView.http_method_names

var model

Inheritance: ItemListView.model

var page_kwarg

Inheritance: ItemListView.page_kwarg

var paginate_by

Inheritance: ItemListView.paginate_by

var paginate_orphans

Inheritance: ItemListView.paginate_orphans

var paginator_class

Inheritance: ItemListView.paginator_class

var queryset

Inheritance: ItemListView.queryset

var response_class

Inheritance: ItemListView.response_class

var template_name

Inheritance: ItemListView.template_name

var template_name_suffix

Inheritance: ItemListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemAliasListView, self).get_context_data(**kwargs)
    context['nom'] = InstrumentAlias.objects.get(id=self.kwargs['value_id']).name
    context['id'] = self.kwargs['value_id']
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

Inheritance: ItemListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemListView.get_queryset

Get the list of items for this view. This must be an iterable, and may be a queryset (in which qs-specific behavior will be enabled).

def get_queryset(self):
    return MediaItem.objects.filter(performances__alias__id=self.kwargs['value_id'])

def get_template_names(

self)

Inheritance: ItemListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemAliasPublishedListView

class ItemAliasPublishedListView(ItemAliasListView):

    def get_queryset(self):
        return super(ItemAliasPublishedListView, self).get_queryset().filter(collection__code__contains='_E_').order_by('code', 'old_code')

Ancestors (in MRO)

  • ItemAliasPublishedListView
  • ItemAliasListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemAliasListView.allow_empty

var content_type

Inheritance: ItemAliasListView.content_type

var context_object_name

Inheritance: ItemAliasListView.context_object_name

var http_method_names

Inheritance: ItemAliasListView.http_method_names

var model

Inheritance: ItemAliasListView.model

var page_kwarg

Inheritance: ItemAliasListView.page_kwarg

var paginate_by

Inheritance: ItemAliasListView.paginate_by

var paginate_orphans

Inheritance: ItemAliasListView.paginate_orphans

var paginator_class

Inheritance: ItemAliasListView.paginator_class

var queryset

Inheritance: ItemAliasListView.queryset

var response_class

Inheritance: ItemAliasListView.response_class

var template_name

Inheritance: ItemAliasListView.template_name

var template_name_suffix

Inheritance: ItemAliasListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemAliasListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemAliasListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemAliasListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemAliasListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemAliasListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemAliasListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemAliasListView, self).get_context_data(**kwargs)
    context['nom'] = InstrumentAlias.objects.get(id=self.kwargs['value_id']).name
    context['id'] = self.kwargs['value_id']
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemAliasListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

Inheritance: ItemAliasListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemAliasListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemAliasListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemAliasListView.get_queryset

def get_queryset(self):
    return super(ItemAliasPublishedListView, self).get_queryset().filter(collection__code__contains='_E_').order_by('code', 'old_code')

def get_template_names(

self)

Inheritance: ItemAliasListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemAliasListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemAliasListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemAliasListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemAliasListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemAliasSoundListView

class ItemAliasSoundListView(ItemAliasListView):

    def get_queryset(self):
        return super(ItemAliasSoundListView, self).get_queryset().sound().order_by('code', 'old_code')

Ancestors (in MRO)

  • ItemAliasSoundListView
  • ItemAliasListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemAliasListView.allow_empty

var content_type

Inheritance: ItemAliasListView.content_type

var context_object_name

Inheritance: ItemAliasListView.context_object_name

var http_method_names

Inheritance: ItemAliasListView.http_method_names

var model

Inheritance: ItemAliasListView.model

var page_kwarg

Inheritance: ItemAliasListView.page_kwarg

var paginate_by

Inheritance: ItemAliasListView.paginate_by

var paginate_orphans

Inheritance: ItemAliasListView.paginate_orphans

var paginator_class

Inheritance: ItemAliasListView.paginator_class

var queryset

Inheritance: ItemAliasListView.queryset

var response_class

Inheritance: ItemAliasListView.response_class

var template_name

Inheritance: ItemAliasListView.template_name

var template_name_suffix

Inheritance: ItemAliasListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemAliasListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemAliasListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemAliasListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemAliasListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemAliasListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemAliasListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemAliasListView, self).get_context_data(**kwargs)
    context['nom'] = InstrumentAlias.objects.get(id=self.kwargs['value_id']).name
    context['id'] = self.kwargs['value_id']
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemAliasListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

Inheritance: ItemAliasListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemAliasListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemAliasListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemAliasListView.get_queryset

def get_queryset(self):
    return super(ItemAliasSoundListView, self).get_queryset().sound().order_by('code', 'old_code')

def get_template_names(

self)

Inheritance: ItemAliasListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemAliasListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemAliasListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemAliasListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemAliasListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemAliasUnpublishedListView

class ItemAliasUnpublishedListView(ItemAliasListView):

    def get_queryset(self):
        return super(ItemAliasUnpublishedListView, self).get_queryset().filter(collection__code__contains='_I_').order_by('code', 'old_code')

Ancestors (in MRO)

  • ItemAliasUnpublishedListView
  • ItemAliasListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemAliasListView.allow_empty

var content_type

Inheritance: ItemAliasListView.content_type

var context_object_name

Inheritance: ItemAliasListView.context_object_name

var http_method_names

Inheritance: ItemAliasListView.http_method_names

var model

Inheritance: ItemAliasListView.model

var page_kwarg

Inheritance: ItemAliasListView.page_kwarg

var paginate_by

Inheritance: ItemAliasListView.paginate_by

var paginate_orphans

Inheritance: ItemAliasListView.paginate_orphans

var paginator_class

Inheritance: ItemAliasListView.paginator_class

var queryset

Inheritance: ItemAliasListView.queryset

var response_class

Inheritance: ItemAliasListView.response_class

var template_name

Inheritance: ItemAliasListView.template_name

var template_name_suffix

Inheritance: ItemAliasListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemAliasListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemAliasListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemAliasListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemAliasListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemAliasListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemAliasListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemAliasListView, self).get_context_data(**kwargs)
    context['nom'] = InstrumentAlias.objects.get(id=self.kwargs['value_id']).name
    context['id'] = self.kwargs['value_id']
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemAliasListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

Inheritance: ItemAliasListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemAliasListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemAliasListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemAliasListView.get_queryset

def get_queryset(self):
    return super(ItemAliasUnpublishedListView, self).get_queryset().filter(collection__code__contains='_I_').order_by('code', 'old_code')

def get_template_names(

self)

Inheritance: ItemAliasListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemAliasListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemAliasListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemAliasListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemAliasListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemBaseMixin

class ItemBaseMixin(TelemetaBaseMixin):

    graphers = timeside.core.processor.processors(timeside.core.api.IGrapher)
    decoders = timeside.core.processor.processors(timeside.core.api.IDecoder)
    encoders = timeside.core.processor.processors(timeside.core.api.IEncoder)
    analyzers = timeside.core.processor.processors(timeside.core.api.IAnalyzer)
    value_analyzers = timeside.core.processor.processors(timeside.core.api.IValueAnalyzer)

    export_enabled = getattr(settings, 'TELEMETA_DOWNLOAD_ENABLED', True)
    export_formats = getattr(settings, 'TELEMETA_DOWNLOAD_FORMATS', ('mp3', 'wav'))
    default_grapher_id = getattr(settings, 'TIMESIDE_DEFAULT_GRAPHER_ID', ('waveform_simple'))
    default_grapher_sizes = getattr(settings, 'TIMESIDE_DEFAULT_GRAPHER_SIZES', ['346x130', ])
    auto_zoom = getattr(settings, 'TIMESIDE_AUTO_ZOOM', False)

    public_graphers  = ['waveform_centroid' ,'waveform_simple',
                        'spectrogram', 'spectrogram_log']

    def get_graphers(self):
        graphers = []
        user = self.request.user
        graphers_access = (user.is_staff
                           or user.is_superuser
                           or user.has_perm('can_run_analysis'))

        for grapher in self.graphers:
            if (not graphers_access
                and grapher.id() not in self.public_graphers):
                continue
            if grapher.id() == self.default_grapher_id:
                graphers.insert(0, {'name': grapher.name(), 'id': grapher.id()})
            elif not hasattr(grapher, '_staging'):
                graphers.append({'name': grapher.name(), 'id': grapher.id()})
            elif not grapher._staging:
                graphers.append({'name': grapher.name(), 'id': grapher.id()})
        return graphers

    def get_grapher(self, id):
        for grapher in self.graphers:
            if grapher.id() == id:
                break
        return grapher

    def get_export_formats(self):
        formats = []
        for encoder in self.encoders:
            if encoder.file_extension() in self.export_formats:
                formats.append({'name': encoder.format(),
                                'extension': encoder.file_extension()})
        return formats

    def get_is_transcoded_flag(self, item, mime_type):
        try:
            is_transcoded_flag, c = MediaItemTranscodingFlag.objects.get_or_create(
                item=item,
                mime_type=mime_type,
                defaults={'value': False})
        except MediaItemTranscodingFlag.MultipleObjectsReturned:
            flags = MediaItemTranscodingFlag.objects.filter(
                item=item,
                mime_type=mime_type)
            value = all([f.value for f in flags])
            is_transcoded_flag = flags[0]
            is_transcoded_flag.value = value
            is_transcoded_flag.save()
            for f in flags[1:]:
                f.delete()
        return is_transcoded_flag

    def item_previous_next(self, item):
        """Get previous and next items inside the collection of the item"""

        pks = []
        items = MediaItem.objects.filter(collection=item.collection)
        items = items.order_by('code', 'old_code')

        if len(items) > 1:
            for it in items:
                pks.append(it.pk)
            for pk in pks:
                if pk == item.pk:
                    if pk == pks[0]:
                        previous_pk = pks[-1]
                        next_pk = pks[1]
                    elif pk == pks[-1]:
                        previous_pk = pks[-2]
                        next_pk = pks[0]
                    else:
                        previous_pk = pks[pks.index(pk) - 1]
                        next_pk = pks[pks.index(pk) + 1]
                    for it in items:
                        if it.pk == previous_pk:
                            previous = it
                        if it.pk == next_pk:
                            next = it
                    previous = previous.public_id
                    next = next.public_id
        else:
            previous = item.public_id
            next = item.public_id
        return previous, next

    @jsonrpc_method('telemeta.get_item_export_url')
    def get_item_file_url(request, public_id, extension):
        return reverse('telemeta-item-export', kwargs={'public_id': public_id, 'extension': extension})

Ancestors (in MRO)

  • ItemBaseMixin
  • telemeta.views.core.TelemetaBaseMixin
  • __builtin__.object

Class variables

var CACHE_DIR

var MEDIA_ROOT

var analyzers

var auto_zoom

var cache_data

var cache_export

var cache_tmp

var decoders

var default_grapher_id

var default_grapher_sizes

var encoders

var export_enabled

var export_formats

var graphers

var public_graphers

var value_analyzers

Methods

def get_export_formats(

self)

def get_export_formats(self):
    formats = []
    for encoder in self.encoders:
        if encoder.file_extension() in self.export_formats:
            formats.append({'name': encoder.format(),
                            'extension': encoder.file_extension()})
    return formats

def get_grapher(

self, id)

def get_grapher(self, id):
    for grapher in self.graphers:
        if grapher.id() == id:
            break
    return grapher

def get_graphers(

self)

def get_graphers(self):
    graphers = []
    user = self.request.user
    graphers_access = (user.is_staff
                       or user.is_superuser
                       or user.has_perm('can_run_analysis'))
    for grapher in self.graphers:
        if (not graphers_access
            and grapher.id() not in self.public_graphers):
            continue
        if grapher.id() == self.default_grapher_id:
            graphers.insert(0, {'name': grapher.name(), 'id': grapher.id()})
        elif not hasattr(grapher, '_staging'):
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
        elif not grapher._staging:
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
    return graphers

def get_is_transcoded_flag(

self, item, mime_type)

def get_is_transcoded_flag(self, item, mime_type):
    try:
        is_transcoded_flag, c = MediaItemTranscodingFlag.objects.get_or_create(
            item=item,
            mime_type=mime_type,
            defaults={'value': False})
    except MediaItemTranscodingFlag.MultipleObjectsReturned:
        flags = MediaItemTranscodingFlag.objects.filter(
            item=item,
            mime_type=mime_type)
        value = all([f.value for f in flags])
        is_transcoded_flag = flags[0]
        is_transcoded_flag.value = value
        is_transcoded_flag.save()
        for f in flags[1:]:
            f.delete()
    return is_transcoded_flag

def get_item_file_url(

*a, **kw)

@jsonrpc_method('telemeta.get_item_export_url')
def get_item_file_url(request, public_id, extension):
    return reverse('telemeta-item-export', kwargs={'public_id': public_id, 'extension': extension})

def item_previous_next(

self, item)

Get previous and next items inside the collection of the item

def item_previous_next(self, item):
    """Get previous and next items inside the collection of the item"""
    pks = []
    items = MediaItem.objects.filter(collection=item.collection)
    items = items.order_by('code', 'old_code')
    if len(items) > 1:
        for it in items:
            pks.append(it.pk)
        for pk in pks:
            if pk == item.pk:
                if pk == pks[0]:
                    previous_pk = pks[-1]
                    next_pk = pks[1]
                elif pk == pks[-1]:
                    previous_pk = pks[-2]
                    next_pk = pks[0]
                else:
                    previous_pk = pks[pks.index(pk) - 1]
                    next_pk = pks[pks.index(pk) + 1]
                for it in items:
                    if it.pk == previous_pk:
                        previous = it
                    if it.pk == next_pk:
                        next = it
                previous = previous.public_id
                next = next.public_id
    else:
        previous = item.public_id
        next = item.public_id
    return previous, next

class ItemCopyView

class ItemCopyView(ItemAddView):

    form_class = MediaItemForm
    template_name = 'telemeta/mediaitem_edit.html'

    def get_initial(self):
        item = self.get_object()
        item.code = auto_code(item.collection)
        return model_to_dict(item)

    def forms_valid(self, form, inlines):
        messages.info(self.request, ugettext_lazy("You have successfully updated your item."))
        item = form.save()
        item.set_revision(self.request.user)
        if not MediaItemPerformance.objects.filter(media_item=item):
            for performance in MediaItemPerformance.objects.filter(media_item=self.get_object()):
                performance.pk = None
                performance.id = None
                performance.media_item = item
                performance.save()
        if not MediaItemKeyword.objects.filter(item=item):
            for keyword in MediaItemKeyword.objects.filter(item=self.get_object()):
                keyword.pk = None
                keyword.id = None
                keyword.item = item
                keyword.save()
        return super(ItemCopyView, self).forms_valid(form, inlines)

    def get_success_url(self):
        return reverse_lazy('telemeta-item-detail', kwargs={'public_id': self.object.code})

    def get_context_data(self, **kwargs):
        context = super(ItemCopyView, self).get_context_data(**kwargs)
        item = self.get_object()
        context['item'] = item
        context['access'] = get_item_access(item, self.request.user)
        context['previous'], context['next'] = self.item_previous_next(item)
        # FIXME
        context['mime_type'] = 'audio/mp3'
        context['export_formats'] = self.get_export_formats()
        context['visualizers'] = self.get_graphers()
        context['audio_export_enabled'] = self.export_enabled
        context['auto_zoom'] = True
        return context

    @method_decorator(permission_required('telemeta.add_mediaitem'))
    def dispatch(self, *args, **kwargs):
        return super(ItemCopyView, self).dispatch(*args, **kwargs)

Ancestors (in MRO)

  • ItemCopyView
  • ItemAddView
  • ItemViewMixin
  • ItemBaseMixin
  • telemeta.views.core.TelemetaBaseMixin
  • extra_views.advanced.CreateWithInlinesView
  • django.views.generic.detail.SingleObjectTemplateResponseMixin
  • extra_views.advanced.BaseCreateWithInlinesView
  • extra_views.advanced.ModelFormWithInlinesMixin
  • django.views.generic.edit.ModelFormMixin
  • extra_views.advanced.ProcessFormWithInlinesView
  • django.views.generic.edit.FormView
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.edit.BaseFormView
  • django.views.generic.edit.FormMixin
  • django.views.generic.detail.SingleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.edit.ProcessFormView
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var CACHE_DIR

Inheritance: ItemAddView.CACHE_DIR

var MEDIA_ROOT

Inheritance: ItemAddView.MEDIA_ROOT

var analyzers

Inheritance: ItemAddView.analyzers

var auto_zoom

Inheritance: ItemAddView.auto_zoom

var cache_data

Inheritance: ItemAddView.cache_data

var cache_export

Inheritance: ItemAddView.cache_export

var cache_tmp

Inheritance: ItemAddView.cache_tmp

var content_type

Inheritance: ItemAddView.content_type

var context_object_name

Inheritance: ItemAddView.context_object_name

var decoders

Inheritance: ItemAddView.decoders

var default_grapher_id

Inheritance: ItemAddView.default_grapher_id

var default_grapher_sizes

Inheritance: ItemAddView.default_grapher_sizes

var encoders

Inheritance: ItemAddView.encoders

var export_enabled

Inheritance: ItemAddView.export_enabled

var export_formats

Inheritance: ItemAddView.export_formats

var fields

Inheritance: ItemAddView.fields

var form_class

Inheritance: ItemAddView.form_class

var graphers

Inheritance: ItemAddView.graphers

var http_method_names

Inheritance: ItemAddView.http_method_names

var initial

Inheritance: ItemAddView.initial

var inlines

Inheritance: ItemAddView.inlines

var model

Inheritance: ItemAddView.model

var pk_url_kwarg

Inheritance: ItemAddView.pk_url_kwarg

var prefix

Inheritance: ItemAddView.prefix

var public_graphers

Inheritance: ItemAddView.public_graphers

var queryset

Inheritance: ItemAddView.queryset

var response_class

Inheritance: ItemAddView.response_class

var slug_field

Inheritance: ItemAddView.slug_field

var slug_url_kwarg

Inheritance: ItemAddView.slug_url_kwarg

var success_url

Inheritance: ItemAddView.success_url

var template_name

Inheritance: ItemAddView.template_name

var template_name_field

Inheritance: ItemAddView.template_name_field

var template_name_suffix

Inheritance: ItemAddView.template_name_suffix

var value_analyzers

Inheritance: ItemAddView.value_analyzers

Methods

def __init__(

self, **kwargs)

Inheritance: ItemAddView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemAddView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def construct_inlines(

self)

Inheritance: ItemAddView.construct_inlines

Returns the inline formset instances

def construct_inlines(self):
    """
    Returns the inline formset instances
    """
    inline_formsets = []
    for inline_class in self.get_inlines():
        inline_instance = inline_class(self.model, self.request, self.object, self.kwargs, self)
        inline_formset = inline_instance.construct_formset()
        inline_formsets.append(inline_formset)
    return inline_formsets

def dispatch(

self, *args, **kwargs)

Inheritance: ItemAddView.dispatch

def _wrapper(self, *args, **kwargs):
    @decorator
    def bound_func(*args2, **kwargs2):
        return func(self, *args2, **kwargs2)
    # bound_func has the signature that 'decorator' expects i.e.  no
    # 'self' argument, but it is a closure over self so it can call
    # 'func' correctly.
    return bound_func(*args, **kwargs)

def form_invalid(

self, form)

Inheritance: ItemAddView.form_invalid

If the form is invalid, re-render the context data with the data-filled form and errors.

def form_invalid(self, form):
    """
    If the form is invalid, re-render the context data with the
    data-filled form and errors.
    """
    return self.render_to_response(self.get_context_data(form=form))

def form_valid(

self, form)

Inheritance: ItemAddView.form_valid

If the form is valid, save the associated model.

def form_valid(self, form):
    """
    If the form is valid, save the associated model.
    """
    self.object = form.save()
    return super(ModelFormMixin, self).form_valid(form)

def forms_invalid(

self, form, inlines)

Inheritance: ItemAddView.forms_invalid

If the form or formsets are invalid, re-render the context data with the data-filled form and formsets and errors.

def forms_invalid(self, form, inlines):
    """
    If the form or formsets are invalid, re-render the context data with the
    data-filled form and formsets and errors.
    """
    return self.render_to_response(self.get_context_data(form=form, inlines=inlines))

def forms_valid(

self, form, inlines)

Inheritance: ItemAddView.forms_valid

def forms_valid(self, form, inlines):
    messages.info(self.request, ugettext_lazy("You have successfully updated your item."))
    item = form.save()
    item.set_revision(self.request.user)
    if not MediaItemPerformance.objects.filter(media_item=item):
        for performance in MediaItemPerformance.objects.filter(media_item=self.get_object()):
            performance.pk = None
            performance.id = None
            performance.media_item = item
            performance.save()
    if not MediaItemKeyword.objects.filter(item=item):
        for keyword in MediaItemKeyword.objects.filter(item=self.get_object()):
            keyword.pk = None
            keyword.id = None
            keyword.item = item
            keyword.save()
    return super(ItemCopyView, self).forms_valid(form, inlines)

def get(

self, request, *args, **kwargs)

Inheritance: ItemAddView.get

def get(self, request, *args, **kwargs):
    self.object = None
    return super(BaseCreateWithInlinesView, self).get(request, *args, **kwargs)

def get_context_data(

self, **kwargs)

Inheritance: ItemAddView.get_context_data

Insert the single object into the context dict.

def get_context_data(self, **kwargs):
    context = super(ItemCopyView, self).get_context_data(**kwargs)
    item = self.get_object()
    context['item'] = item
    context['access'] = get_item_access(item, self.request.user)
    context['previous'], context['next'] = self.item_previous_next(item)
    # FIXME
    context['mime_type'] = 'audio/mp3'
    context['export_formats'] = self.get_export_formats()
    context['visualizers'] = self.get_graphers()
    context['audio_export_enabled'] = self.export_enabled
    context['auto_zoom'] = True
    return context

def get_context_object_name(

self, obj)

Inheritance: ItemAddView.get_context_object_name

Get the name to use for the object.

def get_context_object_name(self, obj):
    """
    Get the name to use for the object.
    """
    if self.context_object_name:
        return self.context_object_name
    elif isinstance(obj, models.Model):
        return obj._meta.model_name
    else:
        return None

def get_export_formats(

self)

Inheritance: ItemAddView.get_export_formats

def get_export_formats(self):
    formats = []
    for encoder in self.encoders:
        if encoder.file_extension() in self.export_formats:
            formats.append({'name': encoder.format(),
                            'extension': encoder.file_extension()})
    return formats

def get_form(

self, form_class)

Inheritance: ItemAddView.get_form

Returns an instance of the form to be used in this view.

def get_form(self, form_class):
    """
    Returns an instance of the form to be used in this view.
    """
    return form_class(**self.get_form_kwargs())

def get_form_class(

self)

Inheritance: ItemAddView.get_form_class

Returns the form class to use in this view.

def get_form_class(self):
    """
    Returns the form class to use in this view.
    """
    if self.form_class:
        return self.form_class
    else:
        if self.model is not None:
            # If a model has been explicitly provided, use it
            model = self.model
        elif hasattr(self, 'object') and self.object is not None:
            # If this view is operating on a single object, use
            # the class of that object
            model = self.object.__class__
        else:
            # Try to get a queryset and extract the model class
            # from that
            model = self.get_queryset().model
        if self.fields is None:
            warnings.warn("Using ModelFormMixin (base class of %s) without "
                          "the 'fields' attribute is deprecated." % self.__class__.__name__,
                          PendingDeprecationWarning)
        return model_forms.modelform_factory(model, fields=self.fields)

def get_form_kwargs(

self)

Inheritance: ItemAddView.get_form_kwargs

Returns the keyword arguments for instantiating the form.

def get_form_kwargs(self):
    """
    Returns the keyword arguments for instantiating the form.
    """
    kwargs = super(ModelFormMixin, self).get_form_kwargs()
    kwargs.update({'instance': self.object})
    return kwargs

def get_grapher(

self, id)

Inheritance: ItemAddView.get_grapher

def get_grapher(self, id):
    for grapher in self.graphers:
        if grapher.id() == id:
            break
    return grapher

def get_graphers(

self)

Inheritance: ItemAddView.get_graphers

def get_graphers(self):
    graphers = []
    user = self.request.user
    graphers_access = (user.is_staff
                       or user.is_superuser
                       or user.has_perm('can_run_analysis'))
    for grapher in self.graphers:
        if (not graphers_access
            and grapher.id() not in self.public_graphers):
            continue
        if grapher.id() == self.default_grapher_id:
            graphers.insert(0, {'name': grapher.name(), 'id': grapher.id()})
        elif not hasattr(grapher, '_staging'):
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
        elif not grapher._staging:
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
    return graphers

def get_initial(

self)

Inheritance: ItemAddView.get_initial

def get_initial(self):
    item = self.get_object()
    item.code = auto_code(item.collection)
    return model_to_dict(item)

def get_inlines(

self)

Inheritance: ItemAddView.get_inlines

Returns the inline formset classes

def get_inlines(self):
    """
    Returns the inline formset classes
    """
    return self.inlines

def get_is_transcoded_flag(

self, item, mime_type)

Inheritance: ItemAddView.get_is_transcoded_flag

def get_is_transcoded_flag(self, item, mime_type):
    try:
        is_transcoded_flag, c = MediaItemTranscodingFlag.objects.get_or_create(
            item=item,
            mime_type=mime_type,
            defaults={'value': False})
    except MediaItemTranscodingFlag.MultipleObjectsReturned:
        flags = MediaItemTranscodingFlag.objects.filter(
            item=item,
            mime_type=mime_type)
        value = all([f.value for f in flags])
        is_transcoded_flag = flags[0]
        is_transcoded_flag.value = value
        is_transcoded_flag.save()
        for f in flags[1:]:
            f.delete()
    return is_transcoded_flag

def get_item_file_url(

*a, **kw)

Inheritance: ItemAddView.get_item_file_url

@jsonrpc_method('telemeta.get_item_export_url')
def get_item_file_url(request, public_id, extension):
    return reverse('telemeta-item-export', kwargs={'public_id': public_id, 'extension': extension})

def get_object(

self)

Inheritance: ItemAddView.get_object

def get_object(self):
    obj = self.model.objects.filter(code=self.kwargs['public_id'])
    if not obj:
        if self.kwargs['public_id'].isdigit():
            try:
                obj = self.model.objects.get(id=self.kwargs['public_id'])
            except self.model.DoesNotExist:
                raise Http404
        else:
            raise Http404
    else:
        obj = obj[0]
    return obj

def get_prefix(

self)

Inheritance: ItemAddView.get_prefix

Returns the prefix to use for forms on this view

def get_prefix(self):
    """
    Returns the prefix to use for forms on this view
    """
    return self.prefix

def get_queryset(

self)

Inheritance: ItemAddView.get_queryset

Get the queryset to look an object up against. May not be called if get_object is overridden.

def get_queryset(self):
    """
    Get the queryset to look an object up against. May not be called if
    `get_object` is overridden.
    """
    if self.queryset is None:
        if self.model:
            return self.model._default_manager.all()
        else:
            raise ImproperlyConfigured("%(cls)s is missing a queryset. Define "
                                       "%(cls)s.model, %(cls)s.queryset, or override "
                                       "%(cls)s.get_queryset()." % {
                                            'cls': self.__class__.__name__
                                    })
    return self.queryset._clone()

def get_slug_field(

self)

Inheritance: ItemAddView.get_slug_field

Get the name of a slug field to be used to look up by slug.

def get_slug_field(self):
    """
    Get the name of a slug field to be used to look up by slug.
    """
    return self.slug_field

def get_success_url(

self)

Inheritance: ItemAddView.get_success_url

def get_success_url(self):
    return reverse_lazy('telemeta-item-detail', kwargs={'public_id': self.object.code})

def get_template_names(

self)

Inheritance: ItemAddView.get_template_names

Return a list of template names to be used for the request. May not be called if render_to_response is overridden. Returns the following list:

  • the value of template_name on the view (if provided)
  • the contents of the template_name_field field on the object instance that the view is operating upon (if available)
  • <app_label>/<model_name><template_name_suffix>.html
def get_template_names(self):
    """
    Return a list of template names to be used for the request. May not be
    called if render_to_response is overridden. Returns the following list:
    * the value of ``template_name`` on the view (if provided)
    * the contents of the ``template_name_field`` field on the
      object instance that the view is operating upon (if available)
    * ``<app_label>/<model_name><template_name_suffix>.html``
    """
    try:
        names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
        # If self.template_name_field is set, grab the value of the field
        # of that name from the object; this is the most specific template
        # name, if given.
        if self.object and self.template_name_field:
            name = getattr(self.object, self.template_name_field, None)
            if name:
                names.insert(0, name)
        # The least-specific option is the default <app>/<model>_detail.html;
        # only use this if the object in question is a model.
        if isinstance(self.object, models.Model):
            names.append("%s/%s%s.html" % (
                self.object._meta.app_label,
                self.object._meta.model_name,
                self.template_name_suffix
            ))
        elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model):
            names.append("%s/%s%s.html" % (
                self.model._meta.app_label,
                self.model._meta.model_name,
                self.template_name_suffix
            ))
        # If we still haven't managed to find any template names, we should
        # re-raise the ImproperlyConfigured to alert the user.
        if not names:
            raise
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemAddView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def item_previous_next(

self, item)

Inheritance: ItemAddView.item_previous_next

Get previous and next items inside the collection of the item

def item_previous_next(self, item):
    """Get previous and next items inside the collection of the item"""
    pks = []
    items = MediaItem.objects.filter(collection=item.collection)
    items = items.order_by('code', 'old_code')
    if len(items) > 1:
        for it in items:
            pks.append(it.pk)
        for pk in pks:
            if pk == item.pk:
                if pk == pks[0]:
                    previous_pk = pks[-1]
                    next_pk = pks[1]
                elif pk == pks[-1]:
                    previous_pk = pks[-2]
                    next_pk = pks[0]
                else:
                    previous_pk = pks[pks.index(pk) - 1]
                    next_pk = pks[pks.index(pk) + 1]
                for it in items:
                    if it.pk == previous_pk:
                        previous = it
                    if it.pk == next_pk:
                        next = it
                previous = previous.public_id
                next = next.public_id
    else:
        previous = item.public_id
        next = item.public_id
    return previous, next

def options(

self, request, *args, **kwargs)

Inheritance: ItemAddView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def post(

self, request, *args, **kwargs)

Inheritance: ItemAddView.post

def post(self, request, *args, **kwargs):
    self.object = None
    return super(BaseCreateWithInlinesView, self).post(request, *args, **kwargs)

def put(

self, *args, **kwargs)

Inheritance: ItemAddView.put

def put(self, *args, **kwargs):
    return self.post(*args, **kwargs)

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemAddView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemDetailDCView

class ItemDetailDCView(ItemDetailView):

    template_name = 'telemeta/mediaitem_detail_dc.html'

Ancestors (in MRO)

  • ItemDetailDCView
  • ItemDetailView
  • ItemViewMixin
  • ItemBaseMixin
  • telemeta.views.core.TelemetaBaseMixin
  • django.views.generic.detail.DetailView
  • django.views.generic.detail.SingleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.detail.BaseDetailView
  • django.views.generic.detail.SingleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var CACHE_DIR

Inheritance: ItemDetailView.CACHE_DIR

var MEDIA_ROOT

Inheritance: ItemDetailView.MEDIA_ROOT

var analyzers

Inheritance: ItemDetailView.analyzers

var auto_zoom

Inheritance: ItemDetailView.auto_zoom

var cache_data

Inheritance: ItemDetailView.cache_data

var cache_export

Inheritance: ItemDetailView.cache_export

var cache_tmp

Inheritance: ItemDetailView.cache_tmp

var content_type

Inheritance: ItemDetailView.content_type

var context_object_name

Inheritance: ItemDetailView.context_object_name

var decoders

Inheritance: ItemDetailView.decoders

var default_grapher_id

Inheritance: ItemDetailView.default_grapher_id

var default_grapher_sizes

Inheritance: ItemDetailView.default_grapher_sizes

var encoders

Inheritance: ItemDetailView.encoders

var export_enabled

Inheritance: ItemDetailView.export_enabled

var export_formats

Inheritance: ItemDetailView.export_formats

var form_class

Inheritance: ItemDetailView.form_class

var graphers

Inheritance: ItemDetailView.graphers

var http_method_names

Inheritance: ItemDetailView.http_method_names

var inlines

Inheritance: ItemDetailView.inlines

var model

Inheritance: ItemDetailView.model

var pk_url_kwarg

Inheritance: ItemDetailView.pk_url_kwarg

var public_graphers

Inheritance: ItemDetailView.public_graphers

var queryset

Inheritance: ItemDetailView.queryset

var response_class

Inheritance: ItemDetailView.response_class

var slug_field

Inheritance: ItemDetailView.slug_field

var slug_url_kwarg

Inheritance: ItemDetailView.slug_url_kwarg

var template_name

Inheritance: ItemDetailView.template_name

var template_name_field

Inheritance: ItemDetailView.template_name_field

var template_name_suffix

Inheritance: ItemDetailView.template_name_suffix

var value_analyzers

Inheritance: ItemDetailView.value_analyzers

Methods

def __init__(

self, **kwargs)

Inheritance: ItemDetailView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemDetailView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemDetailView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemDetailView.get

def get(self, request, *args, **kwargs):
    self.object = self.get_object()
    context = self.get_context_data(object=self.object)
    return self.render_to_response(context)

def get_context_data(

self, **kwargs)

Inheritance: ItemDetailView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemDetailView, self).get_context_data(**kwargs)
    public_id = get_kwargs_or_none('public_id', self.kwargs)
    marker_id = get_kwargs_or_none('marker_id', self.kwargs)
    width = get_kwargs_or_none('width', self.kwargs)
    height = get_kwargs_or_none('height', self.kwargs)
    # get item with one of its given marker_id
    if not public_id and marker_id:
        marker = MediaItemMarker.objects.get(public_id=marker_id)
        item_id = marker.item_id
        item = MediaItem.objects.get(id=item_id)
    else:
        item = self.get_object()
    access = get_item_access(item, self.request.user)
    previous, next = self.item_previous_next(item)
    # Corresponding TimeSide Item
    source, source_type = item.get_source()
    # if source:
    #     ts_item, c = ts.models.Item.objects.get_or_create(**{source_type: source})
    #     if c:
    #         ts_item.title = item.title
    #         ts_item.save()
    self.item_analyze(item)
    # FIXME: use mimetypes.guess_type
    if 'quicktime' in self.mime_type:
        self.mime_type = 'video/mp4'
    playlists = get_playlists_names(self.request)
    rang = []
    for i in range(len(playlists)):
        for resource in playlists[i]['playlist'].resources.all():
            if int(resource.resource_id) == item.id:
                rang.append(i)
                break
    related_media = MediaItemRelated.objects.filter(item=item)
    check_related_media(related_media)
    revisions = Revision.objects.filter(element_type='item', element_id=item.id).order_by('-time')
    if revisions:
        last_revision = revisions[0]
    else:
        last_revision = None
    item_format = ''
    if Format.objects.filter(item=item):
        item_format = item.format.get()
    context['item'] = item
    context['export_formats'] = self.get_export_formats()
    context['visualizers'] = self.get_graphers()
    context['auto_zoom'] = self.auto_zoom
    context['audio_export_enabled'] = self.export_enabled
    context['previous'] = previous
    context['next'] = next
    context['marker'] = marker_id
    context['playlists'] = playlists
    context['access'] = access
    context['width'] = width
    context['height'] = height
    context['related_media'] = related_media
    context['mime_type'] = self.mime_type
    context['last_revision'] = last_revision
    context['format'] = item_format
    context['private_extra_types'] = private_extra_types.values()
    context['site'] = 'http://' + Site.objects.all()[0].name
    context['rang_item_playlist'] = rang
    # if ts_item:
    #     context['ts_item_id'] = ts_item.pk
    # else:
    #     context['ts_item_id'] = None
    return context

def get_context_object_name(

self, obj)

Inheritance: ItemDetailView.get_context_object_name

Get the name to use for the object.

def get_context_object_name(self, obj):
    """
    Get the name to use for the object.
    """
    if self.context_object_name:
        return self.context_object_name
    elif isinstance(obj, models.Model):
        return obj._meta.model_name
    else:
        return None

def get_export_formats(

self)

Inheritance: ItemDetailView.get_export_formats

def get_export_formats(self):
    formats = []
    for encoder in self.encoders:
        if encoder.file_extension() in self.export_formats:
            formats.append({'name': encoder.format(),
                            'extension': encoder.file_extension()})
    return formats

def get_grapher(

self, id)

Inheritance: ItemDetailView.get_grapher

def get_grapher(self, id):
    for grapher in self.graphers:
        if grapher.id() == id:
            break
    return grapher

def get_graphers(

self)

Inheritance: ItemDetailView.get_graphers

def get_graphers(self):
    graphers = []
    user = self.request.user
    graphers_access = (user.is_staff
                       or user.is_superuser
                       or user.has_perm('can_run_analysis'))
    for grapher in self.graphers:
        if (not graphers_access
            and grapher.id() not in self.public_graphers):
            continue
        if grapher.id() == self.default_grapher_id:
            graphers.insert(0, {'name': grapher.name(), 'id': grapher.id()})
        elif not hasattr(grapher, '_staging'):
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
        elif not grapher._staging:
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
    return graphers

def get_is_transcoded_flag(

self, item, mime_type)

Inheritance: ItemDetailView.get_is_transcoded_flag

def get_is_transcoded_flag(self, item, mime_type):
    try:
        is_transcoded_flag, c = MediaItemTranscodingFlag.objects.get_or_create(
            item=item,
            mime_type=mime_type,
            defaults={'value': False})
    except MediaItemTranscodingFlag.MultipleObjectsReturned:
        flags = MediaItemTranscodingFlag.objects.filter(
            item=item,
            mime_type=mime_type)
        value = all([f.value for f in flags])
        is_transcoded_flag = flags[0]
        is_transcoded_flag.value = value
        is_transcoded_flag.save()
        for f in flags[1:]:
            f.delete()
    return is_transcoded_flag

def get_item_file_url(

*a, **kw)

Inheritance: ItemDetailView.get_item_file_url

@jsonrpc_method('telemeta.get_item_export_url')
def get_item_file_url(request, public_id, extension):
    return reverse('telemeta-item-export', kwargs={'public_id': public_id, 'extension': extension})

def get_object(

self)

Inheritance: ItemDetailView.get_object

def get_object(self):
    obj = self.model.objects.filter(code=self.kwargs['public_id'])
    if not obj:
        if self.kwargs['public_id'].isdigit():
            try:
                obj = self.model.objects.get(id=self.kwargs['public_id'])
            except self.model.DoesNotExist:
                raise Http404
        else:
            raise Http404
    else:
        obj = obj[0]
    return obj

def get_queryset(

self)

Inheritance: ItemDetailView.get_queryset

Get the queryset to look an object up against. May not be called if get_object is overridden.

def get_queryset(self):
    """
    Get the queryset to look an object up against. May not be called if
    `get_object` is overridden.
    """
    if self.queryset is None:
        if self.model:
            return self.model._default_manager.all()
        else:
            raise ImproperlyConfigured("%(cls)s is missing a queryset. Define "
                                       "%(cls)s.model, %(cls)s.queryset, or override "
                                       "%(cls)s.get_queryset()." % {
                                            'cls': self.__class__.__name__
                                    })
    return self.queryset._clone()

def get_slug_field(

self)

Inheritance: ItemDetailView.get_slug_field

Get the name of a slug field to be used to look up by slug.

def get_slug_field(self):
    """
    Get the name of a slug field to be used to look up by slug.
    """
    return self.slug_field

def get_template_names(

self)

Inheritance: ItemDetailView.get_template_names

Return a list of template names to be used for the request. May not be called if render_to_response is overridden. Returns the following list:

  • the value of template_name on the view (if provided)
  • the contents of the template_name_field field on the object instance that the view is operating upon (if available)
  • <app_label>/<model_name><template_name_suffix>.html
def get_template_names(self):
    """
    Return a list of template names to be used for the request. May not be
    called if render_to_response is overridden. Returns the following list:
    * the value of ``template_name`` on the view (if provided)
    * the contents of the ``template_name_field`` field on the
      object instance that the view is operating upon (if available)
    * ``<app_label>/<model_name><template_name_suffix>.html``
    """
    try:
        names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
        # If self.template_name_field is set, grab the value of the field
        # of that name from the object; this is the most specific template
        # name, if given.
        if self.object and self.template_name_field:
            name = getattr(self.object, self.template_name_field, None)
            if name:
                names.insert(0, name)
        # The least-specific option is the default <app>/<model>_detail.html;
        # only use this if the object in question is a model.
        if isinstance(self.object, models.Model):
            names.append("%s/%s%s.html" % (
                self.object._meta.app_label,
                self.object._meta.model_name,
                self.template_name_suffix
            ))
        elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model):
            names.append("%s/%s%s.html" % (
                self.model._meta.app_label,
                self.model._meta.model_name,
                self.template_name_suffix
            ))
        # If we still haven't managed to find any template names, we should
        # re-raise the ImproperlyConfigured to alert the user.
        if not names:
            raise
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemDetailView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def item_analyze(

self, item)

Inheritance: ItemDetailView.item_analyze

def item_analyze(self, item):
    analyses = item.analysis.all()
    encoders_id = ['mp3_encoder']  # , 'vorbis_encoder']
    mime_type = ''
    if analyses:
        for analysis in analyses:
            if not item.approx_duration and analysis.analyzer_id == 'duration':
                value = analysis.value
                time = value.split(':')
                time[2] = time[2].split('.')[0]
                time = ':'.join(time)
                item.approx_duration = time
                item.save()
            if analysis.analyzer_id == 'mime_type':
                mime_type = analysis.value
    else:
        analyzers = []
        analyzers_sub = []
        graphers_sub = []
        encoders_sub = []
        source = item.get_source()[0]
        if source:
            decoder = timeside.core.get_processor('file_decoder')(source)
            pipe = decoder
            for analyzer in self.value_analyzers:
                subpipe = analyzer()
                analyzers_sub.append(subpipe)
                pipe = pipe | subpipe
            default_grapher = self.get_grapher(self.default_grapher_id)
            for size in self.default_grapher_sizes:
                width = size.split('x')[0]
                height = size.split('x')[1]
                image_file = '.'.join([item.public_id, self.default_grapher_id, size.replace('x', '_'), 'png'])
                path = self.cache_data.dir + os.sep + image_file
                graph = default_grapher(width=int(width), height=int(height))
                graphers_sub.append({'graph': graph, 'path': path})
                pipe |= graph
            for proc_id in encoders_id:
                encoder_cls = timeside.core.get_processor(proc_id)
                mime_type = encoder_cls.mime_type()
                cache_file = item.public_id + '.' + encoder_cls.file_extension()
                media = self.cache_export.dir + os.sep + cache_file
                encoder = encoder_cls(output=media, overwrite=True)
                encoders_sub.append(encoder)
                pipe |= encoder
            pipe.run()
            for grapher in graphers_sub:
                grapher['graph'].watermark('timeside', opacity=.6, margin=(5, 5))
                f = open(grapher['path'], 'w')
                grapher['graph'].render(grapher['path'])
                f.close()
            if os.path.exists(source):
                mime_type = mimetypes.guess_type(source)[0]
                analysis = MediaItemAnalysis(item=item, name='MIME type',
                                             analyzer_id='mime_type', unit='', value=mime_type)
                analysis.save()
                analysis = MediaItemAnalysis(item=item, name='Size',
                                             analyzer_id='size', unit='', value=item.size())
                analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Channels',
                                         analyzer_id='channels',
                                         unit='', value=decoder.input_channels)
            analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Samplerate',
                                         analyzer_id='samplerate', unit='Hz',
                                         value=unicode(decoder.input_samplerate))
            analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Resolution',
                                         analyzer_id='resolution', unit='bits',
                                         value=unicode(decoder.input_width))
            analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Duration',
                                         analyzer_id='duration', unit='s',
                                         value=unicode(datetime.timedelta(0, decoder.input_duration)))
            analysis.save()
            for analyzer in analyzers_sub:
                for key in analyzer.results.keys():
                    result = analyzer.results[key]
                    value = result.data_object.value
                    if value.shape[0] == 1:
                        value = value[0]
                    analysis = MediaItemAnalysis(item=item, name=result.name,
                                                 analyzer_id=result.id, unit=result.unit, value=unicode(value))
                    analysis.save()
            for encoder in encoders_sub:
                is_transcoded_flag = self.get_is_transcoded_flag(item=item, mime_type=mime_type)
                is_transcoded_flag.value = True
                is_transcoded_flag.save()
             FIXME: parse tags on first load
             tags = decoder.tags
    self.mime_type = mime_type

def item_previous_next(

self, item)

Inheritance: ItemDetailView.item_previous_next

Get previous and next items inside the collection of the item

def item_previous_next(self, item):
    """Get previous and next items inside the collection of the item"""
    pks = []
    items = MediaItem.objects.filter(collection=item.collection)
    items = items.order_by('code', 'old_code')
    if len(items) > 1:
        for it in items:
            pks.append(it.pk)
        for pk in pks:
            if pk == item.pk:
                if pk == pks[0]:
                    previous_pk = pks[-1]
                    next_pk = pks[1]
                elif pk == pks[-1]:
                    previous_pk = pks[-2]
                    next_pk = pks[0]
                else:
                    previous_pk = pks[pks.index(pk) - 1]
                    next_pk = pks[pks.index(pk) + 1]
                for it in items:
                    if it.pk == previous_pk:
                        previous = it
                    if it.pk == next_pk:
                        next = it
                previous = previous.public_id
                next = next.public_id
    else:
        previous = item.public_id
        next = item.public_id
    return previous, next

def options(

self, request, *args, **kwargs)

Inheritance: ItemDetailView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemDetailView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemDetailView

class ItemDetailView(ItemViewMixin, DetailView):

    template_name = 'telemeta/mediaitem_detail.html'

    def item_analyze(self, item):
        analyses = item.analysis.all()
        encoders_id = ['mp3_encoder']  # , 'vorbis_encoder']
        mime_type = ''

        if analyses:
            for analysis in analyses:
                if not item.approx_duration and analysis.analyzer_id == 'duration':
                    value = analysis.value
                    time = value.split(':')
                    time[2] = time[2].split('.')[0]
                    time = ':'.join(time)
                    item.approx_duration = time
                    item.save()
                if analysis.analyzer_id == 'mime_type':
                    mime_type = analysis.value
        else:
            analyzers = []
            analyzers_sub = []
            graphers_sub = []
            encoders_sub = []

            source = item.get_source()[0]

            if source:

                decoder = timeside.core.get_processor('file_decoder')(source)
                pipe = decoder

                for analyzer in self.value_analyzers:
                    subpipe = analyzer()
                    analyzers_sub.append(subpipe)
                    pipe = pipe | subpipe

                default_grapher = self.get_grapher(self.default_grapher_id)
                for size in self.default_grapher_sizes:
                    width = size.split('x')[0]
                    height = size.split('x')[1]
                    image_file = '.'.join([item.public_id, self.default_grapher_id, size.replace('x', '_'), 'png'])
                    path = self.cache_data.dir + os.sep + image_file
                    graph = default_grapher(width=int(width), height=int(height))
                    graphers_sub.append({'graph': graph, 'path': path})
                    pipe |= graph

                for proc_id in encoders_id:
                    encoder_cls = timeside.core.get_processor(proc_id)
                    mime_type = encoder_cls.mime_type()
                    cache_file = item.public_id + '.' + encoder_cls.file_extension()
                    media = self.cache_export.dir + os.sep + cache_file
                    encoder = encoder_cls(output=media, overwrite=True)
                    encoders_sub.append(encoder)
                    pipe |= encoder

                pipe.run()

                for grapher in graphers_sub:
                    grapher['graph'].watermark('timeside', opacity=.6, margin=(5, 5))
                    f = open(grapher['path'], 'w')
                    grapher['graph'].render(grapher['path'])
                    f.close()

                if os.path.exists(source):
                    mime_type = mimetypes.guess_type(source)[0]
                    analysis = MediaItemAnalysis(item=item, name='MIME type',
                                                 analyzer_id='mime_type', unit='', value=mime_type)
                    analysis.save()
                    analysis = MediaItemAnalysis(item=item, name='Size',
                                                 analyzer_id='size', unit='', value=item.size())
                    analysis.save()

                analysis = MediaItemAnalysis(item=item, name='Channels',
                                             analyzer_id='channels',
                                             unit='', value=decoder.input_channels)
                analysis.save()
                analysis = MediaItemAnalysis(item=item, name='Samplerate',
                                             analyzer_id='samplerate', unit='Hz',
                                             value=unicode(decoder.input_samplerate))
                analysis.save()
                analysis = MediaItemAnalysis(item=item, name='Resolution',
                                             analyzer_id='resolution', unit='bits',
                                             value=unicode(decoder.input_width))
                analysis.save()
                analysis = MediaItemAnalysis(item=item, name='Duration',
                                             analyzer_id='duration', unit='s',
                                             value=unicode(datetime.timedelta(0, decoder.input_duration)))
                analysis.save()

                for analyzer in analyzers_sub:
                    for key in analyzer.results.keys():
                        result = analyzer.results[key]
                        value = result.data_object.value
                        if value.shape[0] == 1:
                            value = value[0]
                        analysis = MediaItemAnalysis(item=item, name=result.name,
                                                     analyzer_id=result.id, unit=result.unit, value=unicode(value))
                        analysis.save()

                for encoder in encoders_sub:
                    is_transcoded_flag = self.get_is_transcoded_flag(item=item, mime_type=mime_type)
                    is_transcoded_flag.value = True
                    is_transcoded_flag.save()

#                FIXME: parse tags on first load
#                tags = decoder.tags

        self.mime_type = mime_type

    def get_context_data(self, **kwargs):
        context = super(ItemDetailView, self).get_context_data(**kwargs)

        public_id = get_kwargs_or_none('public_id', self.kwargs)
        marker_id = get_kwargs_or_none('marker_id', self.kwargs)
        width = get_kwargs_or_none('width', self.kwargs)
        height = get_kwargs_or_none('height', self.kwargs)

        # get item with one of its given marker_id
        if not public_id and marker_id:
            marker = MediaItemMarker.objects.get(public_id=marker_id)
            item_id = marker.item_id
            item = MediaItem.objects.get(id=item_id)
        else:
            item = self.get_object()

        access = get_item_access(item, self.request.user)

        previous, next = self.item_previous_next(item)

        # Corresponding TimeSide Item
        source, source_type = item.get_source()
        # if source:
        #     ts_item, c = ts.models.Item.objects.get_or_create(**{source_type: source})
        #     if c:
        #         ts_item.title = item.title
        #         ts_item.save()

        self.item_analyze(item)

        # FIXME: use mimetypes.guess_type
        if 'quicktime' in self.mime_type:
            self.mime_type = 'video/mp4'

        playlists = get_playlists_names(self.request)

        rang = []
        for i in range(len(playlists)):
            for resource in playlists[i]['playlist'].resources.all():
                if int(resource.resource_id) == item.id:
                    rang.append(i)
                    break
        related_media = MediaItemRelated.objects.filter(item=item)
        check_related_media(related_media)
        revisions = Revision.objects.filter(element_type='item', element_id=item.id).order_by('-time')
        if revisions:
            last_revision = revisions[0]
        else:
            last_revision = None

        item_format = ''
        if Format.objects.filter(item=item):
            item_format = item.format.get()

        context['item'] = item
        context['export_formats'] = self.get_export_formats()
        context['visualizers'] = self.get_graphers()
        context['auto_zoom'] = self.auto_zoom
        context['audio_export_enabled'] = self.export_enabled
        context['previous'] = previous
        context['next'] = next
        context['marker'] = marker_id
        context['playlists'] = playlists
        context['access'] = access
        context['width'] = width
        context['height'] = height
        context['related_media'] = related_media
        context['mime_type'] = self.mime_type
        context['last_revision'] = last_revision
        context['format'] = item_format
        context['private_extra_types'] = private_extra_types.values()
        context['site'] = 'http://' + Site.objects.all()[0].name
        context['rang_item_playlist'] = rang
        # if ts_item:
        #     context['ts_item_id'] = ts_item.pk
        # else:
        #     context['ts_item_id'] = None

        return context

Ancestors (in MRO)

  • ItemDetailView
  • ItemViewMixin
  • ItemBaseMixin
  • telemeta.views.core.TelemetaBaseMixin
  • django.views.generic.detail.DetailView
  • django.views.generic.detail.SingleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.detail.BaseDetailView
  • django.views.generic.detail.SingleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var CACHE_DIR

Inheritance: ItemViewMixin.CACHE_DIR

var MEDIA_ROOT

Inheritance: ItemViewMixin.MEDIA_ROOT

var analyzers

Inheritance: ItemViewMixin.analyzers

var auto_zoom

Inheritance: ItemViewMixin.auto_zoom

var cache_data

Inheritance: ItemViewMixin.cache_data

var cache_export

Inheritance: ItemViewMixin.cache_export

var cache_tmp

Inheritance: ItemViewMixin.cache_tmp

var content_type

var context_object_name

var decoders

Inheritance: ItemViewMixin.decoders

var default_grapher_id

Inheritance: ItemViewMixin.default_grapher_id

var default_grapher_sizes

Inheritance: ItemViewMixin.default_grapher_sizes

var encoders

Inheritance: ItemViewMixin.encoders

var export_enabled

Inheritance: ItemViewMixin.export_enabled

var export_formats

Inheritance: ItemViewMixin.export_formats

var form_class

Inheritance: ItemViewMixin.form_class

var graphers

Inheritance: ItemViewMixin.graphers

var http_method_names

var inlines

Inheritance: ItemViewMixin.inlines

var model

Inheritance: ItemViewMixin.model

var pk_url_kwarg

var public_graphers

Inheritance: ItemViewMixin.public_graphers

var queryset

var response_class

var slug_field

var slug_url_kwarg

var template_name

var template_name_field

var template_name_suffix

var value_analyzers

Inheritance: ItemViewMixin.value_analyzers

Methods

def __init__(

self, **kwargs)

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

def get(self, request, *args, **kwargs):
    self.object = self.get_object()
    context = self.get_context_data(object=self.object)
    return self.render_to_response(context)

def get_context_data(

self, **kwargs)

def get_context_data(self, **kwargs):
    context = super(ItemDetailView, self).get_context_data(**kwargs)
    public_id = get_kwargs_or_none('public_id', self.kwargs)
    marker_id = get_kwargs_or_none('marker_id', self.kwargs)
    width = get_kwargs_or_none('width', self.kwargs)
    height = get_kwargs_or_none('height', self.kwargs)
    # get item with one of its given marker_id
    if not public_id and marker_id:
        marker = MediaItemMarker.objects.get(public_id=marker_id)
        item_id = marker.item_id
        item = MediaItem.objects.get(id=item_id)
    else:
        item = self.get_object()
    access = get_item_access(item, self.request.user)
    previous, next = self.item_previous_next(item)
    # Corresponding TimeSide Item
    source, source_type = item.get_source()
    # if source:
    #     ts_item, c = ts.models.Item.objects.get_or_create(**{source_type: source})
    #     if c:
    #         ts_item.title = item.title
    #         ts_item.save()
    self.item_analyze(item)
    # FIXME: use mimetypes.guess_type
    if 'quicktime' in self.mime_type:
        self.mime_type = 'video/mp4'
    playlists = get_playlists_names(self.request)
    rang = []
    for i in range(len(playlists)):
        for resource in playlists[i]['playlist'].resources.all():
            if int(resource.resource_id) == item.id:
                rang.append(i)
                break
    related_media = MediaItemRelated.objects.filter(item=item)
    check_related_media(related_media)
    revisions = Revision.objects.filter(element_type='item', element_id=item.id).order_by('-time')
    if revisions:
        last_revision = revisions[0]
    else:
        last_revision = None
    item_format = ''
    if Format.objects.filter(item=item):
        item_format = item.format.get()
    context['item'] = item
    context['export_formats'] = self.get_export_formats()
    context['visualizers'] = self.get_graphers()
    context['auto_zoom'] = self.auto_zoom
    context['audio_export_enabled'] = self.export_enabled
    context['previous'] = previous
    context['next'] = next
    context['marker'] = marker_id
    context['playlists'] = playlists
    context['access'] = access
    context['width'] = width
    context['height'] = height
    context['related_media'] = related_media
    context['mime_type'] = self.mime_type
    context['last_revision'] = last_revision
    context['format'] = item_format
    context['private_extra_types'] = private_extra_types.values()
    context['site'] = 'http://' + Site.objects.all()[0].name
    context['rang_item_playlist'] = rang
    # if ts_item:
    #     context['ts_item_id'] = ts_item.pk
    # else:
    #     context['ts_item_id'] = None
    return context

def get_context_object_name(

self, obj)

Get the name to use for the object.

def get_context_object_name(self, obj):
    """
    Get the name to use for the object.
    """
    if self.context_object_name:
        return self.context_object_name
    elif isinstance(obj, models.Model):
        return obj._meta.model_name
    else:
        return None

def get_export_formats(

self)

Inheritance: ItemViewMixin.get_export_formats

def get_export_formats(self):
    formats = []
    for encoder in self.encoders:
        if encoder.file_extension() in self.export_formats:
            formats.append({'name': encoder.format(),
                            'extension': encoder.file_extension()})
    return formats

def get_grapher(

self, id)

Inheritance: ItemViewMixin.get_grapher

def get_grapher(self, id):
    for grapher in self.graphers:
        if grapher.id() == id:
            break
    return grapher

def get_graphers(

self)

Inheritance: ItemViewMixin.get_graphers

def get_graphers(self):
    graphers = []
    user = self.request.user
    graphers_access = (user.is_staff
                       or user.is_superuser
                       or user.has_perm('can_run_analysis'))
    for grapher in self.graphers:
        if (not graphers_access
            and grapher.id() not in self.public_graphers):
            continue
        if grapher.id() == self.default_grapher_id:
            graphers.insert(0, {'name': grapher.name(), 'id': grapher.id()})
        elif not hasattr(grapher, '_staging'):
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
        elif not grapher._staging:
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
    return graphers

def get_is_transcoded_flag(

self, item, mime_type)

Inheritance: ItemViewMixin.get_is_transcoded_flag

def get_is_transcoded_flag(self, item, mime_type):
    try:
        is_transcoded_flag, c = MediaItemTranscodingFlag.objects.get_or_create(
            item=item,
            mime_type=mime_type,
            defaults={'value': False})
    except MediaItemTranscodingFlag.MultipleObjectsReturned:
        flags = MediaItemTranscodingFlag.objects.filter(
            item=item,
            mime_type=mime_type)
        value = all([f.value for f in flags])
        is_transcoded_flag = flags[0]
        is_transcoded_flag.value = value
        is_transcoded_flag.save()
        for f in flags[1:]:
            f.delete()
    return is_transcoded_flag

def get_item_file_url(

*a, **kw)

Inheritance: ItemViewMixin.get_item_file_url

@jsonrpc_method('telemeta.get_item_export_url')
def get_item_file_url(request, public_id, extension):
    return reverse('telemeta-item-export', kwargs={'public_id': public_id, 'extension': extension})

def get_object(

self)

Inheritance: ItemViewMixin.get_object

def get_object(self):
    obj = self.model.objects.filter(code=self.kwargs['public_id'])
    if not obj:
        if self.kwargs['public_id'].isdigit():
            try:
                obj = self.model.objects.get(id=self.kwargs['public_id'])
            except self.model.DoesNotExist:
                raise Http404
        else:
            raise Http404
    else:
        obj = obj[0]
    return obj

def get_queryset(

self)

Get the queryset to look an object up against. May not be called if get_object is overridden.

def get_queryset(self):
    """
    Get the queryset to look an object up against. May not be called if
    `get_object` is overridden.
    """
    if self.queryset is None:
        if self.model:
            return self.model._default_manager.all()
        else:
            raise ImproperlyConfigured("%(cls)s is missing a queryset. Define "
                                       "%(cls)s.model, %(cls)s.queryset, or override "
                                       "%(cls)s.get_queryset()." % {
                                            'cls': self.__class__.__name__
                                    })
    return self.queryset._clone()

def get_slug_field(

self)

Get the name of a slug field to be used to look up by slug.

def get_slug_field(self):
    """
    Get the name of a slug field to be used to look up by slug.
    """
    return self.slug_field

def get_template_names(

self)

Return a list of template names to be used for the request. May not be called if render_to_response is overridden. Returns the following list:

  • the value of template_name on the view (if provided)
  • the contents of the template_name_field field on the object instance that the view is operating upon (if available)
  • <app_label>/<model_name><template_name_suffix>.html
def get_template_names(self):
    """
    Return a list of template names to be used for the request. May not be
    called if render_to_response is overridden. Returns the following list:
    * the value of ``template_name`` on the view (if provided)
    * the contents of the ``template_name_field`` field on the
      object instance that the view is operating upon (if available)
    * ``<app_label>/<model_name><template_name_suffix>.html``
    """
    try:
        names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
        # If self.template_name_field is set, grab the value of the field
        # of that name from the object; this is the most specific template
        # name, if given.
        if self.object and self.template_name_field:
            name = getattr(self.object, self.template_name_field, None)
            if name:
                names.insert(0, name)
        # The least-specific option is the default <app>/<model>_detail.html;
        # only use this if the object in question is a model.
        if isinstance(self.object, models.Model):
            names.append("%s/%s%s.html" % (
                self.object._meta.app_label,
                self.object._meta.model_name,
                self.template_name_suffix
            ))
        elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model):
            names.append("%s/%s%s.html" % (
                self.model._meta.app_label,
                self.model._meta.model_name,
                self.template_name_suffix
            ))
        # If we still haven't managed to find any template names, we should
        # re-raise the ImproperlyConfigured to alert the user.
        if not names:
            raise
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def item_analyze(

self, item)

def item_analyze(self, item):
    analyses = item.analysis.all()
    encoders_id = ['mp3_encoder']  # , 'vorbis_encoder']
    mime_type = ''
    if analyses:
        for analysis in analyses:
            if not item.approx_duration and analysis.analyzer_id == 'duration':
                value = analysis.value
                time = value.split(':')
                time[2] = time[2].split('.')[0]
                time = ':'.join(time)
                item.approx_duration = time
                item.save()
            if analysis.analyzer_id == 'mime_type':
                mime_type = analysis.value
    else:
        analyzers = []
        analyzers_sub = []
        graphers_sub = []
        encoders_sub = []
        source = item.get_source()[0]
        if source:
            decoder = timeside.core.get_processor('file_decoder')(source)
            pipe = decoder
            for analyzer in self.value_analyzers:
                subpipe = analyzer()
                analyzers_sub.append(subpipe)
                pipe = pipe | subpipe
            default_grapher = self.get_grapher(self.default_grapher_id)
            for size in self.default_grapher_sizes:
                width = size.split('x')[0]
                height = size.split('x')[1]
                image_file = '.'.join([item.public_id, self.default_grapher_id, size.replace('x', '_'), 'png'])
                path = self.cache_data.dir + os.sep + image_file
                graph = default_grapher(width=int(width), height=int(height))
                graphers_sub.append({'graph': graph, 'path': path})
                pipe |= graph
            for proc_id in encoders_id:
                encoder_cls = timeside.core.get_processor(proc_id)
                mime_type = encoder_cls.mime_type()
                cache_file = item.public_id + '.' + encoder_cls.file_extension()
                media = self.cache_export.dir + os.sep + cache_file
                encoder = encoder_cls(output=media, overwrite=True)
                encoders_sub.append(encoder)
                pipe |= encoder
            pipe.run()
            for grapher in graphers_sub:
                grapher['graph'].watermark('timeside', opacity=.6, margin=(5, 5))
                f = open(grapher['path'], 'w')
                grapher['graph'].render(grapher['path'])
                f.close()
            if os.path.exists(source):
                mime_type = mimetypes.guess_type(source)[0]
                analysis = MediaItemAnalysis(item=item, name='MIME type',
                                             analyzer_id='mime_type', unit='', value=mime_type)
                analysis.save()
                analysis = MediaItemAnalysis(item=item, name='Size',
                                             analyzer_id='size', unit='', value=item.size())
                analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Channels',
                                         analyzer_id='channels',
                                         unit='', value=decoder.input_channels)
            analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Samplerate',
                                         analyzer_id='samplerate', unit='Hz',
                                         value=unicode(decoder.input_samplerate))
            analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Resolution',
                                         analyzer_id='resolution', unit='bits',
                                         value=unicode(decoder.input_width))
            analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Duration',
                                         analyzer_id='duration', unit='s',
                                         value=unicode(datetime.timedelta(0, decoder.input_duration)))
            analysis.save()
            for analyzer in analyzers_sub:
                for key in analyzer.results.keys():
                    result = analyzer.results[key]
                    value = result.data_object.value
                    if value.shape[0] == 1:
                        value = value[0]
                    analysis = MediaItemAnalysis(item=item, name=result.name,
                                                 analyzer_id=result.id, unit=result.unit, value=unicode(value))
                    analysis.save()
            for encoder in encoders_sub:
                is_transcoded_flag = self.get_is_transcoded_flag(item=item, mime_type=mime_type)
                is_transcoded_flag.value = True
                is_transcoded_flag.save()
             FIXME: parse tags on first load
             tags = decoder.tags
    self.mime_type = mime_type

def item_previous_next(

self, item)

Inheritance: ItemViewMixin.item_previous_next

Get previous and next items inside the collection of the item

def item_previous_next(self, item):
    """Get previous and next items inside the collection of the item"""
    pks = []
    items = MediaItem.objects.filter(collection=item.collection)
    items = items.order_by('code', 'old_code')
    if len(items) > 1:
        for it in items:
            pks.append(it.pk)
        for pk in pks:
            if pk == item.pk:
                if pk == pks[0]:
                    previous_pk = pks[-1]
                    next_pk = pks[1]
                elif pk == pks[-1]:
                    previous_pk = pks[-2]
                    next_pk = pks[0]
                else:
                    previous_pk = pks[pks.index(pk) - 1]
                    next_pk = pks[pks.index(pk) + 1]
                for it in items:
                    if it.pk == previous_pk:
                        previous = it
                    if it.pk == next_pk:
                        next = it
                previous = previous.public_id
                next = next.public_id
    else:
        previous = item.public_id
        next = item.public_id
    return previous, next

def options(

self, request, *args, **kwargs)

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def render_to_response(

self, context, **response_kwargs)

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemEditView

class ItemEditView(ItemViewMixin, UpdateWithInlinesView):

    template_name = 'telemeta/mediaitem_edit.html'

    def get_form_class(self):
        if self.request.user.is_staff:
            return MediaItemForm
        else:
            return RestrictedMediaItemForm

    def forms_valid(self, form, inlines):
        messages.info(self.request, ugettext_lazy("You have successfully updated your item."))
        item = form.save()
        self.code = item.code
        if form.files:
            self.cache_data.delete_item_data(item.code)
            self.cache_export.delete_item_data(item.code)
            flags = MediaItemTranscodingFlag.objects.filter(item=item)
            analyses = MediaItemAnalysis.objects.filter(item=item)
            for flag in flags:
                flag.delete()
            for analysis in analyses:
                analysis.delete()
        item.set_revision(self.request.user)
        return super(ItemEditView, self).forms_valid(form, inlines)

    def get_success_url(self):
        return reverse_lazy('telemeta-item-detail', kwargs={'public_id': self.code})

    def get_context_data(self, **kwargs):
        context = super(ItemEditView, self).get_context_data(**kwargs)
        item = self.get_object()
        context['item'] = item
        context['access'] = get_item_access(item, self.request.user)
        context['previous'], context['next'] = self.item_previous_next(item)
        # FIXME
        context['mime_type'] = 'audio/mp3'
        context['export_formats'] = self.get_export_formats()
        context['visualizers'] = self.get_graphers()
        context['audio_export_enabled'] = self.export_enabled
        context['auto_zoom'] = True
        return context

    @method_decorator(permission_required('telemeta.change_mediaitem'))
    def dispatch(self, *args, **kwargs):
        return super(ItemEditView, self).dispatch(*args, **kwargs)

Ancestors (in MRO)

  • ItemEditView
  • ItemViewMixin
  • ItemBaseMixin
  • telemeta.views.core.TelemetaBaseMixin
  • extra_views.advanced.UpdateWithInlinesView
  • django.views.generic.detail.SingleObjectTemplateResponseMixin
  • extra_views.advanced.BaseUpdateWithInlinesView
  • extra_views.advanced.ModelFormWithInlinesMixin
  • django.views.generic.edit.ModelFormMixin
  • extra_views.advanced.ProcessFormWithInlinesView
  • django.views.generic.edit.FormView
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.edit.BaseFormView
  • django.views.generic.edit.FormMixin
  • django.views.generic.detail.SingleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.edit.ProcessFormView
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var CACHE_DIR

Inheritance: ItemViewMixin.CACHE_DIR

var MEDIA_ROOT

Inheritance: ItemViewMixin.MEDIA_ROOT

var analyzers

Inheritance: ItemViewMixin.analyzers

var auto_zoom

Inheritance: ItemViewMixin.auto_zoom

var cache_data

Inheritance: ItemViewMixin.cache_data

var cache_export

Inheritance: ItemViewMixin.cache_export

var cache_tmp

Inheritance: ItemViewMixin.cache_tmp

var content_type

var context_object_name

var decoders

Inheritance: ItemViewMixin.decoders

var default_grapher_id

Inheritance: ItemViewMixin.default_grapher_id

var default_grapher_sizes

Inheritance: ItemViewMixin.default_grapher_sizes

var encoders

Inheritance: ItemViewMixin.encoders

var export_enabled

Inheritance: ItemViewMixin.export_enabled

var export_formats

Inheritance: ItemViewMixin.export_formats

var fields

var form_class

Inheritance: ItemViewMixin.form_class

var graphers

Inheritance: ItemViewMixin.graphers

var http_method_names

var initial

var inlines

Inheritance: ItemViewMixin.inlines

var model

Inheritance: ItemViewMixin.model

var pk_url_kwarg

var prefix

var public_graphers

Inheritance: ItemViewMixin.public_graphers

var queryset

var response_class

var slug_field

var slug_url_kwarg

var success_url

var template_name

var template_name_field

var template_name_suffix

var value_analyzers

Inheritance: ItemViewMixin.value_analyzers

Methods

def __init__(

self, **kwargs)

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def construct_inlines(

self)

Returns the inline formset instances

def construct_inlines(self):
    """
    Returns the inline formset instances
    """
    inline_formsets = []
    for inline_class in self.get_inlines():
        inline_instance = inline_class(self.model, self.request, self.object, self.kwargs, self)
        inline_formset = inline_instance.construct_formset()
        inline_formsets.append(inline_formset)
    return inline_formsets

def dispatch(

self, *args, **kwargs)

def _wrapper(self, *args, **kwargs):
    @decorator
    def bound_func(*args2, **kwargs2):
        return func(self, *args2, **kwargs2)
    # bound_func has the signature that 'decorator' expects i.e.  no
    # 'self' argument, but it is a closure over self so it can call
    # 'func' correctly.
    return bound_func(*args, **kwargs)

def form_invalid(

self, form)

If the form is invalid, re-render the context data with the data-filled form and errors.

def form_invalid(self, form):
    """
    If the form is invalid, re-render the context data with the
    data-filled form and errors.
    """
    return self.render_to_response(self.get_context_data(form=form))

def form_valid(

self, form)

If the form is valid, save the associated model.

def form_valid(self, form):
    """
    If the form is valid, save the associated model.
    """
    self.object = form.save()
    return super(ModelFormMixin, self).form_valid(form)

def forms_invalid(

self, form, inlines)

If the form or formsets are invalid, re-render the context data with the data-filled form and formsets and errors.

def forms_invalid(self, form, inlines):
    """
    If the form or formsets are invalid, re-render the context data with the
    data-filled form and formsets and errors.
    """
    return self.render_to_response(self.get_context_data(form=form, inlines=inlines))

def forms_valid(

self, form, inlines)

def forms_valid(self, form, inlines):
    messages.info(self.request, ugettext_lazy("You have successfully updated your item."))
    item = form.save()
    self.code = item.code
    if form.files:
        self.cache_data.delete_item_data(item.code)
        self.cache_export.delete_item_data(item.code)
        flags = MediaItemTranscodingFlag.objects.filter(item=item)
        analyses = MediaItemAnalysis.objects.filter(item=item)
        for flag in flags:
            flag.delete()
        for analysis in analyses:
            analysis.delete()
    item.set_revision(self.request.user)
    return super(ItemEditView, self).forms_valid(form, inlines)

def get(

self, request, *args, **kwargs)

def get(self, request, *args, **kwargs):
    self.object = self.get_object()
    return super(BaseUpdateWithInlinesView, self).get(request, *args, **kwargs)

def get_context_data(

self, **kwargs)

def get_context_data(self, **kwargs):
    context = super(ItemEditView, self).get_context_data(**kwargs)
    item = self.get_object()
    context['item'] = item
    context['access'] = get_item_access(item, self.request.user)
    context['previous'], context['next'] = self.item_previous_next(item)
    # FIXME
    context['mime_type'] = 'audio/mp3'
    context['export_formats'] = self.get_export_formats()
    context['visualizers'] = self.get_graphers()
    context['audio_export_enabled'] = self.export_enabled
    context['auto_zoom'] = True
    return context

def get_context_object_name(

self, obj)

Get the name to use for the object.

def get_context_object_name(self, obj):
    """
    Get the name to use for the object.
    """
    if self.context_object_name:
        return self.context_object_name
    elif isinstance(obj, models.Model):
        return obj._meta.model_name
    else:
        return None

def get_export_formats(

self)

Inheritance: ItemViewMixin.get_export_formats

def get_export_formats(self):
    formats = []
    for encoder in self.encoders:
        if encoder.file_extension() in self.export_formats:
            formats.append({'name': encoder.format(),
                            'extension': encoder.file_extension()})
    return formats

def get_form(

self, form_class)

Returns an instance of the form to be used in this view.

def get_form(self, form_class):
    """
    Returns an instance of the form to be used in this view.
    """
    return form_class(**self.get_form_kwargs())

def get_form_class(

self)

def get_form_class(self):
    if self.request.user.is_staff:
        return MediaItemForm
    else:
        return RestrictedMediaItemForm

def get_form_kwargs(

self)

Returns the keyword arguments for instantiating the form.

def get_form_kwargs(self):
    """
    Returns the keyword arguments for instantiating the form.
    """
    kwargs = super(ModelFormMixin, self).get_form_kwargs()
    kwargs.update({'instance': self.object})
    return kwargs

def get_grapher(

self, id)

Inheritance: ItemViewMixin.get_grapher

def get_grapher(self, id):
    for grapher in self.graphers:
        if grapher.id() == id:
            break
    return grapher

def get_graphers(

self)

Inheritance: ItemViewMixin.get_graphers

def get_graphers(self):
    graphers = []
    user = self.request.user
    graphers_access = (user.is_staff
                       or user.is_superuser
                       or user.has_perm('can_run_analysis'))
    for grapher in self.graphers:
        if (not graphers_access
            and grapher.id() not in self.public_graphers):
            continue
        if grapher.id() == self.default_grapher_id:
            graphers.insert(0, {'name': grapher.name(), 'id': grapher.id()})
        elif not hasattr(grapher, '_staging'):
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
        elif not grapher._staging:
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
    return graphers

def get_initial(

self)

Returns the initial data to use for forms on this view.

def get_initial(self):
    """
    Returns the initial data to use for forms on this view.
    """
    return self.initial.copy()

def get_inlines(

self)

Returns the inline formset classes

def get_inlines(self):
    """
    Returns the inline formset classes
    """
    return self.inlines

def get_is_transcoded_flag(

self, item, mime_type)

Inheritance: ItemViewMixin.get_is_transcoded_flag

def get_is_transcoded_flag(self, item, mime_type):
    try:
        is_transcoded_flag, c = MediaItemTranscodingFlag.objects.get_or_create(
            item=item,
            mime_type=mime_type,
            defaults={'value': False})
    except MediaItemTranscodingFlag.MultipleObjectsReturned:
        flags = MediaItemTranscodingFlag.objects.filter(
            item=item,
            mime_type=mime_type)
        value = all([f.value for f in flags])
        is_transcoded_flag = flags[0]
        is_transcoded_flag.value = value
        is_transcoded_flag.save()
        for f in flags[1:]:
            f.delete()
    return is_transcoded_flag

def get_item_file_url(

*a, **kw)

Inheritance: ItemViewMixin.get_item_file_url

@jsonrpc_method('telemeta.get_item_export_url')
def get_item_file_url(request, public_id, extension):
    return reverse('telemeta-item-export', kwargs={'public_id': public_id, 'extension': extension})

def get_object(

self)

Inheritance: ItemViewMixin.get_object

def get_object(self):
    obj = self.model.objects.filter(code=self.kwargs['public_id'])
    if not obj:
        if self.kwargs['public_id'].isdigit():
            try:
                obj = self.model.objects.get(id=self.kwargs['public_id'])
            except self.model.DoesNotExist:
                raise Http404
        else:
            raise Http404
    else:
        obj = obj[0]
    return obj

def get_prefix(

self)

Returns the prefix to use for forms on this view

def get_prefix(self):
    """
    Returns the prefix to use for forms on this view
    """
    return self.prefix

def get_queryset(

self)

Get the queryset to look an object up against. May not be called if get_object is overridden.

def get_queryset(self):
    """
    Get the queryset to look an object up against. May not be called if
    `get_object` is overridden.
    """
    if self.queryset is None:
        if self.model:
            return self.model._default_manager.all()
        else:
            raise ImproperlyConfigured("%(cls)s is missing a queryset. Define "
                                       "%(cls)s.model, %(cls)s.queryset, or override "
                                       "%(cls)s.get_queryset()." % {
                                            'cls': self.__class__.__name__
                                    })
    return self.queryset._clone()

def get_slug_field(

self)

Get the name of a slug field to be used to look up by slug.

def get_slug_field(self):
    """
    Get the name of a slug field to be used to look up by slug.
    """
    return self.slug_field

def get_success_url(

self)

def get_success_url(self):
    return reverse_lazy('telemeta-item-detail', kwargs={'public_id': self.code})

def get_template_names(

self)

Return a list of template names to be used for the request. May not be called if render_to_response is overridden. Returns the following list:

  • the value of template_name on the view (if provided)
  • the contents of the template_name_field field on the object instance that the view is operating upon (if available)
  • <app_label>/<model_name><template_name_suffix>.html
def get_template_names(self):
    """
    Return a list of template names to be used for the request. May not be
    called if render_to_response is overridden. Returns the following list:
    * the value of ``template_name`` on the view (if provided)
    * the contents of the ``template_name_field`` field on the
      object instance that the view is operating upon (if available)
    * ``<app_label>/<model_name><template_name_suffix>.html``
    """
    try:
        names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
        # If self.template_name_field is set, grab the value of the field
        # of that name from the object; this is the most specific template
        # name, if given.
        if self.object and self.template_name_field:
            name = getattr(self.object, self.template_name_field, None)
            if name:
                names.insert(0, name)
        # The least-specific option is the default <app>/<model>_detail.html;
        # only use this if the object in question is a model.
        if isinstance(self.object, models.Model):
            names.append("%s/%s%s.html" % (
                self.object._meta.app_label,
                self.object._meta.model_name,
                self.template_name_suffix
            ))
        elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model):
            names.append("%s/%s%s.html" % (
                self.model._meta.app_label,
                self.model._meta.model_name,
                self.template_name_suffix
            ))
        # If we still haven't managed to find any template names, we should
        # re-raise the ImproperlyConfigured to alert the user.
        if not names:
            raise
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def item_previous_next(

self, item)

Inheritance: ItemViewMixin.item_previous_next

Get previous and next items inside the collection of the item

def item_previous_next(self, item):
    """Get previous and next items inside the collection of the item"""
    pks = []
    items = MediaItem.objects.filter(collection=item.collection)
    items = items.order_by('code', 'old_code')
    if len(items) > 1:
        for it in items:
            pks.append(it.pk)
        for pk in pks:
            if pk == item.pk:
                if pk == pks[0]:
                    previous_pk = pks[-1]
                    next_pk = pks[1]
                elif pk == pks[-1]:
                    previous_pk = pks[-2]
                    next_pk = pks[0]
                else:
                    previous_pk = pks[pks.index(pk) - 1]
                    next_pk = pks[pks.index(pk) + 1]
                for it in items:
                    if it.pk == previous_pk:
                        previous = it
                    if it.pk == next_pk:
                        next = it
                previous = previous.public_id
                next = next.public_id
    else:
        previous = item.public_id
        next = item.public_id
    return previous, next

def options(

self, request, *args, **kwargs)

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def post(

self, request, *args, **kwargs)

def post(self, request, *args, **kwargs):
    self.object = self.get_object()
    return super(BaseUpdateWithInlinesView, self).post(request, *args, **kwargs)

def put(

self, *args, **kwargs)

def put(self, *args, **kwargs):
    return self.post(*args, **kwargs)

def render_to_response(

self, context, **response_kwargs)

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemEnumListView

class ItemEnumListView(ItemListView):
    template_name = 'telemeta/media_item_enum_list.html'

    def get_context_data(self, **kwargs):
        context = super(ItemListView, self).get_context_data(**kwargs)
        context['enum'] = self.request.path.split('/')[3]
        context['id'] = self.request.path.split('/')[4]
        context['count'] = self.object_list.count()
        context['keyword'] = False
        context['enum_name'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name
        context['enum_value'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4])
        context['url_all'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item/list"
        context['url_unpublished'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item_unpublished/list/"
        context['url_published'] = "/admin/enumerations/" + context['enum'] +"/"+context['id'] + "/item_published/list/"
        context['url_sound'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item_sound/list/"
        return context

    def get_queryset(self):
        enumeration = self.get_enumeration(self.request.path.split('/')[3])
        queryset = self.get_item(enumeration.objects.filter(id=self.request.path.split('/')[4]).get())
        print type(queryset)
        return queryset

    def get_item(self, enum):
        f = MediaItem._meta.get_all_field_names()
        for field in f:
            if field in enum._meta.db_table.replace(" ", "_"):
                atr = field;
        atr = atr + "_id"
        lookup = "%s__exact" % atr
        return MediaItem.objects.filter(**{lookup: enum.__getattribute__("id")})

    def get_enumeration(self, id):
        from django.db.models import get_models
        models = get_models(telemeta.models)
        for model in models:
            if model._meta.module_name == id:
                break
        if model._meta.module_name != id:
            return None
        return model

Ancestors (in MRO)

  • ItemEnumListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemListView.allow_empty

var content_type

Inheritance: ItemListView.content_type

var context_object_name

Inheritance: ItemListView.context_object_name

var http_method_names

Inheritance: ItemListView.http_method_names

var model

Inheritance: ItemListView.model

var page_kwarg

Inheritance: ItemListView.page_kwarg

var paginate_by

Inheritance: ItemListView.paginate_by

var paginate_orphans

Inheritance: ItemListView.paginate_orphans

var paginator_class

Inheritance: ItemListView.paginator_class

var queryset

Inheritance: ItemListView.queryset

var response_class

Inheritance: ItemListView.response_class

var template_name

Inheritance: ItemListView.template_name

var template_name_suffix

Inheritance: ItemListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemListView, self).get_context_data(**kwargs)
    context['enum'] = self.request.path.split('/')[3]
    context['id'] = self.request.path.split('/')[4]
    context['count'] = self.object_list.count()
    context['keyword'] = False
    context['enum_name'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name
    context['enum_value'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4])
    context['url_all'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item/list"
    context['url_unpublished'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item_unpublished/list/"
    context['url_published'] = "/admin/enumerations/" + context['enum'] +"/"+context['id'] + "/item_published/list/"
    context['url_sound'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item_sound/list/"
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_enumeration(

self, id)

def get_enumeration(self, id):
    from django.db.models import get_models
    models = get_models(telemeta.models)
    for model in models:
        if model._meta.module_name == id:
            break
    if model._meta.module_name != id:
        return None
    return model

def get_item(

self, enum)

def get_item(self, enum):
    f = MediaItem._meta.get_all_field_names()
    for field in f:
        if field in enum._meta.db_table.replace(" ", "_"):
            atr = field;
    atr = atr + "_id"
    lookup = "%s__exact" % atr
    return MediaItem.objects.filter(**{lookup: enum.__getattribute__("id")})

def get_paginate_by(

self, queryset)

Inheritance: ItemListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemListView.get_queryset

Get the list of items for this view. This must be an iterable, and may be a queryset (in which qs-specific behavior will be enabled).

def get_queryset(self):
    enumeration = self.get_enumeration(self.request.path.split('/')[3])
    queryset = self.get_item(enumeration.objects.filter(id=self.request.path.split('/')[4]).get())
    print type(queryset)
    return queryset

def get_template_names(

self)

Inheritance: ItemListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemInstrumentListView

class ItemInstrumentListView(ItemListView):

    template_name = "telemeta/media_item_instrument_list.html"

    def get_queryset(self):
        return MediaItem.objects.filter(performances__instrument__id=self.kwargs['value_id'])

    def get_context_data(self, **kwargs):
        context = super(ItemInstrumentListView, self).get_context_data(**kwargs)

        context['nom'] = Instrument.objects.get(id=self.kwargs['value_id']).name
        context['id'] = self.kwargs['value_id']

        return context

Ancestors (in MRO)

  • ItemInstrumentListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemListView.allow_empty

var content_type

Inheritance: ItemListView.content_type

var context_object_name

Inheritance: ItemListView.context_object_name

var http_method_names

Inheritance: ItemListView.http_method_names

var model

Inheritance: ItemListView.model

var page_kwarg

Inheritance: ItemListView.page_kwarg

var paginate_by

Inheritance: ItemListView.paginate_by

var paginate_orphans

Inheritance: ItemListView.paginate_orphans

var paginator_class

Inheritance: ItemListView.paginator_class

var queryset

Inheritance: ItemListView.queryset

var response_class

Inheritance: ItemListView.response_class

var template_name

Inheritance: ItemListView.template_name

var template_name_suffix

Inheritance: ItemListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemInstrumentListView, self).get_context_data(**kwargs)
    context['nom'] = Instrument.objects.get(id=self.kwargs['value_id']).name
    context['id'] = self.kwargs['value_id']
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

Inheritance: ItemListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemListView.get_queryset

Get the list of items for this view. This must be an iterable, and may be a queryset (in which qs-specific behavior will be enabled).

def get_queryset(self):
    return MediaItem.objects.filter(performances__instrument__id=self.kwargs['value_id'])

def get_template_names(

self)

Inheritance: ItemListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemInstrumentPublishedListView

class ItemInstrumentPublishedListView(ItemInstrumentListView):

    def get_queryset(self):
        return super(ItemInstrumentPublishedListView, self).get_queryset().filter(collection__code__contains='_E_').order_by('code', 'old_code')

Ancestors (in MRO)

  • ItemInstrumentPublishedListView
  • ItemInstrumentListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemInstrumentListView.allow_empty

var content_type

Inheritance: ItemInstrumentListView.content_type

var context_object_name

Inheritance: ItemInstrumentListView.context_object_name

var http_method_names

Inheritance: ItemInstrumentListView.http_method_names

var model

Inheritance: ItemInstrumentListView.model

var page_kwarg

Inheritance: ItemInstrumentListView.page_kwarg

var paginate_by

Inheritance: ItemInstrumentListView.paginate_by

var paginate_orphans

Inheritance: ItemInstrumentListView.paginate_orphans

var paginator_class

Inheritance: ItemInstrumentListView.paginator_class

var queryset

Inheritance: ItemInstrumentListView.queryset

var response_class

Inheritance: ItemInstrumentListView.response_class

var template_name

Inheritance: ItemInstrumentListView.template_name

var template_name_suffix

Inheritance: ItemInstrumentListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemInstrumentListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemInstrumentListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemInstrumentListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemInstrumentListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemInstrumentListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemInstrumentListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemInstrumentListView, self).get_context_data(**kwargs)
    context['nom'] = Instrument.objects.get(id=self.kwargs['value_id']).name
    context['id'] = self.kwargs['value_id']
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemInstrumentListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

Inheritance: ItemInstrumentListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemInstrumentListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemInstrumentListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemInstrumentListView.get_queryset

def get_queryset(self):
    return super(ItemInstrumentPublishedListView, self).get_queryset().filter(collection__code__contains='_E_').order_by('code', 'old_code')

def get_template_names(

self)

Inheritance: ItemInstrumentListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemInstrumentListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemInstrumentListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemInstrumentListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemInstrumentListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemInstrumentSoundListView

class ItemInstrumentSoundListView(ItemInstrumentListView):

    def get_queryset(self):
        return super(ItemInstrumentSoundListView, self).get_queryset().sound().order_by('code', 'old_code')

Ancestors (in MRO)

  • ItemInstrumentSoundListView
  • ItemInstrumentListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemInstrumentListView.allow_empty

var content_type

Inheritance: ItemInstrumentListView.content_type

var context_object_name

Inheritance: ItemInstrumentListView.context_object_name

var http_method_names

Inheritance: ItemInstrumentListView.http_method_names

var model

Inheritance: ItemInstrumentListView.model

var page_kwarg

Inheritance: ItemInstrumentListView.page_kwarg

var paginate_by

Inheritance: ItemInstrumentListView.paginate_by

var paginate_orphans

Inheritance: ItemInstrumentListView.paginate_orphans

var paginator_class

Inheritance: ItemInstrumentListView.paginator_class

var queryset

Inheritance: ItemInstrumentListView.queryset

var response_class

Inheritance: ItemInstrumentListView.response_class

var template_name

Inheritance: ItemInstrumentListView.template_name

var template_name_suffix

Inheritance: ItemInstrumentListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemInstrumentListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemInstrumentListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemInstrumentListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemInstrumentListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemInstrumentListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemInstrumentListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemInstrumentListView, self).get_context_data(**kwargs)
    context['nom'] = Instrument.objects.get(id=self.kwargs['value_id']).name
    context['id'] = self.kwargs['value_id']
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemInstrumentListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

Inheritance: ItemInstrumentListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemInstrumentListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemInstrumentListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemInstrumentListView.get_queryset

def get_queryset(self):
    return super(ItemInstrumentSoundListView, self).get_queryset().sound().order_by('code', 'old_code')

def get_template_names(

self)

Inheritance: ItemInstrumentListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemInstrumentListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemInstrumentListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemInstrumentListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemInstrumentListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemInstrumentUnpublishedListView

class ItemInstrumentUnpublishedListView(ItemInstrumentListView):

    def get_queryset(self):
        return super(ItemInstrumentUnpublishedListView, self).get_queryset().filter(collection__code__contains='_I_').order_by('code', 'old_code')

Ancestors (in MRO)

  • ItemInstrumentUnpublishedListView
  • ItemInstrumentListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemInstrumentListView.allow_empty

var content_type

Inheritance: ItemInstrumentListView.content_type

var context_object_name

Inheritance: ItemInstrumentListView.context_object_name

var http_method_names

Inheritance: ItemInstrumentListView.http_method_names

var model

Inheritance: ItemInstrumentListView.model

var page_kwarg

Inheritance: ItemInstrumentListView.page_kwarg

var paginate_by

Inheritance: ItemInstrumentListView.paginate_by

var paginate_orphans

Inheritance: ItemInstrumentListView.paginate_orphans

var paginator_class

Inheritance: ItemInstrumentListView.paginator_class

var queryset

Inheritance: ItemInstrumentListView.queryset

var response_class

Inheritance: ItemInstrumentListView.response_class

var template_name

Inheritance: ItemInstrumentListView.template_name

var template_name_suffix

Inheritance: ItemInstrumentListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemInstrumentListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemInstrumentListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemInstrumentListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemInstrumentListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemInstrumentListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemInstrumentListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemInstrumentListView, self).get_context_data(**kwargs)
    context['nom'] = Instrument.objects.get(id=self.kwargs['value_id']).name
    context['id'] = self.kwargs['value_id']
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemInstrumentListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

Inheritance: ItemInstrumentListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemInstrumentListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemInstrumentListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemInstrumentListView.get_queryset

def get_queryset(self):
    return super(ItemInstrumentUnpublishedListView, self).get_queryset().filter(collection__code__contains='_I_').order_by('code', 'old_code')

def get_template_names(

self)

Inheritance: ItemInstrumentListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemInstrumentListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemInstrumentListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemInstrumentListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemInstrumentListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemKeywordListView

class ItemKeywordListView(ItemListView):
    template_name = 'telemeta/media_item_enum_list.html'


    def get_context_data(self, **kwargs):
        context = super(ItemListView, self).get_context_data(**kwargs)
        context['enum'] = self.request.path.split('/')[3]
        context['id'] = self.request.path.split('/')[4]
        context['count'] = self.object_list.count()
        context['keyword'] = True
        context['enum_name'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name
        context['enum_value'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4])
        context['url_all'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item/list"
        context['url_unpublished'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_unpublished/list/"
        context['url_published'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_published/list/"
        context['url_sound'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_published/list/"

        context['argument'] = [context['enum'], context['id']]

        return context

    def get_queryset(self):
        queryset = self.get_item(self.request.path.split('/')[4])
        return queryset

    def get_item(self, id):
        c = []
        for m  in MediaItemKeyword.objects.filter(keyword_id=id):
            c.append(m.__getattribute__("item_id"))
        return  MediaItem.objects.filter(id__in=c)


    def get_enumeration(self, id):
        from django.db.models import get_models
        models = get_models(telemeta.models)
        for model in models:
            if model._meta.module_name == id:
                break
        if model._meta.module_name != id:
            return None
        return model

Ancestors (in MRO)

  • ItemKeywordListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemListView.allow_empty

var content_type

Inheritance: ItemListView.content_type

var context_object_name

Inheritance: ItemListView.context_object_name

var http_method_names

Inheritance: ItemListView.http_method_names

var model

Inheritance: ItemListView.model

var page_kwarg

Inheritance: ItemListView.page_kwarg

var paginate_by

Inheritance: ItemListView.paginate_by

var paginate_orphans

Inheritance: ItemListView.paginate_orphans

var paginator_class

Inheritance: ItemListView.paginator_class

var queryset

Inheritance: ItemListView.queryset

var response_class

Inheritance: ItemListView.response_class

var template_name

Inheritance: ItemListView.template_name

var template_name_suffix

Inheritance: ItemListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemListView, self).get_context_data(**kwargs)
    context['enum'] = self.request.path.split('/')[3]
    context['id'] = self.request.path.split('/')[4]
    context['count'] = self.object_list.count()
    context['keyword'] = True
    context['enum_name'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name
    context['enum_value'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4])
    context['url_all'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item/list"
    context['url_unpublished'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_unpublished/list/"
    context['url_published'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_published/list/"
    context['url_sound'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_published/list/"
    context['argument'] = [context['enum'], context['id']]
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_enumeration(

self, id)

def get_enumeration(self, id):
    from django.db.models import get_models
    models = get_models(telemeta.models)
    for model in models:
        if model._meta.module_name == id:
            break
    if model._meta.module_name != id:
        return None
    return model

def get_item(

self, id)

def get_item(self, id):
    c = []
    for m  in MediaItemKeyword.objects.filter(keyword_id=id):
        c.append(m.__getattribute__("item_id"))
    return  MediaItem.objects.filter(id__in=c)

def get_paginate_by(

self, queryset)

Inheritance: ItemListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemListView.get_queryset

Get the list of items for this view. This must be an iterable, and may be a queryset (in which qs-specific behavior will be enabled).

def get_queryset(self):
    queryset = self.get_item(self.request.path.split('/')[4])
    return queryset

def get_template_names(

self)

Inheritance: ItemListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemKeywordPublishedListView

class ItemKeywordPublishedListView(ItemKeywordListView):

    def get_queryset(self):
        c=ItemKeywordListView()
        queryset = self.get_item(self.request.path.split('/')[4],c)
        return queryset

    def get_item(self, id,c):
        return c.get_item(id).filter(code__contains='_E_')

Ancestors (in MRO)

  • ItemKeywordPublishedListView
  • ItemKeywordListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemKeywordListView.allow_empty

var content_type

Inheritance: ItemKeywordListView.content_type

var context_object_name

Inheritance: ItemKeywordListView.context_object_name

var http_method_names

Inheritance: ItemKeywordListView.http_method_names

var model

Inheritance: ItemKeywordListView.model

var page_kwarg

Inheritance: ItemKeywordListView.page_kwarg

var paginate_by

Inheritance: ItemKeywordListView.paginate_by

var paginate_orphans

Inheritance: ItemKeywordListView.paginate_orphans

var paginator_class

Inheritance: ItemKeywordListView.paginator_class

var queryset

Inheritance: ItemKeywordListView.queryset

var response_class

Inheritance: ItemKeywordListView.response_class

var template_name

Inheritance: ItemKeywordListView.template_name

var template_name_suffix

Inheritance: ItemKeywordListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemKeywordListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemKeywordListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemKeywordListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemKeywordListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemKeywordListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemKeywordListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemListView, self).get_context_data(**kwargs)
    context['enum'] = self.request.path.split('/')[3]
    context['id'] = self.request.path.split('/')[4]
    context['count'] = self.object_list.count()
    context['keyword'] = True
    context['enum_name'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name
    context['enum_value'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4])
    context['url_all'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item/list"
    context['url_unpublished'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_unpublished/list/"
    context['url_published'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_published/list/"
    context['url_sound'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_published/list/"
    context['argument'] = [context['enum'], context['id']]
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemKeywordListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_enumeration(

self, id)

Inheritance: ItemKeywordListView.get_enumeration

def get_enumeration(self, id):
    from django.db.models import get_models
    models = get_models(telemeta.models)
    for model in models:
        if model._meta.module_name == id:
            break
    if model._meta.module_name != id:
        return None
    return model

def get_item(

self, id, c)

Inheritance: ItemKeywordListView.get_item

def get_item(self, id,c):
    return c.get_item(id).filter(code__contains='_E_')

def get_paginate_by(

self, queryset)

Inheritance: ItemKeywordListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemKeywordListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemKeywordListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemKeywordListView.get_queryset

def get_queryset(self):
    c=ItemKeywordListView()
    queryset = self.get_item(self.request.path.split('/')[4],c)
    return queryset

def get_template_names(

self)

Inheritance: ItemKeywordListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemKeywordListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemKeywordListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemKeywordListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemKeywordListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemKeywordSoundListView

class ItemKeywordSoundListView(ItemKeywordListView):

    def get_queryset(self):
        c = ItemKeywordListView()
        queryset = self.get_item(self.request.path.split('/')[4], c)
        return queryset

    def get_item(self, id, c):
        return c.get_item(id).sound().order_by('code', 'old_code')

Ancestors (in MRO)

  • ItemKeywordSoundListView
  • ItemKeywordListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemKeywordListView.allow_empty

var content_type

Inheritance: ItemKeywordListView.content_type

var context_object_name

Inheritance: ItemKeywordListView.context_object_name

var http_method_names

Inheritance: ItemKeywordListView.http_method_names

var model

Inheritance: ItemKeywordListView.model

var page_kwarg

Inheritance: ItemKeywordListView.page_kwarg

var paginate_by

Inheritance: ItemKeywordListView.paginate_by

var paginate_orphans

Inheritance: ItemKeywordListView.paginate_orphans

var paginator_class

Inheritance: ItemKeywordListView.paginator_class

var queryset

Inheritance: ItemKeywordListView.queryset

var response_class

Inheritance: ItemKeywordListView.response_class

var template_name

Inheritance: ItemKeywordListView.template_name

var template_name_suffix

Inheritance: ItemKeywordListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemKeywordListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemKeywordListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemKeywordListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemKeywordListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemKeywordListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemKeywordListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemListView, self).get_context_data(**kwargs)
    context['enum'] = self.request.path.split('/')[3]
    context['id'] = self.request.path.split('/')[4]
    context['count'] = self.object_list.count()
    context['keyword'] = True
    context['enum_name'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name
    context['enum_value'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4])
    context['url_all'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item/list"
    context['url_unpublished'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_unpublished/list/"
    context['url_published'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_published/list/"
    context['url_sound'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_published/list/"
    context['argument'] = [context['enum'], context['id']]
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemKeywordListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_enumeration(

self, id)

Inheritance: ItemKeywordListView.get_enumeration

def get_enumeration(self, id):
    from django.db.models import get_models
    models = get_models(telemeta.models)
    for model in models:
        if model._meta.module_name == id:
            break
    if model._meta.module_name != id:
        return None
    return model

def get_item(

self, id, c)

Inheritance: ItemKeywordListView.get_item

def get_item(self, id, c):
    return c.get_item(id).sound().order_by('code', 'old_code')

def get_paginate_by(

self, queryset)

Inheritance: ItemKeywordListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemKeywordListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemKeywordListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemKeywordListView.get_queryset

def get_queryset(self):
    c = ItemKeywordListView()
    queryset = self.get_item(self.request.path.split('/')[4], c)
    return queryset

def get_template_names(

self)

Inheritance: ItemKeywordListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemKeywordListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemKeywordListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemKeywordListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemKeywordListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemKeywordUnpublishedListView

class ItemKeywordUnpublishedListView(ItemKeywordListView):

    def get_queryset(self):
        c=ItemKeywordListView()
        queryset = self.get_item(self.request.path.split('/')[4],c)
        return queryset

    def get_item(self, id,c):
        return c.get_item(id).filter(code__contains='_I_')

Ancestors (in MRO)

  • ItemKeywordUnpublishedListView
  • ItemKeywordListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemKeywordListView.allow_empty

var content_type

Inheritance: ItemKeywordListView.content_type

var context_object_name

Inheritance: ItemKeywordListView.context_object_name

var http_method_names

Inheritance: ItemKeywordListView.http_method_names

var model

Inheritance: ItemKeywordListView.model

var page_kwarg

Inheritance: ItemKeywordListView.page_kwarg

var paginate_by

Inheritance: ItemKeywordListView.paginate_by

var paginate_orphans

Inheritance: ItemKeywordListView.paginate_orphans

var paginator_class

Inheritance: ItemKeywordListView.paginator_class

var queryset

Inheritance: ItemKeywordListView.queryset

var response_class

Inheritance: ItemKeywordListView.response_class

var template_name

Inheritance: ItemKeywordListView.template_name

var template_name_suffix

Inheritance: ItemKeywordListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemKeywordListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemKeywordListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemKeywordListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemKeywordListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemKeywordListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemKeywordListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemListView, self).get_context_data(**kwargs)
    context['enum'] = self.request.path.split('/')[3]
    context['id'] = self.request.path.split('/')[4]
    context['count'] = self.object_list.count()
    context['keyword'] = True
    context['enum_name'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name
    context['enum_value'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4])
    context['url_all'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item/list"
    context['url_unpublished'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_unpublished/list/"
    context['url_published'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_published/list/"
    context['url_sound'] = "/admin/enumerations/"+context['enum']+"/"+context['id']+"/keyword_item_published/list/"
    context['argument'] = [context['enum'], context['id']]
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemKeywordListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_enumeration(

self, id)

Inheritance: ItemKeywordListView.get_enumeration

def get_enumeration(self, id):
    from django.db.models import get_models
    models = get_models(telemeta.models)
    for model in models:
        if model._meta.module_name == id:
            break
    if model._meta.module_name != id:
        return None
    return model

def get_item(

self, id, c)

Inheritance: ItemKeywordListView.get_item

def get_item(self, id,c):
    return c.get_item(id).filter(code__contains='_I_')

def get_paginate_by(

self, queryset)

Inheritance: ItemKeywordListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemKeywordListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemKeywordListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemKeywordListView.get_queryset

def get_queryset(self):
    c=ItemKeywordListView()
    queryset = self.get_item(self.request.path.split('/')[4],c)
    return queryset

def get_template_names(

self)

Inheritance: ItemKeywordListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemKeywordListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemKeywordListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemKeywordListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemKeywordListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemListView

class ItemListView(ListView):

    model = MediaItem
    template_name = "telemeta/mediaitem_list.html"
    queryset = MediaItem.objects.enriched().order_by('code', 'old_code')

    def get_paginate_by(self, queryset):
        return self.request.GET.get('results_page', 20)

    def get_context_data(self, **kwargs):
        context = super(ItemListView, self).get_context_data(**kwargs)
        context['count'] = self.object_list.count()
        context['results_page'] = int(self.request.GET.get('results_page', 20))
        return context

Ancestors (in MRO)

  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

var content_type

var context_object_name

var http_method_names

var model

var page_kwarg

var paginate_by

var paginate_orphans

var paginator_class

var queryset

var response_class

var template_name

var template_name_suffix

Methods

def __init__(

self, **kwargs)

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

def get_context_data(self, **kwargs):
    context = super(ItemListView, self).get_context_data(**kwargs)
    context['count'] = self.object_list.count()
    context['results_page'] = int(self.request.GET.get('results_page', 20))
    return context

def get_context_object_name(

self, object_list)

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Get the list of items for this view. This must be an iterable, and may be a queryset (in which qs-specific behavior will be enabled).

def get_queryset(self):
    """
    Get the list of items for this view. This must be an iterable, and may
    be a queryset (in which qs-specific behavior will be enabled).
    """
    if self.queryset is not None:
        queryset = self.queryset
        if hasattr(queryset, '_clone'):
            queryset = queryset._clone()
    elif self.model is not None:
        queryset = self.model._default_manager.all()
    else:
        raise ImproperlyConfigured("'%s' must define 'queryset' or 'model'"
                                   % self.__class__.__name__)
    return queryset

def get_template_names(

self)

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemListViewFullAccess

class ItemListViewFullAccess(ListView):

    model = MediaItem
    template_name = "telemeta/mediaitem_list.html"
    paginate_by = 20
    queryset = MediaItem.objects.enriched().filter(Q(collection__public_access="full") | Q(public_access="full")).sound().exclude(collection__public_access="none").order_by('code', 'old_code')

    def get_context_data(self, **kwargs):
        context = super(ItemListViewFullAccess, self).get_context_data(**kwargs)
        context['count'] = self.object_list.count()
        return context

Ancestors (in MRO)

  • ItemListViewFullAccess
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

var content_type

var context_object_name

var http_method_names

var model

var page_kwarg

var paginate_by

var paginate_orphans

var paginator_class

var queryset

var response_class

var template_name

var template_name_suffix

Methods

def __init__(

self, **kwargs)

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

def get_context_data(self, **kwargs):
    context = super(ItemListViewFullAccess, self).get_context_data(**kwargs)
    context['count'] = self.object_list.count()
    return context

def get_context_object_name(

self, object_list)

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

Get the number of items to paginate by, or None for no pagination.

def get_paginate_by(self, queryset):
    """
    Get the number of items to paginate by, or ``None`` for no pagination.
    """
    return self.paginate_by

def get_paginate_orphans(

self)

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Get the list of items for this view. This must be an iterable, and may be a queryset (in which qs-specific behavior will be enabled).

def get_queryset(self):
    """
    Get the list of items for this view. This must be an iterable, and may
    be a queryset (in which qs-specific behavior will be enabled).
    """
    if self.queryset is not None:
        queryset = self.queryset
        if hasattr(queryset, '_clone'):
            queryset = queryset._clone()
    elif self.model is not None:
        queryset = self.model._default_manager.all()
    else:
        raise ImproperlyConfigured("'%s' must define 'queryset' or 'model'"
                                   % self.__class__.__name__)
    return queryset

def get_template_names(

self)

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemMarkerJsonView

class ItemMarkerJsonView(View):

    model = MediaItem

    def get(self, request, *args, **kwargs):
        code = self.kwargs['public_id']
        marker_view = MarkerView()
        item = MediaItem.objects.get(code=code)
        markers = marker_view.get_markers(item.id)
        if markers:
            data = json.dumps(markers)
        else:
            data = ''
        response = HttpResponse(data, content_type='application/json')
        response['Content-Disposition'] = "attachment; filename=%s.%s" % \
            (item.code, 'json')
        return response

Ancestors (in MRO)

Class variables

var http_method_names

var model

Methods

def __init__(

self, **kwargs)

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

def get(self, request, *args, **kwargs):
    code = self.kwargs['public_id']
    marker_view = MarkerView()
    item = MediaItem.objects.get(code=code)
    markers = marker_view.get_markers(item.id)
    if markers:
        data = json.dumps(markers)
    else:
        data = ''
    response = HttpResponse(data, content_type='application/json')
    response['Content-Disposition'] = "attachment; filename=%s.%s" % \
        (item.code, 'json')
    return response

def http_method_not_allowed(

self, request, *args, **kwargs)

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

class ItemPlayerDefaultView

class ItemPlayerDefaultView(ItemDetailView):

    template_name = 'telemeta/mediaitem_player.html'

Ancestors (in MRO)

  • ItemPlayerDefaultView
  • ItemDetailView
  • ItemViewMixin
  • ItemBaseMixin
  • telemeta.views.core.TelemetaBaseMixin
  • django.views.generic.detail.DetailView
  • django.views.generic.detail.SingleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.detail.BaseDetailView
  • django.views.generic.detail.SingleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var CACHE_DIR

Inheritance: ItemDetailView.CACHE_DIR

var MEDIA_ROOT

Inheritance: ItemDetailView.MEDIA_ROOT

var analyzers

Inheritance: ItemDetailView.analyzers

var auto_zoom

Inheritance: ItemDetailView.auto_zoom

var cache_data

Inheritance: ItemDetailView.cache_data

var cache_export

Inheritance: ItemDetailView.cache_export

var cache_tmp

Inheritance: ItemDetailView.cache_tmp

var content_type

Inheritance: ItemDetailView.content_type

var context_object_name

Inheritance: ItemDetailView.context_object_name

var decoders

Inheritance: ItemDetailView.decoders

var default_grapher_id

Inheritance: ItemDetailView.default_grapher_id

var default_grapher_sizes

Inheritance: ItemDetailView.default_grapher_sizes

var encoders

Inheritance: ItemDetailView.encoders

var export_enabled

Inheritance: ItemDetailView.export_enabled

var export_formats

Inheritance: ItemDetailView.export_formats

var form_class

Inheritance: ItemDetailView.form_class

var graphers

Inheritance: ItemDetailView.graphers

var http_method_names

Inheritance: ItemDetailView.http_method_names

var inlines

Inheritance: ItemDetailView.inlines

var model

Inheritance: ItemDetailView.model

var pk_url_kwarg

Inheritance: ItemDetailView.pk_url_kwarg

var public_graphers

Inheritance: ItemDetailView.public_graphers

var queryset

Inheritance: ItemDetailView.queryset

var response_class

Inheritance: ItemDetailView.response_class

var slug_field

Inheritance: ItemDetailView.slug_field

var slug_url_kwarg

Inheritance: ItemDetailView.slug_url_kwarg

var template_name

Inheritance: ItemDetailView.template_name

var template_name_field

Inheritance: ItemDetailView.template_name_field

var template_name_suffix

Inheritance: ItemDetailView.template_name_suffix

var value_analyzers

Inheritance: ItemDetailView.value_analyzers

Methods

def __init__(

self, **kwargs)

Inheritance: ItemDetailView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemDetailView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemDetailView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemDetailView.get

def get(self, request, *args, **kwargs):
    self.object = self.get_object()
    context = self.get_context_data(object=self.object)
    return self.render_to_response(context)

def get_context_data(

self, **kwargs)

Inheritance: ItemDetailView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemDetailView, self).get_context_data(**kwargs)
    public_id = get_kwargs_or_none('public_id', self.kwargs)
    marker_id = get_kwargs_or_none('marker_id', self.kwargs)
    width = get_kwargs_or_none('width', self.kwargs)
    height = get_kwargs_or_none('height', self.kwargs)
    # get item with one of its given marker_id
    if not public_id and marker_id:
        marker = MediaItemMarker.objects.get(public_id=marker_id)
        item_id = marker.item_id
        item = MediaItem.objects.get(id=item_id)
    else:
        item = self.get_object()
    access = get_item_access(item, self.request.user)
    previous, next = self.item_previous_next(item)
    # Corresponding TimeSide Item
    source, source_type = item.get_source()
    # if source:
    #     ts_item, c = ts.models.Item.objects.get_or_create(**{source_type: source})
    #     if c:
    #         ts_item.title = item.title
    #         ts_item.save()
    self.item_analyze(item)
    # FIXME: use mimetypes.guess_type
    if 'quicktime' in self.mime_type:
        self.mime_type = 'video/mp4'
    playlists = get_playlists_names(self.request)
    rang = []
    for i in range(len(playlists)):
        for resource in playlists[i]['playlist'].resources.all():
            if int(resource.resource_id) == item.id:
                rang.append(i)
                break
    related_media = MediaItemRelated.objects.filter(item=item)
    check_related_media(related_media)
    revisions = Revision.objects.filter(element_type='item', element_id=item.id).order_by('-time')
    if revisions:
        last_revision = revisions[0]
    else:
        last_revision = None
    item_format = ''
    if Format.objects.filter(item=item):
        item_format = item.format.get()
    context['item'] = item
    context['export_formats'] = self.get_export_formats()
    context['visualizers'] = self.get_graphers()
    context['auto_zoom'] = self.auto_zoom
    context['audio_export_enabled'] = self.export_enabled
    context['previous'] = previous
    context['next'] = next
    context['marker'] = marker_id
    context['playlists'] = playlists
    context['access'] = access
    context['width'] = width
    context['height'] = height
    context['related_media'] = related_media
    context['mime_type'] = self.mime_type
    context['last_revision'] = last_revision
    context['format'] = item_format
    context['private_extra_types'] = private_extra_types.values()
    context['site'] = 'http://' + Site.objects.all()[0].name
    context['rang_item_playlist'] = rang
    # if ts_item:
    #     context['ts_item_id'] = ts_item.pk
    # else:
    #     context['ts_item_id'] = None
    return context

def get_context_object_name(

self, obj)

Inheritance: ItemDetailView.get_context_object_name

Get the name to use for the object.

def get_context_object_name(self, obj):
    """
    Get the name to use for the object.
    """
    if self.context_object_name:
        return self.context_object_name
    elif isinstance(obj, models.Model):
        return obj._meta.model_name
    else:
        return None

def get_export_formats(

self)

Inheritance: ItemDetailView.get_export_formats

def get_export_formats(self):
    formats = []
    for encoder in self.encoders:
        if encoder.file_extension() in self.export_formats:
            formats.append({'name': encoder.format(),
                            'extension': encoder.file_extension()})
    return formats

def get_grapher(

self, id)

Inheritance: ItemDetailView.get_grapher

def get_grapher(self, id):
    for grapher in self.graphers:
        if grapher.id() == id:
            break
    return grapher

def get_graphers(

self)

Inheritance: ItemDetailView.get_graphers

def get_graphers(self):
    graphers = []
    user = self.request.user
    graphers_access = (user.is_staff
                       or user.is_superuser
                       or user.has_perm('can_run_analysis'))
    for grapher in self.graphers:
        if (not graphers_access
            and grapher.id() not in self.public_graphers):
            continue
        if grapher.id() == self.default_grapher_id:
            graphers.insert(0, {'name': grapher.name(), 'id': grapher.id()})
        elif not hasattr(grapher, '_staging'):
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
        elif not grapher._staging:
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
    return graphers

def get_is_transcoded_flag(

self, item, mime_type)

Inheritance: ItemDetailView.get_is_transcoded_flag

def get_is_transcoded_flag(self, item, mime_type):
    try:
        is_transcoded_flag, c = MediaItemTranscodingFlag.objects.get_or_create(
            item=item,
            mime_type=mime_type,
            defaults={'value': False})
    except MediaItemTranscodingFlag.MultipleObjectsReturned:
        flags = MediaItemTranscodingFlag.objects.filter(
            item=item,
            mime_type=mime_type)
        value = all([f.value for f in flags])
        is_transcoded_flag = flags[0]
        is_transcoded_flag.value = value
        is_transcoded_flag.save()
        for f in flags[1:]:
            f.delete()
    return is_transcoded_flag

def get_item_file_url(

*a, **kw)

Inheritance: ItemDetailView.get_item_file_url

@jsonrpc_method('telemeta.get_item_export_url')
def get_item_file_url(request, public_id, extension):
    return reverse('telemeta-item-export', kwargs={'public_id': public_id, 'extension': extension})

def get_object(

self)

Inheritance: ItemDetailView.get_object

def get_object(self):
    obj = self.model.objects.filter(code=self.kwargs['public_id'])
    if not obj:
        if self.kwargs['public_id'].isdigit():
            try:
                obj = self.model.objects.get(id=self.kwargs['public_id'])
            except self.model.DoesNotExist:
                raise Http404
        else:
            raise Http404
    else:
        obj = obj[0]
    return obj

def get_queryset(

self)

Inheritance: ItemDetailView.get_queryset

Get the queryset to look an object up against. May not be called if get_object is overridden.

def get_queryset(self):
    """
    Get the queryset to look an object up against. May not be called if
    `get_object` is overridden.
    """
    if self.queryset is None:
        if self.model:
            return self.model._default_manager.all()
        else:
            raise ImproperlyConfigured("%(cls)s is missing a queryset. Define "
                                       "%(cls)s.model, %(cls)s.queryset, or override "
                                       "%(cls)s.get_queryset()." % {
                                            'cls': self.__class__.__name__
                                    })
    return self.queryset._clone()

def get_slug_field(

self)

Inheritance: ItemDetailView.get_slug_field

Get the name of a slug field to be used to look up by slug.

def get_slug_field(self):
    """
    Get the name of a slug field to be used to look up by slug.
    """
    return self.slug_field

def get_template_names(

self)

Inheritance: ItemDetailView.get_template_names

Return a list of template names to be used for the request. May not be called if render_to_response is overridden. Returns the following list:

  • the value of template_name on the view (if provided)
  • the contents of the template_name_field field on the object instance that the view is operating upon (if available)
  • <app_label>/<model_name><template_name_suffix>.html
def get_template_names(self):
    """
    Return a list of template names to be used for the request. May not be
    called if render_to_response is overridden. Returns the following list:
    * the value of ``template_name`` on the view (if provided)
    * the contents of the ``template_name_field`` field on the
      object instance that the view is operating upon (if available)
    * ``<app_label>/<model_name><template_name_suffix>.html``
    """
    try:
        names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
        # If self.template_name_field is set, grab the value of the field
        # of that name from the object; this is the most specific template
        # name, if given.
        if self.object and self.template_name_field:
            name = getattr(self.object, self.template_name_field, None)
            if name:
                names.insert(0, name)
        # The least-specific option is the default <app>/<model>_detail.html;
        # only use this if the object in question is a model.
        if isinstance(self.object, models.Model):
            names.append("%s/%s%s.html" % (
                self.object._meta.app_label,
                self.object._meta.model_name,
                self.template_name_suffix
            ))
        elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model):
            names.append("%s/%s%s.html" % (
                self.model._meta.app_label,
                self.model._meta.model_name,
                self.template_name_suffix
            ))
        # If we still haven't managed to find any template names, we should
        # re-raise the ImproperlyConfigured to alert the user.
        if not names:
            raise
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemDetailView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def item_analyze(

self, item)

Inheritance: ItemDetailView.item_analyze

def item_analyze(self, item):
    analyses = item.analysis.all()
    encoders_id = ['mp3_encoder']  # , 'vorbis_encoder']
    mime_type = ''
    if analyses:
        for analysis in analyses:
            if not item.approx_duration and analysis.analyzer_id == 'duration':
                value = analysis.value
                time = value.split(':')
                time[2] = time[2].split('.')[0]
                time = ':'.join(time)
                item.approx_duration = time
                item.save()
            if analysis.analyzer_id == 'mime_type':
                mime_type = analysis.value
    else:
        analyzers = []
        analyzers_sub = []
        graphers_sub = []
        encoders_sub = []
        source = item.get_source()[0]
        if source:
            decoder = timeside.core.get_processor('file_decoder')(source)
            pipe = decoder
            for analyzer in self.value_analyzers:
                subpipe = analyzer()
                analyzers_sub.append(subpipe)
                pipe = pipe | subpipe
            default_grapher = self.get_grapher(self.default_grapher_id)
            for size in self.default_grapher_sizes:
                width = size.split('x')[0]
                height = size.split('x')[1]
                image_file = '.'.join([item.public_id, self.default_grapher_id, size.replace('x', '_'), 'png'])
                path = self.cache_data.dir + os.sep + image_file
                graph = default_grapher(width=int(width), height=int(height))
                graphers_sub.append({'graph': graph, 'path': path})
                pipe |= graph
            for proc_id in encoders_id:
                encoder_cls = timeside.core.get_processor(proc_id)
                mime_type = encoder_cls.mime_type()
                cache_file = item.public_id + '.' + encoder_cls.file_extension()
                media = self.cache_export.dir + os.sep + cache_file
                encoder = encoder_cls(output=media, overwrite=True)
                encoders_sub.append(encoder)
                pipe |= encoder
            pipe.run()
            for grapher in graphers_sub:
                grapher['graph'].watermark('timeside', opacity=.6, margin=(5, 5))
                f = open(grapher['path'], 'w')
                grapher['graph'].render(grapher['path'])
                f.close()
            if os.path.exists(source):
                mime_type = mimetypes.guess_type(source)[0]
                analysis = MediaItemAnalysis(item=item, name='MIME type',
                                             analyzer_id='mime_type', unit='', value=mime_type)
                analysis.save()
                analysis = MediaItemAnalysis(item=item, name='Size',
                                             analyzer_id='size', unit='', value=item.size())
                analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Channels',
                                         analyzer_id='channels',
                                         unit='', value=decoder.input_channels)
            analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Samplerate',
                                         analyzer_id='samplerate', unit='Hz',
                                         value=unicode(decoder.input_samplerate))
            analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Resolution',
                                         analyzer_id='resolution', unit='bits',
                                         value=unicode(decoder.input_width))
            analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Duration',
                                         analyzer_id='duration', unit='s',
                                         value=unicode(datetime.timedelta(0, decoder.input_duration)))
            analysis.save()
            for analyzer in analyzers_sub:
                for key in analyzer.results.keys():
                    result = analyzer.results[key]
                    value = result.data_object.value
                    if value.shape[0] == 1:
                        value = value[0]
                    analysis = MediaItemAnalysis(item=item, name=result.name,
                                                 analyzer_id=result.id, unit=result.unit, value=unicode(value))
                    analysis.save()
            for encoder in encoders_sub:
                is_transcoded_flag = self.get_is_transcoded_flag(item=item, mime_type=mime_type)
                is_transcoded_flag.value = True
                is_transcoded_flag.save()
             FIXME: parse tags on first load
             tags = decoder.tags
    self.mime_type = mime_type

def item_previous_next(

self, item)

Inheritance: ItemDetailView.item_previous_next

Get previous and next items inside the collection of the item

def item_previous_next(self, item):
    """Get previous and next items inside the collection of the item"""
    pks = []
    items = MediaItem.objects.filter(collection=item.collection)
    items = items.order_by('code', 'old_code')
    if len(items) > 1:
        for it in items:
            pks.append(it.pk)
        for pk in pks:
            if pk == item.pk:
                if pk == pks[0]:
                    previous_pk = pks[-1]
                    next_pk = pks[1]
                elif pk == pks[-1]:
                    previous_pk = pks[-2]
                    next_pk = pks[0]
                else:
                    previous_pk = pks[pks.index(pk) - 1]
                    next_pk = pks[pks.index(pk) + 1]
                for it in items:
                    if it.pk == previous_pk:
                        previous = it
                    if it.pk == next_pk:
                        next = it
                previous = previous.public_id
                next = next.public_id
    else:
        previous = item.public_id
        next = item.public_id
    return previous, next

def options(

self, request, *args, **kwargs)

Inheritance: ItemDetailView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemDetailView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemPublishedEnumListView

class ItemPublishedEnumListView(ItemEnumListView):
    def get_queryset(self):
        c = ItemEnumListView()
        #id of value of enumeration
        i = self.request.path.split('/')[4]
        enumeration = c.get_enumeration(self.request.path.split('/')[3])
        queryset = self.get_item(enumeration.objects.filter(id=i).get(), c)
        return queryset

    def get_item(self, enum, c):
        return c.get_item(enum).filter(code__contains='_E_')

Ancestors (in MRO)

  • ItemPublishedEnumListView
  • ItemEnumListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemEnumListView.allow_empty

var content_type

Inheritance: ItemEnumListView.content_type

var context_object_name

Inheritance: ItemEnumListView.context_object_name

var http_method_names

Inheritance: ItemEnumListView.http_method_names

var model

Inheritance: ItemEnumListView.model

var page_kwarg

Inheritance: ItemEnumListView.page_kwarg

var paginate_by

Inheritance: ItemEnumListView.paginate_by

var paginate_orphans

Inheritance: ItemEnumListView.paginate_orphans

var paginator_class

Inheritance: ItemEnumListView.paginator_class

var queryset

Inheritance: ItemEnumListView.queryset

var response_class

Inheritance: ItemEnumListView.response_class

var template_name

Inheritance: ItemEnumListView.template_name

var template_name_suffix

Inheritance: ItemEnumListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemEnumListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemEnumListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemEnumListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemEnumListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemEnumListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemEnumListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemListView, self).get_context_data(**kwargs)
    context['enum'] = self.request.path.split('/')[3]
    context['id'] = self.request.path.split('/')[4]
    context['count'] = self.object_list.count()
    context['keyword'] = False
    context['enum_name'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name
    context['enum_value'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4])
    context['url_all'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item/list"
    context['url_unpublished'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item_unpublished/list/"
    context['url_published'] = "/admin/enumerations/" + context['enum'] +"/"+context['id'] + "/item_published/list/"
    context['url_sound'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item_sound/list/"
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemEnumListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_enumeration(

self, id)

Inheritance: ItemEnumListView.get_enumeration

def get_enumeration(self, id):
    from django.db.models import get_models
    models = get_models(telemeta.models)
    for model in models:
        if model._meta.module_name == id:
            break
    if model._meta.module_name != id:
        return None
    return model

def get_item(

self, enum, c)

Inheritance: ItemEnumListView.get_item

def get_item(self, enum, c):
    return c.get_item(enum).filter(code__contains='_E_')

def get_paginate_by(

self, queryset)

Inheritance: ItemEnumListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemEnumListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemEnumListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemEnumListView.get_queryset

def get_queryset(self):
    c = ItemEnumListView()
    #id of value of enumeration
    i = self.request.path.split('/')[4]
    enumeration = c.get_enumeration(self.request.path.split('/')[3])
    queryset = self.get_item(enumeration.objects.filter(id=i).get(), c)
    return queryset

def get_template_names(

self)

Inheritance: ItemEnumListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemEnumListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemEnumListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemEnumListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemEnumListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemPublishedListView

class ItemPublishedListView(ItemListView):

    queryset = MediaItem.objects.filter(collection__code__contains='_E_').order_by('code', 'old_code')

Ancestors (in MRO)

  • ItemPublishedListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemListView.allow_empty

var content_type

Inheritance: ItemListView.content_type

var context_object_name

Inheritance: ItemListView.context_object_name

var http_method_names

Inheritance: ItemListView.http_method_names

var model

Inheritance: ItemListView.model

var page_kwarg

Inheritance: ItemListView.page_kwarg

var paginate_by

Inheritance: ItemListView.paginate_by

var paginate_orphans

Inheritance: ItemListView.paginate_orphans

var paginator_class

Inheritance: ItemListView.paginator_class

var queryset

Inheritance: ItemListView.queryset

var response_class

Inheritance: ItemListView.response_class

var template_name

Inheritance: ItemListView.template_name

var template_name_suffix

Inheritance: ItemListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemListView, self).get_context_data(**kwargs)
    context['count'] = self.object_list.count()
    context['results_page'] = int(self.request.GET.get('results_page', 20))
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

Inheritance: ItemListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemListView.get_queryset

Get the list of items for this view. This must be an iterable, and may be a queryset (in which qs-specific behavior will be enabled).

def get_queryset(self):
    """
    Get the list of items for this view. This must be an iterable, and may
    be a queryset (in which qs-specific behavior will be enabled).
    """
    if self.queryset is not None:
        queryset = self.queryset
        if hasattr(queryset, '_clone'):
            queryset = queryset._clone()
    elif self.model is not None:
        queryset = self.model._default_manager.all()
    else:
        raise ImproperlyConfigured("'%s' must define 'queryset' or 'model'"
                                   % self.__class__.__name__)
    return queryset

def get_template_names(

self)

Inheritance: ItemListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemSoundEnumListView

class ItemSoundEnumListView(ItemEnumListView):
    def get_queryset(self):
        c = ItemEnumListView()
        #id of value of enumeration
        i= self.request.path.split('/')[4]
        enumeration = c.get_enumeration(self.request.path.split('/')[3])
        queryset = self.get_item(enumeration.objects.filter(id=i).get(), c)
        return queryset

    def get_item(self, enum, c):
        return c.get_item(enum).sound().order_by('code', 'old_code')

Ancestors (in MRO)

  • ItemSoundEnumListView
  • ItemEnumListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemEnumListView.allow_empty

var content_type

Inheritance: ItemEnumListView.content_type

var context_object_name

Inheritance: ItemEnumListView.context_object_name

var http_method_names

Inheritance: ItemEnumListView.http_method_names

var model

Inheritance: ItemEnumListView.model

var page_kwarg

Inheritance: ItemEnumListView.page_kwarg

var paginate_by

Inheritance: ItemEnumListView.paginate_by

var paginate_orphans

Inheritance: ItemEnumListView.paginate_orphans

var paginator_class

Inheritance: ItemEnumListView.paginator_class

var queryset

Inheritance: ItemEnumListView.queryset

var response_class

Inheritance: ItemEnumListView.response_class

var template_name

Inheritance: ItemEnumListView.template_name

var template_name_suffix

Inheritance: ItemEnumListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemEnumListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemEnumListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemEnumListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemEnumListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemEnumListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemEnumListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemListView, self).get_context_data(**kwargs)
    context['enum'] = self.request.path.split('/')[3]
    context['id'] = self.request.path.split('/')[4]
    context['count'] = self.object_list.count()
    context['keyword'] = False
    context['enum_name'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name
    context['enum_value'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4])
    context['url_all'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item/list"
    context['url_unpublished'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item_unpublished/list/"
    context['url_published'] = "/admin/enumerations/" + context['enum'] +"/"+context['id'] + "/item_published/list/"
    context['url_sound'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item_sound/list/"
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemEnumListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_enumeration(

self, id)

Inheritance: ItemEnumListView.get_enumeration

def get_enumeration(self, id):
    from django.db.models import get_models
    models = get_models(telemeta.models)
    for model in models:
        if model._meta.module_name == id:
            break
    if model._meta.module_name != id:
        return None
    return model

def get_item(

self, enum, c)

Inheritance: ItemEnumListView.get_item

def get_item(self, enum, c):
    return c.get_item(enum).sound().order_by('code', 'old_code')

def get_paginate_by(

self, queryset)

Inheritance: ItemEnumListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemEnumListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemEnumListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemEnumListView.get_queryset

def get_queryset(self):
    c = ItemEnumListView()
    #id of value of enumeration
    i= self.request.path.split('/')[4]
    enumeration = c.get_enumeration(self.request.path.split('/')[3])
    queryset = self.get_item(enumeration.objects.filter(id=i).get(), c)
    return queryset

def get_template_names(

self)

Inheritance: ItemEnumListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemEnumListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemEnumListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemEnumListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemEnumListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemSoundListView

class ItemSoundListView(ItemListView):

    queryset = MediaItem.objects.sound().order_by('code', 'old_code')

Ancestors (in MRO)

  • ItemSoundListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemListView.allow_empty

var content_type

Inheritance: ItemListView.content_type

var context_object_name

Inheritance: ItemListView.context_object_name

var http_method_names

Inheritance: ItemListView.http_method_names

var model

Inheritance: ItemListView.model

var page_kwarg

Inheritance: ItemListView.page_kwarg

var paginate_by

Inheritance: ItemListView.paginate_by

var paginate_orphans

Inheritance: ItemListView.paginate_orphans

var paginator_class

Inheritance: ItemListView.paginator_class

var queryset

Inheritance: ItemListView.queryset

var response_class

Inheritance: ItemListView.response_class

var template_name

Inheritance: ItemListView.template_name

var template_name_suffix

Inheritance: ItemListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemListView, self).get_context_data(**kwargs)
    context['count'] = self.object_list.count()
    context['results_page'] = int(self.request.GET.get('results_page', 20))
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

Inheritance: ItemListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemListView.get_queryset

Get the list of items for this view. This must be an iterable, and may be a queryset (in which qs-specific behavior will be enabled).

def get_queryset(self):
    """
    Get the list of items for this view. This must be an iterable, and may
    be a queryset (in which qs-specific behavior will be enabled).
    """
    if self.queryset is not None:
        queryset = self.queryset
        if hasattr(queryset, '_clone'):
            queryset = queryset._clone()
    elif self.model is not None:
        queryset = self.model._default_manager.all()
    else:
        raise ImproperlyConfigured("'%s' must define 'queryset' or 'model'"
                                   % self.__class__.__name__)
    return queryset

def get_template_names(

self)

Inheritance: ItemListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemUnpublishedEnumListView

class ItemUnpublishedEnumListView(ItemEnumListView):
    def get_queryset(self):
        c = ItemEnumListView()
        #id of value of enumeration
        i= self.request.path.split('/')[4]
        enumeration = c.get_enumeration(self.request.path.split('/')[3])
        queryset = self.get_item(enumeration.objects.filter(id=i).get(), c)
        return queryset

    def get_item(self, enum, c):
        return c.get_item(enum).filter(code__contains='_I_')

Ancestors (in MRO)

  • ItemUnpublishedEnumListView
  • ItemEnumListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemEnumListView.allow_empty

var content_type

Inheritance: ItemEnumListView.content_type

var context_object_name

Inheritance: ItemEnumListView.context_object_name

var http_method_names

Inheritance: ItemEnumListView.http_method_names

var model

Inheritance: ItemEnumListView.model

var page_kwarg

Inheritance: ItemEnumListView.page_kwarg

var paginate_by

Inheritance: ItemEnumListView.paginate_by

var paginate_orphans

Inheritance: ItemEnumListView.paginate_orphans

var paginator_class

Inheritance: ItemEnumListView.paginator_class

var queryset

Inheritance: ItemEnumListView.queryset

var response_class

Inheritance: ItemEnumListView.response_class

var template_name

Inheritance: ItemEnumListView.template_name

var template_name_suffix

Inheritance: ItemEnumListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemEnumListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemEnumListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemEnumListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemEnumListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemEnumListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemEnumListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemListView, self).get_context_data(**kwargs)
    context['enum'] = self.request.path.split('/')[3]
    context['id'] = self.request.path.split('/')[4]
    context['count'] = self.object_list.count()
    context['keyword'] = False
    context['enum_name'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name
    context['enum_value'] = ItemEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4])
    context['url_all'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item/list"
    context['url_unpublished'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item_unpublished/list/"
    context['url_published'] = "/admin/enumerations/" + context['enum'] +"/"+context['id'] + "/item_published/list/"
    context['url_sound'] = "/admin/enumerations/" + context['enum'] + "/" + context['id'] + "/item_sound/list/"
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemEnumListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_enumeration(

self, id)

Inheritance: ItemEnumListView.get_enumeration

def get_enumeration(self, id):
    from django.db.models import get_models
    models = get_models(telemeta.models)
    for model in models:
        if model._meta.module_name == id:
            break
    if model._meta.module_name != id:
        return None
    return model

def get_item(

self, enum, c)

Inheritance: ItemEnumListView.get_item

def get_item(self, enum, c):
    return c.get_item(enum).filter(code__contains='_I_')

def get_paginate_by(

self, queryset)

Inheritance: ItemEnumListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemEnumListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemEnumListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemEnumListView.get_queryset

def get_queryset(self):
    c = ItemEnumListView()
    #id of value of enumeration
    i= self.request.path.split('/')[4]
    enumeration = c.get_enumeration(self.request.path.split('/')[3])
    queryset = self.get_item(enumeration.objects.filter(id=i).get(), c)
    return queryset

def get_template_names(

self)

Inheritance: ItemEnumListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemEnumListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemEnumListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemEnumListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemEnumListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemUnpublishedListView

class ItemUnpublishedListView(ItemListView):

    queryset = MediaItem.objects.filter(collection__code__contains='_I_').order_by('code', 'old_code')

Ancestors (in MRO)

  • ItemUnpublishedListView
  • ItemListView
  • django.views.generic.list.ListView
  • django.views.generic.list.MultipleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.list.BaseListView
  • django.views.generic.list.MultipleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var allow_empty

Inheritance: ItemListView.allow_empty

var content_type

Inheritance: ItemListView.content_type

var context_object_name

Inheritance: ItemListView.context_object_name

var http_method_names

Inheritance: ItemListView.http_method_names

var model

Inheritance: ItemListView.model

var page_kwarg

Inheritance: ItemListView.page_kwarg

var paginate_by

Inheritance: ItemListView.paginate_by

var paginate_orphans

Inheritance: ItemListView.paginate_orphans

var paginator_class

Inheritance: ItemListView.paginator_class

var queryset

Inheritance: ItemListView.queryset

var response_class

Inheritance: ItemListView.response_class

var template_name

Inheritance: ItemListView.template_name

var template_name_suffix

Inheritance: ItemListView.template_name_suffix

Methods

def __init__(

self, **kwargs)

Inheritance: ItemListView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemListView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemListView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemListView.get

def get(self, request, *args, **kwargs):
    self.object_list = self.get_queryset()
    allow_empty = self.get_allow_empty()
    if not allow_empty:
        # When pagination is enabled and object_list is a queryset,
        # it's better to do a cheap query than to load the unpaginated
        # queryset in memory.
        if (self.get_paginate_by(self.object_list) is not None
            and hasattr(self.object_list, 'exists')):
            is_empty = not self.object_list.exists()
        else:
            is_empty = len(self.object_list) == 0
        if is_empty:
            raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.")
                    % {'class_name': self.__class__.__name__})
    context = self.get_context_data()
    return self.render_to_response(context)

def get_allow_empty(

self)

Inheritance: ItemListView.get_allow_empty

Returns True if the view should display empty lists, and False if a 404 should be raised instead.

def get_allow_empty(self):
    """
    Returns ``True`` if the view should display empty lists, and ``False``
    if a 404 should be raised instead.
    """
    return self.allow_empty

def get_context_data(

self, **kwargs)

Inheritance: ItemListView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemListView, self).get_context_data(**kwargs)
    context['count'] = self.object_list.count()
    context['results_page'] = int(self.request.GET.get('results_page', 20))
    return context

def get_context_object_name(

self, object_list)

Inheritance: ItemListView.get_context_object_name

Get the name of the item to be used in the context.

def get_context_object_name(self, object_list):
    """
    Get the name of the item to be used in the context.
    """
    if self.context_object_name:
        return self.context_object_name
    elif hasattr(object_list, 'model'):
        return '%s_list' % object_list.model._meta.model_name
    else:
        return None

def get_paginate_by(

self, queryset)

Inheritance: ItemListView.get_paginate_by

def get_paginate_by(self, queryset):
    return self.request.GET.get('results_page', 20)

def get_paginate_orphans(

self)

Inheritance: ItemListView.get_paginate_orphans

Returns the maximum number of orphans extend the last page by when paginating.

def get_paginate_orphans(self):
    """
    Returns the maximum number of orphans extend the last page by when
    paginating.
    """
    return self.paginate_orphans

def get_paginator(

self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs)

Inheritance: ItemListView.get_paginator

Return an instance of the paginator for this view.

def get_paginator(self, queryset, per_page, orphans=0,
                  allow_empty_first_page=True, **kwargs):
    """
    Return an instance of the paginator for this view.
    """
    return self.paginator_class(
        queryset, per_page, orphans=orphans,
        allow_empty_first_page=allow_empty_first_page, **kwargs)

def get_queryset(

self)

Inheritance: ItemListView.get_queryset

Get the list of items for this view. This must be an iterable, and may be a queryset (in which qs-specific behavior will be enabled).

def get_queryset(self):
    """
    Get the list of items for this view. This must be an iterable, and may
    be a queryset (in which qs-specific behavior will be enabled).
    """
    if self.queryset is not None:
        queryset = self.queryset
        if hasattr(queryset, '_clone'):
            queryset = queryset._clone()
    elif self.model is not None:
        queryset = self.model._default_manager.all()
    else:
        raise ImproperlyConfigured("'%s' must define 'queryset' or 'model'"
                                   % self.__class__.__name__)
    return queryset

def get_template_names(

self)

Inheritance: ItemListView.get_template_names

Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden.

def get_template_names(self):
    """
    Return a list of template names to be used for the request. Must return
    a list. May not be called if render_to_response is overridden.
    """
    try:
        names = super(MultipleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
    # If the list is a queryset, we'll invent a template name based on the
    # app and model name. This name gets put at the end of the template
    # name list so that user-supplied names override the automatically-
    # generated ones.
    if hasattr(self.object_list, 'model'):
        opts = self.object_list.model._meta
        names.append("%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix))
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemListView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def options(

self, request, *args, **kwargs)

Inheritance: ItemListView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def paginate_queryset(

self, queryset, page_size)

Inheritance: ItemListView.paginate_queryset

Paginate the queryset, if needed.

def paginate_queryset(self, queryset, page_size):
    """
    Paginate the queryset, if needed.
    """
    paginator = self.get_paginator(
        queryset, page_size, orphans=self.get_paginate_orphans(),
        allow_empty_first_page=self.get_allow_empty())
    page_kwarg = self.page_kwarg
    page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise Http404(_("Page is not 'last', nor can it be converted to an int."))
    try:
        page = paginator.page(page_number)
        return (paginator, page, page.object_list, page.has_other_pages())
    except InvalidPage as e:
        raise Http404(_('Invalid page (%(page_number)s): %(message)s') % {
                            'page_number': page_number,
                            'message': str(e)
        })

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemListView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemVideoPlayerView

class ItemVideoPlayerView(ItemDetailView):

    template_name = 'telemeta/mediaitem_video_player.html'

Ancestors (in MRO)

  • ItemVideoPlayerView
  • ItemDetailView
  • ItemViewMixin
  • ItemBaseMixin
  • telemeta.views.core.TelemetaBaseMixin
  • django.views.generic.detail.DetailView
  • django.views.generic.detail.SingleObjectTemplateResponseMixin
  • django.views.generic.base.TemplateResponseMixin
  • django.views.generic.detail.BaseDetailView
  • django.views.generic.detail.SingleObjectMixin
  • django.views.generic.base.ContextMixin
  • django.views.generic.base.View
  • __builtin__.object

Class variables

var CACHE_DIR

Inheritance: ItemDetailView.CACHE_DIR

var MEDIA_ROOT

Inheritance: ItemDetailView.MEDIA_ROOT

var analyzers

Inheritance: ItemDetailView.analyzers

var auto_zoom

Inheritance: ItemDetailView.auto_zoom

var cache_data

Inheritance: ItemDetailView.cache_data

var cache_export

Inheritance: ItemDetailView.cache_export

var cache_tmp

Inheritance: ItemDetailView.cache_tmp

var content_type

Inheritance: ItemDetailView.content_type

var context_object_name

Inheritance: ItemDetailView.context_object_name

var decoders

Inheritance: ItemDetailView.decoders

var default_grapher_id

Inheritance: ItemDetailView.default_grapher_id

var default_grapher_sizes

Inheritance: ItemDetailView.default_grapher_sizes

var encoders

Inheritance: ItemDetailView.encoders

var export_enabled

Inheritance: ItemDetailView.export_enabled

var export_formats

Inheritance: ItemDetailView.export_formats

var form_class

Inheritance: ItemDetailView.form_class

var graphers

Inheritance: ItemDetailView.graphers

var http_method_names

Inheritance: ItemDetailView.http_method_names

var inlines

Inheritance: ItemDetailView.inlines

var model

Inheritance: ItemDetailView.model

var pk_url_kwarg

Inheritance: ItemDetailView.pk_url_kwarg

var public_graphers

Inheritance: ItemDetailView.public_graphers

var queryset

Inheritance: ItemDetailView.queryset

var response_class

Inheritance: ItemDetailView.response_class

var slug_field

Inheritance: ItemDetailView.slug_field

var slug_url_kwarg

Inheritance: ItemDetailView.slug_url_kwarg

var template_name

Inheritance: ItemDetailView.template_name

var template_name_field

Inheritance: ItemDetailView.template_name_field

var template_name_suffix

Inheritance: ItemDetailView.template_name_suffix

var value_analyzers

Inheritance: ItemDetailView.value_analyzers

Methods

def __init__(

self, **kwargs)

Inheritance: ItemDetailView.__init__

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

def __init__(self, **kwargs):
    """
    Constructor. Called in the URLconf; can contain helpful extra
    keyword arguments, and other things.
    """
    # Go through keyword arguments, and either save their values to our
    # instance, or raise an error.
    for key, value in six.iteritems(kwargs):
        setattr(self, key, value)

def as_view(

cls, **initkwargs)

Inheritance: ItemDetailView.as_view

Main entry point for a request-response process.

@classonlymethod
def as_view(cls, **initkwargs):
    """
    Main entry point for a request-response process.
    """
    # sanitize keyword arguments
    for key in initkwargs:
        if key in cls.http_method_names:
            raise TypeError("You tried to pass in the %s method name as a "
                            "keyword argument to %s(). Don't do that."
                            % (key, cls.__name__))
        if not hasattr(cls, key):
            raise TypeError("%s() received an invalid keyword %r. as_view "
                            "only accepts arguments that are already "
                            "attributes of the class." % (cls.__name__, key))
    def view(request, *args, **kwargs):
        self = cls(**initkwargs)
        if hasattr(self, 'get') and not hasattr(self, 'head'):
            self.head = self.get
        self.request = request
        self.args = args
        self.kwargs = kwargs
        return self.dispatch(request, *args, **kwargs)
    # take name and docstring from class
    update_wrapper(view, cls, updated=())
    # and possible attributes set by decorators
    # like csrf_exempt from dispatch
    update_wrapper(view, cls.dispatch, assigned=())
    return view

def dispatch(

self, request, *args, **kwargs)

Inheritance: ItemDetailView.dispatch

def dispatch(self, request, *args, **kwargs):
    # Try to dispatch to the right method; if a method doesn't exist,
    # defer to the error handler. Also defer to the error handler if the
    # request method isn't on the approved list.
    if request.method.lower() in self.http_method_names:
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)

def get(

self, request, *args, **kwargs)

Inheritance: ItemDetailView.get

def get(self, request, *args, **kwargs):
    self.object = self.get_object()
    context = self.get_context_data(object=self.object)
    return self.render_to_response(context)

def get_context_data(

self, **kwargs)

Inheritance: ItemDetailView.get_context_data

def get_context_data(self, **kwargs):
    context = super(ItemDetailView, self).get_context_data(**kwargs)
    public_id = get_kwargs_or_none('public_id', self.kwargs)
    marker_id = get_kwargs_or_none('marker_id', self.kwargs)
    width = get_kwargs_or_none('width', self.kwargs)
    height = get_kwargs_or_none('height', self.kwargs)
    # get item with one of its given marker_id
    if not public_id and marker_id:
        marker = MediaItemMarker.objects.get(public_id=marker_id)
        item_id = marker.item_id
        item = MediaItem.objects.get(id=item_id)
    else:
        item = self.get_object()
    access = get_item_access(item, self.request.user)
    previous, next = self.item_previous_next(item)
    # Corresponding TimeSide Item
    source, source_type = item.get_source()
    # if source:
    #     ts_item, c = ts.models.Item.objects.get_or_create(**{source_type: source})
    #     if c:
    #         ts_item.title = item.title
    #         ts_item.save()
    self.item_analyze(item)
    # FIXME: use mimetypes.guess_type
    if 'quicktime' in self.mime_type:
        self.mime_type = 'video/mp4'
    playlists = get_playlists_names(self.request)
    rang = []
    for i in range(len(playlists)):
        for resource in playlists[i]['playlist'].resources.all():
            if int(resource.resource_id) == item.id:
                rang.append(i)
                break
    related_media = MediaItemRelated.objects.filter(item=item)
    check_related_media(related_media)
    revisions = Revision.objects.filter(element_type='item', element_id=item.id).order_by('-time')
    if revisions:
        last_revision = revisions[0]
    else:
        last_revision = None
    item_format = ''
    if Format.objects.filter(item=item):
        item_format = item.format.get()
    context['item'] = item
    context['export_formats'] = self.get_export_formats()
    context['visualizers'] = self.get_graphers()
    context['auto_zoom'] = self.auto_zoom
    context['audio_export_enabled'] = self.export_enabled
    context['previous'] = previous
    context['next'] = next
    context['marker'] = marker_id
    context['playlists'] = playlists
    context['access'] = access
    context['width'] = width
    context['height'] = height
    context['related_media'] = related_media
    context['mime_type'] = self.mime_type
    context['last_revision'] = last_revision
    context['format'] = item_format
    context['private_extra_types'] = private_extra_types.values()
    context['site'] = 'http://' + Site.objects.all()[0].name
    context['rang_item_playlist'] = rang
    # if ts_item:
    #     context['ts_item_id'] = ts_item.pk
    # else:
    #     context['ts_item_id'] = None
    return context

def get_context_object_name(

self, obj)

Inheritance: ItemDetailView.get_context_object_name

Get the name to use for the object.

def get_context_object_name(self, obj):
    """
    Get the name to use for the object.
    """
    if self.context_object_name:
        return self.context_object_name
    elif isinstance(obj, models.Model):
        return obj._meta.model_name
    else:
        return None

def get_export_formats(

self)

Inheritance: ItemDetailView.get_export_formats

def get_export_formats(self):
    formats = []
    for encoder in self.encoders:
        if encoder.file_extension() in self.export_formats:
            formats.append({'name': encoder.format(),
                            'extension': encoder.file_extension()})
    return formats

def get_grapher(

self, id)

Inheritance: ItemDetailView.get_grapher

def get_grapher(self, id):
    for grapher in self.graphers:
        if grapher.id() == id:
            break
    return grapher

def get_graphers(

self)

Inheritance: ItemDetailView.get_graphers

def get_graphers(self):
    graphers = []
    user = self.request.user
    graphers_access = (user.is_staff
                       or user.is_superuser
                       or user.has_perm('can_run_analysis'))
    for grapher in self.graphers:
        if (not graphers_access
            and grapher.id() not in self.public_graphers):
            continue
        if grapher.id() == self.default_grapher_id:
            graphers.insert(0, {'name': grapher.name(), 'id': grapher.id()})
        elif not hasattr(grapher, '_staging'):
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
        elif not grapher._staging:
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
    return graphers

def get_is_transcoded_flag(

self, item, mime_type)

Inheritance: ItemDetailView.get_is_transcoded_flag

def get_is_transcoded_flag(self, item, mime_type):
    try:
        is_transcoded_flag, c = MediaItemTranscodingFlag.objects.get_or_create(
            item=item,
            mime_type=mime_type,
            defaults={'value': False})
    except MediaItemTranscodingFlag.MultipleObjectsReturned:
        flags = MediaItemTranscodingFlag.objects.filter(
            item=item,
            mime_type=mime_type)
        value = all([f.value for f in flags])
        is_transcoded_flag = flags[0]
        is_transcoded_flag.value = value
        is_transcoded_flag.save()
        for f in flags[1:]:
            f.delete()
    return is_transcoded_flag

def get_item_file_url(

*a, **kw)

Inheritance: ItemDetailView.get_item_file_url

@jsonrpc_method('telemeta.get_item_export_url')
def get_item_file_url(request, public_id, extension):
    return reverse('telemeta-item-export', kwargs={'public_id': public_id, 'extension': extension})

def get_object(

self)

Inheritance: ItemDetailView.get_object

def get_object(self):
    obj = self.model.objects.filter(code=self.kwargs['public_id'])
    if not obj:
        if self.kwargs['public_id'].isdigit():
            try:
                obj = self.model.objects.get(id=self.kwargs['public_id'])
            except self.model.DoesNotExist:
                raise Http404
        else:
            raise Http404
    else:
        obj = obj[0]
    return obj

def get_queryset(

self)

Inheritance: ItemDetailView.get_queryset

Get the queryset to look an object up against. May not be called if get_object is overridden.

def get_queryset(self):
    """
    Get the queryset to look an object up against. May not be called if
    `get_object` is overridden.
    """
    if self.queryset is None:
        if self.model:
            return self.model._default_manager.all()
        else:
            raise ImproperlyConfigured("%(cls)s is missing a queryset. Define "
                                       "%(cls)s.model, %(cls)s.queryset, or override "
                                       "%(cls)s.get_queryset()." % {
                                            'cls': self.__class__.__name__
                                    })
    return self.queryset._clone()

def get_slug_field(

self)

Inheritance: ItemDetailView.get_slug_field

Get the name of a slug field to be used to look up by slug.

def get_slug_field(self):
    """
    Get the name of a slug field to be used to look up by slug.
    """
    return self.slug_field

def get_template_names(

self)

Inheritance: ItemDetailView.get_template_names

Return a list of template names to be used for the request. May not be called if render_to_response is overridden. Returns the following list:

  • the value of template_name on the view (if provided)
  • the contents of the template_name_field field on the object instance that the view is operating upon (if available)
  • <app_label>/<model_name><template_name_suffix>.html
def get_template_names(self):
    """
    Return a list of template names to be used for the request. May not be
    called if render_to_response is overridden. Returns the following list:
    * the value of ``template_name`` on the view (if provided)
    * the contents of the ``template_name_field`` field on the
      object instance that the view is operating upon (if available)
    * ``<app_label>/<model_name><template_name_suffix>.html``
    """
    try:
        names = super(SingleObjectTemplateResponseMixin, self).get_template_names()
    except ImproperlyConfigured:
        # If template_name isn't specified, it's not a problem --
        # we just start with an empty list.
        names = []
        # If self.template_name_field is set, grab the value of the field
        # of that name from the object; this is the most specific template
        # name, if given.
        if self.object and self.template_name_field:
            name = getattr(self.object, self.template_name_field, None)
            if name:
                names.insert(0, name)
        # The least-specific option is the default <app>/<model>_detail.html;
        # only use this if the object in question is a model.
        if isinstance(self.object, models.Model):
            names.append("%s/%s%s.html" % (
                self.object._meta.app_label,
                self.object._meta.model_name,
                self.template_name_suffix
            ))
        elif hasattr(self, 'model') and self.model is not None and issubclass(self.model, models.Model):
            names.append("%s/%s%s.html" % (
                self.model._meta.app_label,
                self.model._meta.model_name,
                self.template_name_suffix
            ))
        # If we still haven't managed to find any template names, we should
        # re-raise the ImproperlyConfigured to alert the user.
        if not names:
            raise
    return names

def http_method_not_allowed(

self, request, *args, **kwargs)

Inheritance: ItemDetailView.http_method_not_allowed

def http_method_not_allowed(self, request, *args, **kwargs):
    logger.warning('Method Not Allowed (%s): %s', request.method, request.path,
        extra={
            'status_code': 405,
            'request': self.request
        }
    )
    return http.HttpResponseNotAllowed(self._allowed_methods())

def item_analyze(

self, item)

Inheritance: ItemDetailView.item_analyze

def item_analyze(self, item):
    analyses = item.analysis.all()
    encoders_id = ['mp3_encoder']  # , 'vorbis_encoder']
    mime_type = ''
    if analyses:
        for analysis in analyses:
            if not item.approx_duration and analysis.analyzer_id == 'duration':
                value = analysis.value
                time = value.split(':')
                time[2] = time[2].split('.')[0]
                time = ':'.join(time)
                item.approx_duration = time
                item.save()
            if analysis.analyzer_id == 'mime_type':
                mime_type = analysis.value
    else:
        analyzers = []
        analyzers_sub = []
        graphers_sub = []
        encoders_sub = []
        source = item.get_source()[0]
        if source:
            decoder = timeside.core.get_processor('file_decoder')(source)
            pipe = decoder
            for analyzer in self.value_analyzers:
                subpipe = analyzer()
                analyzers_sub.append(subpipe)
                pipe = pipe | subpipe
            default_grapher = self.get_grapher(self.default_grapher_id)
            for size in self.default_grapher_sizes:
                width = size.split('x')[0]
                height = size.split('x')[1]
                image_file = '.'.join([item.public_id, self.default_grapher_id, size.replace('x', '_'), 'png'])
                path = self.cache_data.dir + os.sep + image_file
                graph = default_grapher(width=int(width), height=int(height))
                graphers_sub.append({'graph': graph, 'path': path})
                pipe |= graph
            for proc_id in encoders_id:
                encoder_cls = timeside.core.get_processor(proc_id)
                mime_type = encoder_cls.mime_type()
                cache_file = item.public_id + '.' + encoder_cls.file_extension()
                media = self.cache_export.dir + os.sep + cache_file
                encoder = encoder_cls(output=media, overwrite=True)
                encoders_sub.append(encoder)
                pipe |= encoder
            pipe.run()
            for grapher in graphers_sub:
                grapher['graph'].watermark('timeside', opacity=.6, margin=(5, 5))
                f = open(grapher['path'], 'w')
                grapher['graph'].render(grapher['path'])
                f.close()
            if os.path.exists(source):
                mime_type = mimetypes.guess_type(source)[0]
                analysis = MediaItemAnalysis(item=item, name='MIME type',
                                             analyzer_id='mime_type', unit='', value=mime_type)
                analysis.save()
                analysis = MediaItemAnalysis(item=item, name='Size',
                                             analyzer_id='size', unit='', value=item.size())
                analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Channels',
                                         analyzer_id='channels',
                                         unit='', value=decoder.input_channels)
            analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Samplerate',
                                         analyzer_id='samplerate', unit='Hz',
                                         value=unicode(decoder.input_samplerate))
            analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Resolution',
                                         analyzer_id='resolution', unit='bits',
                                         value=unicode(decoder.input_width))
            analysis.save()
            analysis = MediaItemAnalysis(item=item, name='Duration',
                                         analyzer_id='duration', unit='s',
                                         value=unicode(datetime.timedelta(0, decoder.input_duration)))
            analysis.save()
            for analyzer in analyzers_sub:
                for key in analyzer.results.keys():
                    result = analyzer.results[key]
                    value = result.data_object.value
                    if value.shape[0] == 1:
                        value = value[0]
                    analysis = MediaItemAnalysis(item=item, name=result.name,
                                                 analyzer_id=result.id, unit=result.unit, value=unicode(value))
                    analysis.save()
            for encoder in encoders_sub:
                is_transcoded_flag = self.get_is_transcoded_flag(item=item, mime_type=mime_type)
                is_transcoded_flag.value = True
                is_transcoded_flag.save()
             FIXME: parse tags on first load
             tags = decoder.tags
    self.mime_type = mime_type

def item_previous_next(

self, item)

Inheritance: ItemDetailView.item_previous_next

Get previous and next items inside the collection of the item

def item_previous_next(self, item):
    """Get previous and next items inside the collection of the item"""
    pks = []
    items = MediaItem.objects.filter(collection=item.collection)
    items = items.order_by('code', 'old_code')
    if len(items) > 1:
        for it in items:
            pks.append(it.pk)
        for pk in pks:
            if pk == item.pk:
                if pk == pks[0]:
                    previous_pk = pks[-1]
                    next_pk = pks[1]
                elif pk == pks[-1]:
                    previous_pk = pks[-2]
                    next_pk = pks[0]
                else:
                    previous_pk = pks[pks.index(pk) - 1]
                    next_pk = pks[pks.index(pk) + 1]
                for it in items:
                    if it.pk == previous_pk:
                        previous = it
                    if it.pk == next_pk:
                        next = it
                previous = previous.public_id
                next = next.public_id
    else:
        previous = item.public_id
        next = item.public_id
    return previous, next

def options(

self, request, *args, **kwargs)

Inheritance: ItemDetailView.options

Handles responding to requests for the OPTIONS HTTP verb.

def options(self, request, *args, **kwargs):
    """
    Handles responding to requests for the OPTIONS HTTP verb.
    """
    response = http.HttpResponse()
    response['Allow'] = ', '.join(self._allowed_methods())
    response['Content-Length'] = '0'
    return response

def render_to_response(

self, context, **response_kwargs)

Inheritance: ItemDetailView.render_to_response

Returns a response, using the response_class for this view, with a template rendered with the given context.

If any keyword arguments are provided, they will be passed to the constructor of the response class.

def render_to_response(self, context, **response_kwargs):
    """
    Returns a response, using the `response_class` for this
    view, with a template rendered with the given context.
    If any keyword arguments are provided, they will be
    passed to the constructor of the response class.
    """
    response_kwargs.setdefault('content_type', self.content_type)
    return self.response_class(
        request = self.request,
        template = self.get_template_names(),
        context = context,
        **response_kwargs
    )

class ItemView

Provide Item web UI methods

class ItemView(ItemBaseMixin):
    """Provide Item web UI methods"""

    def item_detail(self, request, public_id=None, marker_id=None, width=None, height=None,
                    template='telemeta/mediaitem_detail.html'):
        """Show the details of a given item"""

        # get item with one of its given marker_id
        if not public_id and marker_id:
            marker = get_object_or_404(MediaItemMarker, public_id=marker_id)
            item_id = marker.item_id
            item = MediaItem.objects.get(id=item_id)
        else:
            item = get_object_or_404(MediaItem, public_id=public_id)

        access = get_item_access(item, request.user)

        if access == 'none':
            mess = ugettext('Access not allowed')
            title = ugettext('Item') + ' : ' + public_id + ' : ' + mess
            description = ugettext('Please login or contact the website administator to get a private access.')
            messages.error(request, title)
            return render(request, 'telemeta/messages.html', {'description': description})

        previous, next = self.item_previous_next(item)

        mime_type = item.mime_type
        if mime_type and mime_type != 'none':
            if 'quicktime' in mime_type:
                mime_type = 'video/mp4'

        playlists = get_playlists_names(request)
        related_media = MediaItemRelated.objects.filter(item=item)
        check_related_media(related_media)
        revisions = Revision.objects.filter(element_type='item', element_id=item.id).order_by('-time')
        if revisions:
            last_revision = revisions[0]
        else:
            last_revision = None

        format = ''
        if Format.objects.filter(item=item):
            format = item.format.get()

        return render(request, template,
                      {'item': item, 'export_formats': self.get_export_formats(),
                       'visualizers': self.get_graphers(), 'auto_zoom': self.auto_zoom,
                       'audio_export_enabled': self.export_enabled,
                       'previous': previous, 'next': next, 'marker': marker_id, 'playlists': playlists,
                       'access': access, 'width': width, 'height': height,
                       'related_media': related_media, 'mime_type': mime_type, 'last_revision': last_revision,
                       'format': format,
                       })

    def related_media_item_stream(self, request, item_public_id, media_id):
        item = get_object_or_404(MediaItem, code=item_public_id)
        media = get_object_or_404(MediaItemRelated, item=item, id=media_id)
        if media.file:
            response = serve_media(media.file.path, content_type=media.mime_type)
        else:
            raise Http404
        return response

    def related_media_item_download(self, request, item_public_id, media_id):
        item = get_object_or_404(MediaItem, code=item_public_id)
        media = get_object_or_404(MediaItemRelated, item=item, id=media_id)
        if media.file:
            response = serve_media(media.file.path, content_type=media.mime_type)
        else:
            raise Http404
        return response

    @method_decorator(permission_required('telemeta.change_mediaitem'))
    def related_media_edit(self, request, public_id, template):
        item = get_object_or_404(MediaItem, code=public_id)
        MediaItemRelatedFormSet = inlineformset_factory(MediaItem, MediaItemRelated, form=MediaItemRelatedForm)
        if request.method == 'POST':
            formset = MediaItemRelatedFormSet(data=request.POST, files=request.FILES, instance=item)
            if formset.is_valid():
                formset.save()
                item.set_revision(request.user)
                return redirect('telemeta-item-edit', public_id)
        else:
            formset = MediaItemRelatedFormSet(instance=item)
        return render(request, template, {'item': item, 'formset': formset, })

    @method_decorator(permission_required('telemeta.delete_mediaitem'))
    def item_delete(self, request, public_id):
        """Delete a given item"""
        item = MediaItem.objects.get(public_id=public_id)
        revisions = Revision.objects.filter(element_type='item', element_id=item.id)
        for revision in revisions:
            revision.delete()
        collection = item.collection
        item.delete()
        return redirect('telemeta-collection-detail', collection.code)

    def item_analyze_xml(self, request, public_id):
        item = MediaItem.objects.get(public_id=public_id)
        analyses = item.analysis.all()
        analyzers = []
        for analysis in analyses:
            analyzers.append(analysis.to_dict())
        mime_type = 'text/xml'
        response = HttpResponse(self.cache_data.get_analyzer_xml(analyzers), content_type=mime_type)
        response['Content-Disposition'] = 'attachment; filename=' + public_id + '.xml'
        return response

    def item_visualize(self, request, public_id, grapher_id, width, height):
        try:
            width = int(width)
            height = int(height)
        except:
            pass

        if not isinstance(width, int) or not isinstance(height, int):
            size = self.default_grapher_sizes[0]
            width = int(size.split('x')[0])
            height = int(size.split('x')[1])

        item = MediaItem.objects.get(public_id=public_id)
        mime_type = 'image/png'

        source, source_type = item.get_source()
        # if source:
        #     ts_item, c = ts.models.Item.objects.get_or_create(**{source_type: source})
        #     if c:
        #         ts_item.title = item.title
        #         ts_item.save()
        #
        # ts_grapher, c = ts.models.Processor.objects.get_or_create(pid=grapher_id)
        # ts_preset, c = ts.models.Preset.objects.get_or_create(processor=ts_grapher,
        #                                                       parameters={'width': width, 'height': height})
        # ts_experience = ts_preset.get_single_experience()
        # ts_selection = ts_item.get_single_selection()
        # ts_task, c = ts.models.Task.objects.get_or_create(experience=ts_experience,
        #                                            selection=ts_selection)
        # ts_task.run()

        grapher = self.get_grapher(grapher_id)

        if grapher.id() != grapher_id:
            raise Http404

        size = str(width) + '_' + str(height)
        image_file = '.'.join([public_id, grapher_id, size, 'png'])

        # FIX waveform grapher name change
        old_image_file = '.'.join([public_id, 'waveform', size, 'png'])
        if 'waveform_centroid' in grapher_id and self.cache_data.exists(old_image_file):
            image_file = old_image_file

        if not self.cache_data.exists(image_file):
            source, _ = item.get_source()
            if source:
                path = self.cache_data.dir + os.sep + image_file
                decoder = timeside.core.get_processor('file_decoder')(source)
                graph = grapher(width=width, height=height)
                (decoder | graph).run()
                graph.watermark('timeside', opacity=.6, margin=(5, 5))
                #f = open(path, 'w')
                graph.render(output=path)
                # f.close()
                self.cache_data.add_file(image_file)

        response = StreamingHttpResponse(self.cache_data.read_stream_bin(image_file), content_type=mime_type)
        return response

    def list_export_extensions(self):
        "Return the recognized item export file extensions, as a list"
        list = []
        for encoder in self.encoders:
            list.append(encoder.file_extension())
        # FIXME: MP4
        list.append('mp4')
        return list

    def item_transcode(self, item, extension):
        for encoder in self.encoders:
            if encoder.file_extension() == extension:
                break

        if encoder.file_extension() != extension:
            raise Http404('Unknown export file extension: %s' % extension)

        mime_type = encoder.mime_type()
        file = item.public_id + '.' + encoder.file_extension()
        source, source_type = item.get_source()

        is_transcoded_flag = self.get_is_transcoded_flag(item=item, mime_type=mime_type)

        format = item.mime_type
        dc_metadata = dublincore.express_item(item).to_list()
        mapping = DublinCoreToFormatMetadata(extension)
        if not extension in mapping.unavailable_extensions:
            metadata = mapping.get_metadata(dc_metadata)
        else:
            metadata = None

        if mime_type in format and source_type == 'file':
            # source > stream
            if metadata:
                proc = encoder(source, overwrite=True)
                proc.set_metadata(metadata)
                try:
                    # FIXME: should test if metadata writer is available
                    proc.write_metadata()
                except:
                    pass
            return (source, mime_type)
        else:
            media = self.cache_export.dir + os.sep + file
            if not is_transcoded_flag.value:
                try:
                    progress_flag = MediaItemTranscodingFlag.objects.get(
                        item=item,
                        mime_type=mime_type + '/transcoding')
                    if progress_flag.value:
                        # The media is being transcoded
                        # return None
                        return (None, None)

                    else:
                        # wait for the transcode to begin
                        time.sleep(1)
                        return (None, None)  # self.item_transcode(item, extension)

                except MediaItemTranscodingFlag.DoesNotExist:
                    pass
                # source > encoder > stream
                from telemeta.tasks import task_transcode
                # Sent the transcoding task synchronously to the worker
                task_transcode.apply_async(kwargs={'source': source,
                                                   'media': media,
                                                   'encoder_id': encoder.id(),
                                                   'item_public_id': item.public_id,
                                                   'mime_type': mime_type,
                                                   'metadata': metadata})

                self.cache_export.add_file(file)
                if not os.path.exists(media):
                    return (None, None)
            else:
                # cache > stream
                if not os.path.exists(media):
                    is_transcoded_flag.value = False
                    is_transcoded_flag.save()
                    return self.item_transcode(item, extension)

        return (media, mime_type)

    def item_export(self, request, public_id, extension, return_availability=False):
        """Export a given media item in the specified format (OGG, FLAC, ...)"""

        item = MediaItem.objects.get(public_id=public_id)
        public_access = get_item_access(item, request.user)

        if not extension:
            extension = item.file.path.split('.')[-1]

        if (not public_access == 'full' or not extension in settings.TELEMETA_STREAMING_FORMATS) and \
                not (request.user.has_perm('telemeta.can_play_all_items') or request.user.is_superuser):
            mess = ugettext('Access not allowed')
            title = 'Item file : ' + public_id + '.' + extension + ' : ' + mess
            description = ugettext('Please login or contact the website administator to get a private access.')
            messages.error(request, title)
            return render(request, 'telemeta/messages.html', {'description': description})

        # FIXME: MP4 handling in TimeSide
        if 'mp4' in extension:
            mime_type = 'video/mp4'
            video = item.file.path
            response = serve_media(video, content_type=mime_type)
            # response['Content-Disposition'] = 'attachment'
            # TF : I don't know why empty attachment was set
            # TODO: remove if useless
            if return_availability:
                data = json.dumps({'available': True})
                return HttpResponse(data, content_type='application/json')
            return response

        if 'webm' in extension:
            mime_type = 'video/webm'
            video = item.file.path
            response = serve_media(video, content_type=mime_type)
            # response['Content-Disposition'] = 'attachment'
            # TF : I don't know why empty attachment was set,
            # TODO: remove if useless
            if return_availability:
                data = json.dumps({'available': True})
                return HttpResponse(data, content_type='application/json')
            return response

        (media, mime_type) = self.item_transcode(item, extension)
        #media  = None
        if media:
            if return_availability:
                data = json.dumps({'available': True})
                return HttpResponse(data, content_type='application/json')
            response = serve_media(media, content_type=mime_type)
            return response
        else:
            if return_availability:
                data = json.dumps({'available': False})
                return HttpResponse(data, content_type='application/json')

            mess = ugettext('Transcoding in progress')
            title = ugettext('Item') + ' : ' + public_id + ' : ' + mess
            description = ugettext('The media transcoding is in progress. '
                                   'Please wait for the trancoding process to complete.')
            messages.info(request, title)
            response = render(request, 'telemeta/messages.html', {'description': description})
            from django.utils.cache import patch_cache_control
            #patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)
            return response

    def item_export_available(self, request, public_id, extension):
        return self.item_export(request, public_id, extension, return_availability=True)

    def item_playlist(self, request, public_id, template, mimetype):
        try:
            item = MediaItem.objects.get(public_id=public_id)
        except ObjectDoesNotExist:
            raise Http404

        template = loader.get_template(template)
        context = RequestContext(request, {'item': item, 'host': request.META['HTTP_HOST']})
        return HttpResponse(template.render(context), content_type=mimetype)

    @method_decorator(permission_required('telemeta.change_mediaitem'))
    def item_performances_edit(self, request, public_id, template):
        item = MediaItem.objects.get(public_id=public_id)
        PerformanceFormSet = inlineformset_factory(MediaItem, MediaItemPerformance, form=MediaItemPerformanceForm)
        if request.method == 'POST':
            formset = PerformanceFormSet(data=request.POST, instance=item)
            if formset.is_valid():
                formset.save()
                return redirect('telemeta-item-edit', item.public_id)
        else:
            formset = PerformanceFormSet(instance=item)
        return render(request, template, {'item': item, 'formset': formset, })

    @method_decorator(permission_required('telemeta.change_mediaitem'))
    def item_keywords_edit(self, request, public_id, template):
        item = MediaItem.objects.get(public_id=public_id)
        FormSet = inlineformset_factory(MediaItem, MediaItemKeyword)
        if request.method == 'POST':
            formset = FormSet(data=request.POST, instance=item)
            if formset.is_valid():
                formset.save()
                return redirect('telemeta-item-edit', item.public_id)
        else:
            formset = FormSet(instance=item)
        return render(request, template, {'item': item, 'formset': formset, })

Ancestors (in MRO)

Class variables

var CACHE_DIR

Inheritance: ItemBaseMixin.CACHE_DIR

var MEDIA_ROOT

Inheritance: ItemBaseMixin.MEDIA_ROOT

var analyzers

Inheritance: ItemBaseMixin.analyzers

var auto_zoom

Inheritance: ItemBaseMixin.auto_zoom

var cache_data

Inheritance: ItemBaseMixin.cache_data

var cache_export

Inheritance: ItemBaseMixin.cache_export

var cache_tmp

Inheritance: ItemBaseMixin.cache_tmp

var decoders

Inheritance: ItemBaseMixin.decoders

var default_grapher_id

Inheritance: ItemBaseMixin.default_grapher_id

var default_grapher_sizes

Inheritance: ItemBaseMixin.default_grapher_sizes

var encoders

Inheritance: ItemBaseMixin.encoders

var export_enabled

Inheritance: ItemBaseMixin.export_enabled

var export_formats

Inheritance: ItemBaseMixin.export_formats

var graphers

Inheritance: ItemBaseMixin.graphers

var public_graphers

Inheritance: ItemBaseMixin.public_graphers

var value_analyzers

Inheritance: ItemBaseMixin.value_analyzers

Methods

def get_export_formats(

self)

Inheritance: ItemBaseMixin.get_export_formats

def get_export_formats(self):
    formats = []
    for encoder in self.encoders:
        if encoder.file_extension() in self.export_formats:
            formats.append({'name': encoder.format(),
                            'extension': encoder.file_extension()})
    return formats

def get_grapher(

self, id)

Inheritance: ItemBaseMixin.get_grapher

def get_grapher(self, id):
    for grapher in self.graphers:
        if grapher.id() == id:
            break
    return grapher

def get_graphers(

self)

Inheritance: ItemBaseMixin.get_graphers

def get_graphers(self):
    graphers = []
    user = self.request.user
    graphers_access = (user.is_staff
                       or user.is_superuser
                       or user.has_perm('can_run_analysis'))
    for grapher in self.graphers:
        if (not graphers_access
            and grapher.id() not in self.public_graphers):
            continue
        if grapher.id() == self.default_grapher_id:
            graphers.insert(0, {'name': grapher.name(), 'id': grapher.id()})
        elif not hasattr(grapher, '_staging'):
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
        elif not grapher._staging:
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
    return graphers

def get_is_transcoded_flag(

self, item, mime_type)

Inheritance: ItemBaseMixin.get_is_transcoded_flag

def get_is_transcoded_flag(self, item, mime_type):
    try:
        is_transcoded_flag, c = MediaItemTranscodingFlag.objects.get_or_create(
            item=item,
            mime_type=mime_type,
            defaults={'value': False})
    except MediaItemTranscodingFlag.MultipleObjectsReturned:
        flags = MediaItemTranscodingFlag.objects.filter(
            item=item,
            mime_type=mime_type)
        value = all([f.value for f in flags])
        is_transcoded_flag = flags[0]
        is_transcoded_flag.value = value
        is_transcoded_flag.save()
        for f in flags[1:]:
            f.delete()
    return is_transcoded_flag

def get_item_file_url(

*a, **kw)

Inheritance: ItemBaseMixin.get_item_file_url

@jsonrpc_method('telemeta.get_item_export_url')
def get_item_file_url(request, public_id, extension):
    return reverse('telemeta-item-export', kwargs={'public_id': public_id, 'extension': extension})

def item_analyze_xml(

self, request, public_id)

def item_analyze_xml(self, request, public_id):
    item = MediaItem.objects.get(public_id=public_id)
    analyses = item.analysis.all()
    analyzers = []
    for analysis in analyses:
        analyzers.append(analysis.to_dict())
    mime_type = 'text/xml'
    response = HttpResponse(self.cache_data.get_analyzer_xml(analyzers), content_type=mime_type)
    response['Content-Disposition'] = 'attachment; filename=' + public_id + '.xml'
    return response

def item_delete(

self, *args, **kwargs)

Delete a given item

def _wrapper(self, *args, **kwargs):
    @decorator
    def bound_func(*args2, **kwargs2):
        return func(self, *args2, **kwargs2)
    # bound_func has the signature that 'decorator' expects i.e.  no
    # 'self' argument, but it is a closure over self so it can call
    # 'func' correctly.
    return bound_func(*args, **kwargs)

def item_detail(

self, request, public_id=None, marker_id=None, width=None, height=None, template='telemeta/mediaitem_detail.html')

Show the details of a given item

def item_detail(self, request, public_id=None, marker_id=None, width=None, height=None,
                template='telemeta/mediaitem_detail.html'):
    """Show the details of a given item"""
    # get item with one of its given marker_id
    if not public_id and marker_id:
        marker = get_object_or_404(MediaItemMarker, public_id=marker_id)
        item_id = marker.item_id
        item = MediaItem.objects.get(id=item_id)
    else:
        item = get_object_or_404(MediaItem, public_id=public_id)
    access = get_item_access(item, request.user)
    if access == 'none':
        mess = ugettext('Access not allowed')
        title = ugettext('Item') + ' : ' + public_id + ' : ' + mess
        description = ugettext('Please login or contact the website administator to get a private access.')
        messages.error(request, title)
        return render(request, 'telemeta/messages.html', {'description': description})
    previous, next = self.item_previous_next(item)
    mime_type = item.mime_type
    if mime_type and mime_type != 'none':
        if 'quicktime' in mime_type:
            mime_type = 'video/mp4'
    playlists = get_playlists_names(request)
    related_media = MediaItemRelated.objects.filter(item=item)
    check_related_media(related_media)
    revisions = Revision.objects.filter(element_type='item', element_id=item.id).order_by('-time')
    if revisions:
        last_revision = revisions[0]
    else:
        last_revision = None
    format = ''
    if Format.objects.filter(item=item):
        format = item.format.get()
    return render(request, template,
                  {'item': item, 'export_formats': self.get_export_formats(),
                   'visualizers': self.get_graphers(), 'auto_zoom': self.auto_zoom,
                   'audio_export_enabled': self.export_enabled,
                   'previous': previous, 'next': next, 'marker': marker_id, 'playlists': playlists,
                   'access': access, 'width': width, 'height': height,
                   'related_media': related_media, 'mime_type': mime_type, 'last_revision': last_revision,
                   'format': format,
                   })

def item_export(

self, request, public_id, extension, return_availability=False)

Export a given media item in the specified format (OGG, FLAC, ...)

def item_export(self, request, public_id, extension, return_availability=False):
    """Export a given media item in the specified format (OGG, FLAC, ...)"""
    item = MediaItem.objects.get(public_id=public_id)
    public_access = get_item_access(item, request.user)
    if not extension:
        extension = item.file.path.split('.')[-1]
    if (not public_access == 'full' or not extension in settings.TELEMETA_STREAMING_FORMATS) and \
            not (request.user.has_perm('telemeta.can_play_all_items') or request.user.is_superuser):
        mess = ugettext('Access not allowed')
        title = 'Item file : ' + public_id + '.' + extension + ' : ' + mess
        description = ugettext('Please login or contact the website administator to get a private access.')
        messages.error(request, title)
        return render(request, 'telemeta/messages.html', {'description': description})
    # FIXME: MP4 handling in TimeSide
    if 'mp4' in extension:
        mime_type = 'video/mp4'
        video = item.file.path
        response = serve_media(video, content_type=mime_type)
        # response['Content-Disposition'] = 'attachment'
        # TF : I don't know why empty attachment was set
        # TODO: remove if useless
        if return_availability:
            data = json.dumps({'available': True})
            return HttpResponse(data, content_type='application/json')
        return response
    if 'webm' in extension:
        mime_type = 'video/webm'
        video = item.file.path
        response = serve_media(video, content_type=mime_type)
        # response['Content-Disposition'] = 'attachment'
        # TF : I don't know why empty attachment was set,
        # TODO: remove if useless
        if return_availability:
            data = json.dumps({'available': True})
            return HttpResponse(data, content_type='application/json')
        return response
    (media, mime_type) = self.item_transcode(item, extension)
    #media  = None
    if media:
        if return_availability:
            data = json.dumps({'available': True})
            return HttpResponse(data, content_type='application/json')
        response = serve_media(media, content_type=mime_type)
        return response
    else:
        if return_availability:
            data = json.dumps({'available': False})
            return HttpResponse(data, content_type='application/json')
        mess = ugettext('Transcoding in progress')
        title = ugettext('Item') + ' : ' + public_id + ' : ' + mess
        description = ugettext('The media transcoding is in progress. '
                               'Please wait for the trancoding process to complete.')
        messages.info(request, title)
        response = render(request, 'telemeta/messages.html', {'description': description})
        from django.utils.cache import patch_cache_control
        #patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)
        return response

def item_export_available(

self, request, public_id, extension)

def item_export_available(self, request, public_id, extension):
    return self.item_export(request, public_id, extension, return_availability=True)

def item_keywords_edit(

self, *args, **kwargs)

def _wrapper(self, *args, **kwargs):
    @decorator
    def bound_func(*args2, **kwargs2):
        return func(self, *args2, **kwargs2)
    # bound_func has the signature that 'decorator' expects i.e.  no
    # 'self' argument, but it is a closure over self so it can call
    # 'func' correctly.
    return bound_func(*args, **kwargs)

def item_performances_edit(

self, *args, **kwargs)

def _wrapper(self, *args, **kwargs):
    @decorator
    def bound_func(*args2, **kwargs2):
        return func(self, *args2, **kwargs2)
    # bound_func has the signature that 'decorator' expects i.e.  no
    # 'self' argument, but it is a closure over self so it can call
    # 'func' correctly.
    return bound_func(*args, **kwargs)

def item_playlist(

self, request, public_id, template, mimetype)

def item_playlist(self, request, public_id, template, mimetype):
    try:
        item = MediaItem.objects.get(public_id=public_id)
    except ObjectDoesNotExist:
        raise Http404
    template = loader.get_template(template)
    context = RequestContext(request, {'item': item, 'host': request.META['HTTP_HOST']})
    return HttpResponse(template.render(context), content_type=mimetype)

def item_previous_next(

self, item)

Inheritance: ItemBaseMixin.item_previous_next

Get previous and next items inside the collection of the item

def item_previous_next(self, item):
    """Get previous and next items inside the collection of the item"""
    pks = []
    items = MediaItem.objects.filter(collection=item.collection)
    items = items.order_by('code', 'old_code')
    if len(items) > 1:
        for it in items:
            pks.append(it.pk)
        for pk in pks:
            if pk == item.pk:
                if pk == pks[0]:
                    previous_pk = pks[-1]
                    next_pk = pks[1]
                elif pk == pks[-1]:
                    previous_pk = pks[-2]
                    next_pk = pks[0]
                else:
                    previous_pk = pks[pks.index(pk) - 1]
                    next_pk = pks[pks.index(pk) + 1]
                for it in items:
                    if it.pk == previous_pk:
                        previous = it
                    if it.pk == next_pk:
                        next = it
                previous = previous.public_id
                next = next.public_id
    else:
        previous = item.public_id
        next = item.public_id
    return previous, next

def item_transcode(

self, item, extension)

def item_transcode(self, item, extension):
    for encoder in self.encoders:
        if encoder.file_extension() == extension:
            break
    if encoder.file_extension() != extension:
        raise Http404('Unknown export file extension: %s' % extension)
    mime_type = encoder.mime_type()
    file = item.public_id + '.' + encoder.file_extension()
    source, source_type = item.get_source()
    is_transcoded_flag = self.get_is_transcoded_flag(item=item, mime_type=mime_type)
    format = item.mime_type
    dc_metadata = dublincore.express_item(item).to_list()
    mapping = DublinCoreToFormatMetadata(extension)
    if not extension in mapping.unavailable_extensions:
        metadata = mapping.get_metadata(dc_metadata)
    else:
        metadata = None
    if mime_type in format and source_type == 'file':
        # source > stream
        if metadata:
            proc = encoder(source, overwrite=True)
            proc.set_metadata(metadata)
            try:
                # FIXME: should test if metadata writer is available
                proc.write_metadata()
            except:
                pass
        return (source, mime_type)
    else:
        media = self.cache_export.dir + os.sep + file
        if not is_transcoded_flag.value:
            try:
                progress_flag = MediaItemTranscodingFlag.objects.get(
                    item=item,
                    mime_type=mime_type + '/transcoding')
                if progress_flag.value:
                    # The media is being transcoded
                    # return None
                    return (None, None)
                else:
                    # wait for the transcode to begin
                    time.sleep(1)
                    return (None, None)  # self.item_transcode(item, extension)
            except MediaItemTranscodingFlag.DoesNotExist:
                pass
            # source > encoder > stream
            from telemeta.tasks import task_transcode
            # Sent the transcoding task synchronously to the worker
            task_transcode.apply_async(kwargs={'source': source,
                                               'media': media,
                                               'encoder_id': encoder.id(),
                                               'item_public_id': item.public_id,
                                               'mime_type': mime_type,
                                               'metadata': metadata})
            self.cache_export.add_file(file)
            if not os.path.exists(media):
                return (None, None)
        else:
            # cache > stream
            if not os.path.exists(media):
                is_transcoded_flag.value = False
                is_transcoded_flag.save()
                return self.item_transcode(item, extension)
    return (media, mime_type)

def item_visualize(

self, request, public_id, grapher_id, width, height)

def item_visualize(self, request, public_id, grapher_id, width, height):
    try:
        width = int(width)
        height = int(height)
    except:
        pass
    if not isinstance(width, int) or not isinstance(height, int):
        size = self.default_grapher_sizes[0]
        width = int(size.split('x')[0])
        height = int(size.split('x')[1])
    item = MediaItem.objects.get(public_id=public_id)
    mime_type = 'image/png'
    source, source_type = item.get_source()
    # if source:
    #     ts_item, c = ts.models.Item.objects.get_or_create(**{source_type: source})
    #     if c:
    #         ts_item.title = item.title
    #         ts_item.save()
    #
    # ts_grapher, c = ts.models.Processor.objects.get_or_create(pid=grapher_id)
    # ts_preset, c = ts.models.Preset.objects.get_or_create(processor=ts_grapher,
    #                                                       parameters={'width': width, 'height': height})
    # ts_experience = ts_preset.get_single_experience()
    # ts_selection = ts_item.get_single_selection()
    # ts_task, c = ts.models.Task.objects.get_or_create(experience=ts_experience,
    #                                            selection=ts_selection)
    # ts_task.run()
    grapher = self.get_grapher(grapher_id)
    if grapher.id() != grapher_id:
        raise Http404
    size = str(width) + '_' + str(height)
    image_file = '.'.join([public_id, grapher_id, size, 'png'])
    # FIX waveform grapher name change
    old_image_file = '.'.join([public_id, 'waveform', size, 'png'])
    if 'waveform_centroid' in grapher_id and self.cache_data.exists(old_image_file):
        image_file = old_image_file
    if not self.cache_data.exists(image_file):
        source, _ = item.get_source()
        if source:
            path = self.cache_data.dir + os.sep + image_file
            decoder = timeside.core.get_processor('file_decoder')(source)
            graph = grapher(width=width, height=height)
            (decoder | graph).run()
            graph.watermark('timeside', opacity=.6, margin=(5, 5))
            #f = open(path, 'w')
            graph.render(output=path)
            # f.close()
            self.cache_data.add_file(image_file)
    response = StreamingHttpResponse(self.cache_data.read_stream_bin(image_file), content_type=mime_type)
    return response

def list_export_extensions(

self)

Return the recognized item export file extensions, as a list

def list_export_extensions(self):
    "Return the recognized item export file extensions, as a list"
    list = []
    for encoder in self.encoders:
        list.append(encoder.file_extension())
    # FIXME: MP4
    list.append('mp4')
    return list

def related_media_edit(

self, *args, **kwargs)

def _wrapper(self, *args, **kwargs):
    @decorator
    def bound_func(*args2, **kwargs2):
        return func(self, *args2, **kwargs2)
    # bound_func has the signature that 'decorator' expects i.e.  no
    # 'self' argument, but it is a closure over self so it can call
    # 'func' correctly.
    return bound_func(*args, **kwargs)

def related_media_item_download(

self, request, item_public_id, media_id)

def related_media_item_download(self, request, item_public_id, media_id):
    item = get_object_or_404(MediaItem, code=item_public_id)
    media = get_object_or_404(MediaItemRelated, item=item, id=media_id)
    if media.file:
        response = serve_media(media.file.path, content_type=media.mime_type)
    else:
        raise Http404
    return response

def related_media_item_stream(

self, request, item_public_id, media_id)

def related_media_item_stream(self, request, item_public_id, media_id):
    item = get_object_or_404(MediaItem, code=item_public_id)
    media = get_object_or_404(MediaItemRelated, item=item, id=media_id)
    if media.file:
        response = serve_media(media.file.path, content_type=media.mime_type)
    else:
        raise Http404
    return response

class ItemViewMixin

class ItemViewMixin(ItemBaseMixin):

    model = MediaItem
    form_class = MediaItemForm
    inlines = [ItemPerformanceInline, ItemKeywordInline, ItemRelatedInline, ItemIdentifierInline]
    # inlines = [ItemPerformanceInline, ItemKeywordInline, ItemRelatedInline,
    #             ItemFormatInline, ItemIdentifierInline]

    def get_object(self):
        obj = self.model.objects.filter(code=self.kwargs['public_id'])
        if not obj:
            if self.kwargs['public_id'].isdigit():
                try:
                    obj = self.model.objects.get(id=self.kwargs['public_id'])
                except self.model.DoesNotExist:
                    raise Http404
            else:
                raise Http404
        else:
            obj = obj[0]
        return obj

Ancestors (in MRO)

Class variables

var CACHE_DIR

Inheritance: ItemBaseMixin.CACHE_DIR

var MEDIA_ROOT

Inheritance: ItemBaseMixin.MEDIA_ROOT

var analyzers

Inheritance: ItemBaseMixin.analyzers

var auto_zoom

Inheritance: ItemBaseMixin.auto_zoom

var cache_data

Inheritance: ItemBaseMixin.cache_data

var cache_export

Inheritance: ItemBaseMixin.cache_export

var cache_tmp

Inheritance: ItemBaseMixin.cache_tmp

var decoders

Inheritance: ItemBaseMixin.decoders

var default_grapher_id

Inheritance: ItemBaseMixin.default_grapher_id

var default_grapher_sizes

Inheritance: ItemBaseMixin.default_grapher_sizes

var encoders

Inheritance: ItemBaseMixin.encoders

var export_enabled

Inheritance: ItemBaseMixin.export_enabled

var export_formats

Inheritance: ItemBaseMixin.export_formats

var form_class

var graphers

Inheritance: ItemBaseMixin.graphers

var inlines

var model

var public_graphers

Inheritance: ItemBaseMixin.public_graphers

var value_analyzers

Inheritance: ItemBaseMixin.value_analyzers

Methods

def get_export_formats(

self)

Inheritance: ItemBaseMixin.get_export_formats

def get_export_formats(self):
    formats = []
    for encoder in self.encoders:
        if encoder.file_extension() in self.export_formats:
            formats.append({'name': encoder.format(),
                            'extension': encoder.file_extension()})
    return formats

def get_grapher(

self, id)

Inheritance: ItemBaseMixin.get_grapher

def get_grapher(self, id):
    for grapher in self.graphers:
        if grapher.id() == id:
            break
    return grapher

def get_graphers(

self)

Inheritance: ItemBaseMixin.get_graphers

def get_graphers(self):
    graphers = []
    user = self.request.user
    graphers_access = (user.is_staff
                       or user.is_superuser
                       or user.has_perm('can_run_analysis'))
    for grapher in self.graphers:
        if (not graphers_access
            and grapher.id() not in self.public_graphers):
            continue
        if grapher.id() == self.default_grapher_id:
            graphers.insert(0, {'name': grapher.name(), 'id': grapher.id()})
        elif not hasattr(grapher, '_staging'):
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
        elif not grapher._staging:
            graphers.append({'name': grapher.name(), 'id': grapher.id()})
    return graphers

def get_is_transcoded_flag(

self, item, mime_type)

Inheritance: ItemBaseMixin.get_is_transcoded_flag

def get_is_transcoded_flag(self, item, mime_type):
    try:
        is_transcoded_flag, c = MediaItemTranscodingFlag.objects.get_or_create(
            item=item,
            mime_type=mime_type,
            defaults={'value': False})
    except MediaItemTranscodingFlag.MultipleObjectsReturned:
        flags = MediaItemTranscodingFlag.objects.filter(
            item=item,
            mime_type=mime_type)
        value = all([f.value for f in flags])
        is_transcoded_flag = flags[0]
        is_transcoded_flag.value = value
        is_transcoded_flag.save()
        for f in flags[1:]:
            f.delete()
    return is_transcoded_flag

def get_item_file_url(

*a, **kw)

Inheritance: ItemBaseMixin.get_item_file_url

@jsonrpc_method('telemeta.get_item_export_url')
def get_item_file_url(request, public_id, extension):
    return reverse('telemeta-item-export', kwargs={'public_id': public_id, 'extension': extension})

def get_object(

self)

def get_object(self):
    obj = self.model.objects.filter(code=self.kwargs['public_id'])
    if not obj:
        if self.kwargs['public_id'].isdigit():
            try:
                obj = self.model.objects.get(id=self.kwargs['public_id'])
            except self.model.DoesNotExist:
                raise Http404
        else:
            raise Http404
    else:
        obj = obj[0]
    return obj

def item_previous_next(

self, item)

Inheritance: ItemBaseMixin.item_previous_next

Get previous and next items inside the collection of the item

def item_previous_next(self, item):
    """Get previous and next items inside the collection of the item"""
    pks = []
    items = MediaItem.objects.filter(collection=item.collection)
    items = items.order_by('code', 'old_code')
    if len(items) > 1:
        for it in items:
            pks.append(it.pk)
        for pk in pks:
            if pk == item.pk:
                if pk == pks[0]:
                    previous_pk = pks[-1]
                    next_pk = pks[1]
                elif pk == pks[-1]:
                    previous_pk = pks[-2]
                    next_pk = pks[0]
                else:
                    previous_pk = pks[pks.index(pk) - 1]
                    next_pk = pks[pks.index(pk) + 1]
                for it in items:
                    if it.pk == previous_pk:
                        previous = it
                    if it.pk == next_pk:
                        next = it
                previous = previous.public_id
                next = next.public_id
    else:
        previous = item.public_id
        next = item.public_id
    return previous, next