telemeta.views.collection module
# -*- coding: utf-8 -*- # Copyright (C) 2007-2010 Samalyse SARL # Copyright (C) 2010-2012 Parisson 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.epub import * class CollectionView(object): """Provide Collections web UI methods""" def collection_detail(self, request, public_id, template='telemeta/collection_detail.html'): collection = MediaCollection.objects.get(public_id=public_id) items = collection.items.enriched() items = items.order_by('code', 'old_code') if collection.public_access == 'none' and not (request.user.is_staff or request.user.is_superuser): mess = ugettext('Access not allowed') title = ugettext('Collection') + ' : ' + 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}) playlists = get_playlists_names(request) related_media = MediaCollectionRelated.objects.filter(collection=collection) check_related_media(related_media) parents = MediaCorpus.objects.filter(children=collection) revisions = Revision.objects.filter(element_type='collection', element_id=collection.id).order_by('-time') if revisions: last_revision = revisions[0] else: last_revision = None return render(request, template, {'collection': collection, 'playlists': playlists, 'items': items, 'related_media': related_media, 'parents': parents, 'last_revision': last_revision}) @method_decorator(permission_required('telemeta.change_mediacollection')) def collection_edit(self, request, public_id, template='telemeta/collection_edit.html'): collection = MediaCollection.objects.get(public_id=public_id) if request.method == 'POST': form = MediaCollectionForm(data=request.POST, files=request.FILES, instance=collection) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id form.save() collection.set_revision(request.user) return redirect('telemeta-collection-detail', code) else: form = MediaCollectionForm(instance=collection) return render(request, template, {'collection': collection, "form": form, }) @method_decorator(permission_required('telemeta.add_mediacollection')) def collection_add(self, request, template='telemeta/collection_add.html'): collection = MediaCollection() if request.method == 'POST': form = MediaCollectionForm(data=request.POST, files=request.FILES, instance=collection) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id form.save() collection.set_revision(request.user) return redirect('telemeta-collection-detail', code) else: form = MediaCollectionForm(instance=collection) return render(request, template, {'collection': collection, "form": form, }) @method_decorator(permission_required('telemeta.add_mediacollection')) def collection_copy(self, request, public_id, template='telemeta/collection_edit.html'): if request.method == 'POST': collection = MediaCollection() form = MediaCollectionForm(data=request.POST, files=request.FILES, instance=collection) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id form.save() collection.set_revision(request.user) return redirect('telemeta-collection-detail', code) else: collection = MediaCollection.objects.get(public_id=public_id) form = MediaCollectionForm(instance=collection) return render(request, template, {'collection': collection, "form": form, }) def collection_playlist(self, request, public_id, template, mimetype): try: collection = MediaCollection.objects.get(public_id=public_id) except ObjectDoesNotExist: raise Http404 template = loader.get_template(template) context = RequestContext(request, {'collection': collection, 'host': request.META['HTTP_HOST']}) return HttpResponse(template.render(context), content_type=mimetype) @method_decorator(permission_required('telemeta.delete_mediacollection')) def collection_delete(self, request, public_id): """Delete a given collection""" collection = MediaCollection.objects.get(public_id=public_id) revisions = Revision.objects.filter(element_type='collection', element_id=collection.id) for revision in revisions: revision.delete() collection.delete() return redirect('telemeta-collections') def related_media_collection_stream(self, request, public_id, media_id): collection = MediaCollection.objects.get(public_id=public_id) media = MediaCollectionRelated.objects.get(collection=collection, id=media_id) response = serve_media(media.file.path, content_type=media.mime_type) return response def related_media_collection_download(self, request, public_id, media_id): collection = MediaCollection.objects.get(public_id=public_id) media = MediaCollectionRelated.objects.get(collection=collection, id=media_id) response = serve_media(media.file.path, content_type=media.mime_type) return response @method_decorator(permission_required('telemeta.change_mediacollection')) def related_media_edit(self, request, public_id, template): collection = MediaCollection.objects.get(public_id=public_id) MediaCollectionRelatedFormSet = inlineformset_factory(MediaCollection, MediaCollectionRelated, form=MediaCollectionRelatedForm) if request.method == 'POST': formset = MediaCollectionRelatedFormSet(data=request.POST, files=request.FILES, instance=collection) if formset.is_valid(): formset.save() collection.set_revision(request.user) return redirect('telemeta-collection-edit', public_id) else: formset = MediaCollectionRelatedFormSet(instance=collection) return render(request, template, {'collection': collection, 'formset': formset, }) class CollectionZipView(View): model = MediaCollection def get_object(self): return MediaCollection.objects.get(public_id=self.kwargs['public_id']) def get(self, request, *args, **kwargs): """ Stream a ZIP file of collection data without loading the whole file into memory. Based on ZipStream """ from telemeta.views import MarkerView from telemeta.backup import CollectionSerializer import zipstream from zipfile import ZIP_DEFLATED, ZIP_STORED import json zip_file = zipstream.ZipFile(mode='w', compression=ZIP_STORED, allowZip64=True) cache_data = TelemetaCache(settings.TELEMETA_DATA_CACHE_DIR) collection = self.get_object() serializer = CollectionSerializer(collection) data = collection.get_json().encode('utf-8') filename = collection.public_id + '.json' cache_data.write_bin(data, filename) path = cache_data.dir + os.sep + filename zip_file.write(path, arcname=collection.public_id + os.sep + filename) data = serializer.get_xml().encode('utf-8') filename = collection.public_id + '.xml' cache_data.write_bin(data, filename) path = cache_data.dir + os.sep + filename zip_file.write(path, arcname=collection.public_id + os.sep + filename) for item in collection.items.all(): if item.file: filename, ext = os.path.splitext(item.file.path.split(os.sep)[-1]) zip_file.write(item.file.path, arcname=collection.public_id + os.sep + item.code + ext) marker_view = MarkerView() markers = marker_view.get_markers(item.id) if markers: data = json.dumps(markers) filename = item.code + '.json' cache_data.write_bin(data, filename) path = cache_data.dir + os.sep + filename zip_file.write(path, arcname=collection.public_id + os.sep + filename) response = StreamingHttpResponse(zip_file, content_type='application/zip') response['Content-Disposition'] = "attachment; filename=%s.%s" % \ (collection.code, 'zip') return response @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(CollectionZipView, self).dispatch(*args, **kwargs) class CollectionViewMixin(object): model = MediaCollection form_class = MediaCollectionForm 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 CollectionListView(ListView): model = MediaCollection template_name = "telemeta/collection_list.html" paginate_by = 20 queryset = MediaCollection.objects.enriched() def get_context_data(self, **kwargs): context = super(CollectionListView, self).get_context_data(**kwargs) context['count'] = self.object_list.count() return context class CollectionUnpublishedListView(CollectionListView): queryset = MediaCollection.objects.filter(code__contains='_I_') class CollectionPublishedListView(CollectionListView): queryset = MediaCollection.objects.filter(code__contains='_E_') class CollectionSoundListView(CollectionListView): queryset = MediaCollection.objects.sound().order_by('code', 'old_code') class CollectionDetailView(CollectionViewMixin, DetailView): template_name = 'telemeta/collection_detail.html' def get_context_data(self, **kwargs): context = super(CollectionDetailView, self).get_context_data(**kwargs) collection = self.get_object() items = collection.items.enriched() context['collection'] = collection context['items'] = items.order_by('code', 'old_code') context['playlists'] = get_playlists_names(self.request) context['related_media'] = MediaCollectionRelated.objects.filter(collection=collection) check_related_media(context['related_media']) context['parents'] = MediaCorpus.objects.filter(children=collection) revisions = Revision.objects.filter(element_type='collection', element_id=collection.id) if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None return context class CollectionDetailViewDC(CollectionDetailView): template_name = "telemeta/collection_detail_dc.html" class CollectionEditView(CollectionViewMixin, UpdateWithInlinesView): template_name = 'telemeta/collection_edit.html' inlines = [CollectionRelatedInline, CollectionIdentifierInline] def forms_valid(self, form, inlines): messages.info(self.request, ugettext_lazy("You have successfully updated your collection.")) obj = form.save() obj.set_revision(self.request.user) self.code = obj.code return super(CollectionEditView, self).forms_valid(form, inlines) def get_success_url(self): return reverse_lazy('telemeta-collection-detail', kwargs={'public_id': self.code}) def get_context_data(self, **kwargs): context = super(CollectionEditView, self).get_context_data(**kwargs) collection = self.get_object() context['collection'] = collection return context @method_decorator(permission_required('telemeta.change_mediacollection')) def dispatch(self, *args, **kwargs): return super(CollectionEditView, self).dispatch(*args, **kwargs) class CollectionAddView(CollectionViewMixin, CreateWithInlinesView): template_name = 'telemeta/collection_add.html' inlines = [CollectionRelatedInline, CollectionIdentifierInline] def forms_valid(self, form, inlines): messages.info(self.request, ugettext_lazy("You have successfully added your collection.")) obj = form.save() obj.set_revision(self.request.user) return super(CollectionAddView, self).forms_valid(form, inlines) def get_success_url(self): return reverse_lazy('telemeta-collection-detail', kwargs={'public_id': self.object.code}) @method_decorator(permission_required('telemeta.add_mediacollection')) def dispatch(self, *args, **kwargs): return super(CollectionAddView, self).dispatch(*args, **kwargs) class CollectionCopyView(CollectionAddView): template_name = 'telemeta/collection_edit.html' def get_initial(self): return model_to_dict(self.get_object()) def get_context_data(self, **kwargs): context = super(CollectionCopyView, self).get_context_data(**kwargs) collection = self.get_object() context['collection'] = collection return context @method_decorator(permission_required('telemeta.add_mediacollection')) def dispatch(self, *args, **kwargs): return super(CollectionCopyView, self).dispatch(*args, **kwargs) class CollectionEpubView(BaseEpubMixin, View): "Download collection data embedded in an EPUB3 file" model = MediaCollection def get_object(self): return MediaCollection.objects.get(public_id=self.kwargs['public_id']) def get(self, request, *args, **kwargs): collection = self.get_object() corpus = collection.corpus.all()[0] self.setup_epub(corpus, collection=collection) if not os.path.exists(self.path): self.write_book() epub_file = open(self.path, 'rb') response = HttpResponse(epub_file.read(), content_type='application/epub+zip') response['Content-Disposition'] = "attachment; filename=%s" % self.filename + '.epub' return response # @method_decorator(login_required) # @method_decorator(permission_required('telemeta.can_download_collection_epub')) def dispatch(self, *args, **kwargs): return super(CollectionEpubView, self).dispatch(*args, **kwargs) class CollectionEnumListView(CollectionListView): template_name = "telemeta/collection_enum_list.html" def get_context_data(self, **kwargs): context = super(CollectionListView, self).get_context_data(**kwargs) context['enum']=self.request.path[20:-6].split('/')[0] context['id']=self.request.path[20:-6].split('/')[1] context['count'] = self.object_list.count() context['enum_name'] = CollectionEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name context['enum_value'] = CollectionEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4]) return context def get_queryset(self): enumeration = self.get_enumeration(self.request.path[20:-6].split('/')[0]) queryset= self.get_coll(enumeration.objects.filter(id=self.request.path[20:-6].split('/')[1]).get()) return queryset def get_coll(self, enum): f = MediaCollection._meta.get_all_field_names() for field in f: if field in enum._meta.db_table.replace(" ", "_"): atr = field; atr = atr lookup = "%s__exact" % atr return MediaCollection.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 CollectionPublishedEnumListView(CollectionEnumListView): def get_queryset(self): c = CollectionEnumListView() #id of value of enumeration i= self.request.path.split('/')[4] enumeration = c.get_enumeration(self.request.path.split('/')[3]) queryset = self.get_coll(enumeration.objects.filter(id=i).get(), c) return queryset def get_coll(self, enum,c): return c.get_coll(enum).filter(code__contains='_E_') class CollectionUnpublishedEnumListView(CollectionEnumListView): def get_queryset(self): c = CollectionEnumListView() #id of value of enumeration i= self.request.path.split('/')[4] enumeration = c.get_enumeration( self.request.path.split('/')[3]) queryset = self.get_coll(enumeration.objects.filter(id=i).get(), c) return queryset def get_coll(self, enum, c): return c.get_coll(enum).filter(code__contains='_I_') class CollectionSoundEnumListView(CollectionEnumListView): def get_queryset(self): c = CollectionEnumListView() #id of value of enumeration i= self.request.path.split('/')[4] enumeration = c.get_enumeration( self.request.path.split('/')[3]) queryset = self.get_coll(enumeration.objects.filter(id=i).get(), c) return queryset def get_coll(self, enum,c): return c.get_coll(enum).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 CollectionAddView
class CollectionAddView(CollectionViewMixin, CreateWithInlinesView): template_name = 'telemeta/collection_add.html' inlines = [CollectionRelatedInline, CollectionIdentifierInline] def forms_valid(self, form, inlines): messages.info(self.request, ugettext_lazy("You have successfully added your collection.")) obj = form.save() obj.set_revision(self.request.user) return super(CollectionAddView, self).forms_valid(form, inlines) def get_success_url(self): return reverse_lazy('telemeta-collection-detail', kwargs={'public_id': self.object.code}) @method_decorator(permission_required('telemeta.add_mediacollection')) def dispatch(self, *args, **kwargs): return super(CollectionAddView, self).dispatch(*args, **kwargs)
Ancestors (in MRO)
- CollectionAddView
- CollectionViewMixin
- 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 content_type
var context_object_name
var fields
var http_method_names
var initial
var inlines
var pk_url_kwarg
var prefix
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
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 collection.")) obj = form.save() obj.set_revision(self.request.user) return super(CollectionAddView, 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_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_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_object(
self)
Inheritance:
CollectionViewMixin
.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-collection-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 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 CollectionCopyView
class CollectionCopyView(CollectionAddView): template_name = 'telemeta/collection_edit.html' def get_initial(self): return model_to_dict(self.get_object()) def get_context_data(self, **kwargs): context = super(CollectionCopyView, self).get_context_data(**kwargs) collection = self.get_object() context['collection'] = collection return context @method_decorator(permission_required('telemeta.add_mediacollection')) def dispatch(self, *args, **kwargs): return super(CollectionCopyView, self).dispatch(*args, **kwargs)
Ancestors (in MRO)
- CollectionCopyView
- CollectionAddView
- CollectionViewMixin
- 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
Methods
def __init__(
self, **kwargs)
Inheritance:
CollectionAddView
.__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:
CollectionAddView
.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:
CollectionAddView
.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:
CollectionAddView
.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:
CollectionAddView
.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:
CollectionAddView
.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:
CollectionAddView
.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:
CollectionAddView
.forms_valid
def forms_valid(self, form, inlines): messages.info(self.request, ugettext_lazy("You have successfully added your collection.")) obj = form.save() obj.set_revision(self.request.user) return super(CollectionAddView, self).forms_valid(form, inlines)
def get(
self, request, *args, **kwargs)
Inheritance:
CollectionAddView
.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:
CollectionAddView
.get_context_data
Insert the single object into the context dict.
def get_context_data(self, **kwargs): context = super(CollectionCopyView, self).get_context_data(**kwargs) collection = self.get_object() context['collection'] = collection return context
def get_context_object_name(
self, obj)
Inheritance:
CollectionAddView
.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_form(
self, form_class)
Inheritance:
CollectionAddView
.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:
CollectionAddView
.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:
CollectionAddView
.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_initial(
self)
Inheritance:
CollectionAddView
.get_initial
Returns the initial data to use for forms on this view.
def get_initial(self): return model_to_dict(self.get_object())
def get_inlines(
self)
Inheritance:
CollectionAddView
.get_inlines
Returns the inline formset classes
def get_inlines(self): """ Returns the inline formset classes """ return self.inlines
def get_object(
self)
Inheritance:
CollectionAddView
.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:
CollectionAddView
.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:
CollectionAddView
.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:
CollectionAddView
.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:
CollectionAddView
.get_success_url
def get_success_url(self): return reverse_lazy('telemeta-collection-detail', kwargs={'public_id': self.object.code})
def get_template_names(
self)
Inheritance:
CollectionAddView
.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:
CollectionAddView
.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:
CollectionAddView
.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:
CollectionAddView
.post
def post(self, request, *args, **kwargs): self.object = None return super(BaseCreateWithInlinesView, self).post(request, *args, **kwargs)
def put(
self, *args, **kwargs)
Inheritance:
CollectionAddView
.put
def put(self, *args, **kwargs): return self.post(*args, **kwargs)
def render_to_response(
self, context, **response_kwargs)
Inheritance:
CollectionAddView
.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 CollectionDetailView
class CollectionDetailView(CollectionViewMixin, DetailView): template_name = 'telemeta/collection_detail.html' def get_context_data(self, **kwargs): context = super(CollectionDetailView, self).get_context_data(**kwargs) collection = self.get_object() items = collection.items.enriched() context['collection'] = collection context['items'] = items.order_by('code', 'old_code') context['playlists'] = get_playlists_names(self.request) context['related_media'] = MediaCollectionRelated.objects.filter(collection=collection) check_related_media(context['related_media']) context['parents'] = MediaCorpus.objects.filter(children=collection) revisions = Revision.objects.filter(element_type='collection', element_id=collection.id) if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None return context
Ancestors (in MRO)
- CollectionDetailView
- CollectionViewMixin
- 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 content_type
var context_object_name
var http_method_names
var pk_url_kwarg
var queryset
var response_class
var slug_field
var slug_url_kwarg
var template_name
var template_name_field
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 = 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(CollectionDetailView, self).get_context_data(**kwargs) collection = self.get_object() items = collection.items.enriched() context['collection'] = collection context['items'] = items.order_by('code', 'old_code') context['playlists'] = get_playlists_names(self.request) context['related_media'] = MediaCollectionRelated.objects.filter(collection=collection) check_related_media(context['related_media']) context['parents'] = MediaCorpus.objects.filter(children=collection) revisions = Revision.objects.filter(element_type='collection', element_id=collection.id) if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = 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_object(
self)
Inheritance:
CollectionViewMixin
.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 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 CollectionDetailViewDC
class CollectionDetailViewDC(CollectionDetailView): template_name = "telemeta/collection_detail_dc.html"
Ancestors (in MRO)
- CollectionDetailViewDC
- CollectionDetailView
- CollectionViewMixin
- 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
Methods
def __init__(
self, **kwargs)
Inheritance:
CollectionDetailView
.__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:
CollectionDetailView
.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:
CollectionDetailView
.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:
CollectionDetailView
.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:
CollectionDetailView
.get_context_data
def get_context_data(self, **kwargs): context = super(CollectionDetailView, self).get_context_data(**kwargs) collection = self.get_object() items = collection.items.enriched() context['collection'] = collection context['items'] = items.order_by('code', 'old_code') context['playlists'] = get_playlists_names(self.request) context['related_media'] = MediaCollectionRelated.objects.filter(collection=collection) check_related_media(context['related_media']) context['parents'] = MediaCorpus.objects.filter(children=collection) revisions = Revision.objects.filter(element_type='collection', element_id=collection.id) if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None return context
def get_context_object_name(
self, obj)
Inheritance:
CollectionDetailView
.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_object(
self)
Inheritance:
CollectionDetailView
.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:
CollectionDetailView
.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:
CollectionDetailView
.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:
CollectionDetailView
.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:
CollectionDetailView
.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:
CollectionDetailView
.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:
CollectionDetailView
.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 CollectionEditView
class CollectionEditView(CollectionViewMixin, UpdateWithInlinesView): template_name = 'telemeta/collection_edit.html' inlines = [CollectionRelatedInline, CollectionIdentifierInline] def forms_valid(self, form, inlines): messages.info(self.request, ugettext_lazy("You have successfully updated your collection.")) obj = form.save() obj.set_revision(self.request.user) self.code = obj.code return super(CollectionEditView, self).forms_valid(form, inlines) def get_success_url(self): return reverse_lazy('telemeta-collection-detail', kwargs={'public_id': self.code}) def get_context_data(self, **kwargs): context = super(CollectionEditView, self).get_context_data(**kwargs) collection = self.get_object() context['collection'] = collection return context @method_decorator(permission_required('telemeta.change_mediacollection')) def dispatch(self, *args, **kwargs): return super(CollectionEditView, self).dispatch(*args, **kwargs)
Ancestors (in MRO)
- CollectionEditView
- CollectionViewMixin
- 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 content_type
var context_object_name
var fields
var http_method_names
var initial
var inlines
var pk_url_kwarg
var prefix
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
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 collection.")) obj = form.save() obj.set_revision(self.request.user) self.code = obj.code return super(CollectionEditView, 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(CollectionEditView, self).get_context_data(**kwargs) collection = self.get_object() context['collection'] = collection 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_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_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_object(
self)
Inheritance:
CollectionViewMixin
.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-collection-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 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 CollectionEnumListView
class CollectionEnumListView(CollectionListView): template_name = "telemeta/collection_enum_list.html" def get_context_data(self, **kwargs): context = super(CollectionListView, self).get_context_data(**kwargs) context['enum']=self.request.path[20:-6].split('/')[0] context['id']=self.request.path[20:-6].split('/')[1] context['count'] = self.object_list.count() context['enum_name'] = CollectionEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name context['enum_value'] = CollectionEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4]) return context def get_queryset(self): enumeration = self.get_enumeration(self.request.path[20:-6].split('/')[0]) queryset= self.get_coll(enumeration.objects.filter(id=self.request.path[20:-6].split('/')[1]).get()) return queryset def get_coll(self, enum): f = MediaCollection._meta.get_all_field_names() for field in f: if field in enum._meta.db_table.replace(" ", "_"): atr = field; atr = atr lookup = "%s__exact" % atr return MediaCollection.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)
- CollectionEnumListView
- CollectionListView
- 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
Methods
def __init__(
self, **kwargs)
Inheritance:
CollectionListView
.__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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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_coll(
self, enum)
def get_coll(self, enum): f = MediaCollection._meta.get_all_field_names() for field in f: if field in enum._meta.db_table.replace(" ", "_"): atr = field; atr = atr lookup = "%s__exact" % atr return MediaCollection.objects.filter(**{lookup: enum.__getattribute__("id")})
def get_context_data(
self, **kwargs)
Inheritance:
CollectionListView
.get_context_data
def get_context_data(self, **kwargs): context = super(CollectionListView, self).get_context_data(**kwargs) context['enum']=self.request.path[20:-6].split('/')[0] context['id']=self.request.path[20:-6].split('/')[1] context['count'] = self.object_list.count() context['enum_name'] = CollectionEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name context['enum_value'] = CollectionEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4]) return context
def get_context_object_name(
self, object_list)
Inheritance:
CollectionListView
.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_paginate_by(
self, queryset)
Inheritance:
CollectionListView
.get_paginate_by
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)
Inheritance:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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[20:-6].split('/')[0]) queryset= self.get_coll(enumeration.objects.filter(id=self.request.path[20:-6].split('/')[1]).get()) return queryset
def get_template_names(
self)
Inheritance:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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 CollectionEpubView
Download collection data embedded in an EPUB3 file
class CollectionEpubView(BaseEpubMixin, View): "Download collection data embedded in an EPUB3 file" model = MediaCollection def get_object(self): return MediaCollection.objects.get(public_id=self.kwargs['public_id']) def get(self, request, *args, **kwargs): collection = self.get_object() corpus = collection.corpus.all()[0] self.setup_epub(corpus, collection=collection) if not os.path.exists(self.path): self.write_book() epub_file = open(self.path, 'rb') response = HttpResponse(epub_file.read(), content_type='application/epub+zip') response['Content-Disposition'] = "attachment; filename=%s" % self.filename + '.epub' return response # @method_decorator(login_required) # @method_decorator(permission_required('telemeta.can_download_collection_epub')) def dispatch(self, *args, **kwargs): return super(CollectionEpubView, self).dispatch(*args, **kwargs)
Ancestors (in MRO)
- CollectionEpubView
- telemeta.views.epub.BaseEpubMixin
- telemeta.views.core.TelemetaBaseMixin
- django.views.generic.base.View
- __builtin__.object
Class variables
var CACHE_DIR
var MEDIA_ROOT
var cache_data
var cache_export
var cache_tmp
var css
var default_image
var default_image_end
var http_method_names
var local_path
var model
var template
var template_cover
var template_preamble
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, *args, **kwargs)
def dispatch(self, *args, **kwargs): return super(CollectionEpubView, self).dispatch(*args, **kwargs)
def get(
self, request, *args, **kwargs)
def get(self, request, *args, **kwargs): collection = self.get_object() corpus = collection.corpus.all()[0] self.setup_epub(corpus, collection=collection) if not os.path.exists(self.path): self.write_book() epub_file = open(self.path, 'rb') response = HttpResponse(epub_file.read(), content_type='application/epub+zip') response['Content-Disposition'] = "attachment; filename=%s" % self.filename + '.epub' return response
def get_object(
self)
def get_object(self): return MediaCollection.objects.get(public_id=self.kwargs['public_id'])
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 setup_epub(
self, corpus, collection=None, path=None)
def setup_epub(self, corpus, collection=None, path=None): self.book = epub.EpubBook() self.corpus = corpus self.collection = collection self.site = Site.objects.get_current() self.chapters = [] self.default_image_added = False if not collection: self.filename = corpus.code self.book.set_title(corpus.title) self.full_title = corpus.title else: self.filename = collection.code short_title = collection.title.split(' ') if not ' 0' in collection.title: short_title = short_title[0][:4] + ' ' + short_title[1] else: short_title = 'Intro' self.book.set_title(corpus.title[:15] + '... ' + short_title) self.full_title = corpus.title + ' - ' + collection.title self.path = self.cache_data.dir + os.sep + self.filename + '.epub' return self.path
def write_book(
self)
def write_book(self): # add metadata self.book.set_identifier(self.corpus.public_id) self.book.set_language('fr') self.book.add_author(self.corpus.descriptions) # add css style style = open(self.css, 'r') css = epub.EpubItem(uid="style_nav", file_name="style/epub.css", media_type="text/css", content=style.read()) self.book.add_item(css) if self.collection: self.collections = [self.collection] mode_single = True instance = self.collection if ' 0' in self.collection.title: chap_num = "d'introduction" else: chap_num = self.collection.code.split('_')[-1] context = {'title': 'chapitre ' + chap_num, 'mode_single': mode_single} else: self.collections = self.corpus.children.all() mode_single = False instance = self.corpus context = {'title': '', 'mode_single': mode_single} # add cover image for media in instance.related.all(): self.cover_filename = os.path.split(media.file.path)[-1] self.book.set_cover(self.cover_filename, open(media.file.path, 'rb').read()) break preamble = epub.EpubHtml(title='Copyright', file_name='copyright' + '.xhtml', lang='fr') preamble.content = render_to_string(self.template_preamble, context) preamble.is_chapter = True self.default_image_added = False default_image_relative_path = '' self.book.add_item(preamble) self.chapters.append(preamble) image = open(self.default_image_end, 'r') default_image_end_relative_path = 'images' + os.sep + os.path.split(self.default_image_end)[-1] epub_last_image = epub.EpubItem(file_name=default_image_end_relative_path, content=image.read()) self.book.add_item(epub_last_image) i = 1 for collection in self.collections: items = {} for item in collection.items.all(): if '.' in item.old_code: id = item.old_code.split('.')[1] else: id = item.old_code for c in id: if c.isalpha(): id = id.replace(c, '.' + str(ord(c) - 96)) items[item] = float(id) items = OrderedDict(sorted(items.items(), key=lambda t: t[1])) for item in items: if item.file: audio = open(item.file.path, 'r') filename = str(item.file) epub_item = epub.EpubItem(file_name=str(item.file), content=audio.read()) self.book.add_item(epub_item) related_all = item.related.all() if related_all: for related in related_all: if 'image' in related.mime_type: image = open(related.file.path, 'r') epub_item = epub.EpubItem(file_name=str(related.file), content=image.read()) self.book.add_item(epub_item) elif not self.default_image_added: image = open(self.default_image, 'r') default_image_relative_path = 'images' + os.sep + os.path.split(self.default_image)[-1] epub_item = epub.EpubItem(file_name=default_image_relative_path, content=image.read()) self.book.add_item(epub_item) self.default_image_added = True title_split = collection.title.split(' - ') if len(title_split) > 1: if ' 0' in title_split[0]: title = '' subtitle = title_split[1] chapter_title = subtitle else: title = title_split[0] subtitle = title_split[1] chapter_title = ' - '.join([title, subtitle]) else: title = collection.title subtitle = '' chapter_title = title last_collection = False if i == len(self.collections): last_collection = True context = {'collection': collection, 'title': title, 'subtitle': subtitle, 'mode_single': mode_single, 'site': self.site, 'items': items, 'default_image': default_image_relative_path, 'default_image_end': default_image_end_relative_path, 'last_collection': last_collection} c = epub.EpubHtml(title=chapter_title, file_name=collection.code + '.xhtml', lang='fr') c.content = render_to_string(self.template, context) self.book.add_item(c) self.chapters.append(c) i += 1 # create table of contents # - add manual link # - add section # - add auto created links to chapters self.book.toc = ((self.chapters)) self.book.spine = self.chapters # add navigation files ncx = epub.EpubNcx() self.book.add_item(ncx) nav = epub.EpubNav() self.book.add_item(nav) if not mode_single: self.book.spine.insert(0, 'nav') # create spin, add cover page as first page cover = epub.EpubHtml(title=self.full_title, file_name='cover-bis' + '.xhtml') cover.content = render_to_string(self.template_cover, {'image': self.cover_filename}) self.book.add_item(cover) self.book.spine.insert(0, cover) # self.book.guide.insert(0, { # "type" : "cover", # "href" : cover.file_name, # "title" : cover.title, # }) # write epub file epub.write_epub(self.path, self.book, {})
class CollectionListView
class CollectionListView(ListView): model = MediaCollection template_name = "telemeta/collection_list.html" paginate_by = 20 queryset = MediaCollection.objects.enriched() def get_context_data(self, **kwargs): context = super(CollectionListView, self).get_context_data(**kwargs) context['count'] = self.object_list.count() return context
Ancestors (in MRO)
- CollectionListView
- 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(CollectionListView, 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 CollectionPublishedEnumListView
class CollectionPublishedEnumListView(CollectionEnumListView): def get_queryset(self): c = CollectionEnumListView() #id of value of enumeration i= self.request.path.split('/')[4] enumeration = c.get_enumeration(self.request.path.split('/')[3]) queryset = self.get_coll(enumeration.objects.filter(id=i).get(), c) return queryset def get_coll(self, enum,c): return c.get_coll(enum).filter(code__contains='_E_')
Ancestors (in MRO)
- CollectionPublishedEnumListView
- CollectionEnumListView
- CollectionListView
- 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
Methods
def __init__(
self, **kwargs)
Inheritance:
CollectionEnumListView
.__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:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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_coll(
self, enum, c)
Inheritance:
CollectionEnumListView
.get_coll
def get_coll(self, enum,c): return c.get_coll(enum).filter(code__contains='_E_')
def get_context_data(
self, **kwargs)
Inheritance:
CollectionEnumListView
.get_context_data
def get_context_data(self, **kwargs): context = super(CollectionListView, self).get_context_data(**kwargs) context['enum']=self.request.path[20:-6].split('/')[0] context['id']=self.request.path[20:-6].split('/')[1] context['count'] = self.object_list.count() context['enum_name'] = CollectionEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name context['enum_value'] = CollectionEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4]) return context
def get_context_object_name(
self, object_list)
Inheritance:
CollectionEnumListView
.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:
CollectionEnumListView
.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_paginate_by(
self, queryset)
Inheritance:
CollectionEnumListView
.get_paginate_by
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)
Inheritance:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.get_queryset
def get_queryset(self): c = CollectionEnumListView() #id of value of enumeration i= self.request.path.split('/')[4] enumeration = c.get_enumeration(self.request.path.split('/')[3]) queryset = self.get_coll(enumeration.objects.filter(id=i).get(), c) return queryset
def get_template_names(
self)
Inheritance:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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 CollectionPublishedListView
class CollectionPublishedListView(CollectionListView): queryset = MediaCollection.objects.filter(code__contains='_E_')
Ancestors (in MRO)
- CollectionPublishedListView
- CollectionListView
- 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
Methods
def __init__(
self, **kwargs)
Inheritance:
CollectionListView
.__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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.get_context_data
def get_context_data(self, **kwargs): context = super(CollectionListView, self).get_context_data(**kwargs) context['count'] = self.object_list.count() return context
def get_context_object_name(
self, object_list)
Inheritance:
CollectionListView
.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:
CollectionListView
.get_paginate_by
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)
Inheritance:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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 CollectionSoundEnumListView
class CollectionSoundEnumListView(CollectionEnumListView): def get_queryset(self): c = CollectionEnumListView() #id of value of enumeration i= self.request.path.split('/')[4] enumeration = c.get_enumeration( self.request.path.split('/')[3]) queryset = self.get_coll(enumeration.objects.filter(id=i).get(), c) return queryset def get_coll(self, enum,c): return c.get_coll(enum).sound().order_by('code', 'old_code')
Ancestors (in MRO)
- CollectionSoundEnumListView
- CollectionEnumListView
- CollectionListView
- 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
Methods
def __init__(
self, **kwargs)
Inheritance:
CollectionEnumListView
.__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:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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_coll(
self, enum, c)
Inheritance:
CollectionEnumListView
.get_coll
def get_coll(self, enum,c): return c.get_coll(enum).sound().order_by('code', 'old_code')
def get_context_data(
self, **kwargs)
Inheritance:
CollectionEnumListView
.get_context_data
def get_context_data(self, **kwargs): context = super(CollectionListView, self).get_context_data(**kwargs) context['enum']=self.request.path[20:-6].split('/')[0] context['id']=self.request.path[20:-6].split('/')[1] context['count'] = self.object_list.count() context['enum_name'] = CollectionEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name context['enum_value'] = CollectionEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4]) return context
def get_context_object_name(
self, object_list)
Inheritance:
CollectionEnumListView
.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:
CollectionEnumListView
.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_paginate_by(
self, queryset)
Inheritance:
CollectionEnumListView
.get_paginate_by
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)
Inheritance:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.get_queryset
def get_queryset(self): c = CollectionEnumListView() #id of value of enumeration i= self.request.path.split('/')[4] enumeration = c.get_enumeration( self.request.path.split('/')[3]) queryset = self.get_coll(enumeration.objects.filter(id=i).get(), c) return queryset
def get_template_names(
self)
Inheritance:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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 CollectionSoundListView
class CollectionSoundListView(CollectionListView): queryset = MediaCollection.objects.sound().order_by('code', 'old_code')
Ancestors (in MRO)
- CollectionSoundListView
- CollectionListView
- 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
Methods
def __init__(
self, **kwargs)
Inheritance:
CollectionListView
.__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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.get_context_data
def get_context_data(self, **kwargs): context = super(CollectionListView, self).get_context_data(**kwargs) context['count'] = self.object_list.count() return context
def get_context_object_name(
self, object_list)
Inheritance:
CollectionListView
.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:
CollectionListView
.get_paginate_by
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)
Inheritance:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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 CollectionUnpublishedEnumListView
class CollectionUnpublishedEnumListView(CollectionEnumListView): def get_queryset(self): c = CollectionEnumListView() #id of value of enumeration i= self.request.path.split('/')[4] enumeration = c.get_enumeration( self.request.path.split('/')[3]) queryset = self.get_coll(enumeration.objects.filter(id=i).get(), c) return queryset def get_coll(self, enum, c): return c.get_coll(enum).filter(code__contains='_I_')
Ancestors (in MRO)
- CollectionUnpublishedEnumListView
- CollectionEnumListView
- CollectionListView
- 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
Methods
def __init__(
self, **kwargs)
Inheritance:
CollectionEnumListView
.__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:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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_coll(
self, enum, c)
Inheritance:
CollectionEnumListView
.get_coll
def get_coll(self, enum, c): return c.get_coll(enum).filter(code__contains='_I_')
def get_context_data(
self, **kwargs)
Inheritance:
CollectionEnumListView
.get_context_data
def get_context_data(self, **kwargs): context = super(CollectionListView, self).get_context_data(**kwargs) context['enum']=self.request.path[20:-6].split('/')[0] context['id']=self.request.path[20:-6].split('/')[1] context['count'] = self.object_list.count() context['enum_name'] = CollectionEnumListView().get_enumeration(self.request.path.split('/')[3])._meta.verbose_name context['enum_value'] = CollectionEnumListView().get_enumeration(self.request.path.split('/')[3]).objects.get(id__exact=self.request.path.split('/')[4]) return context
def get_context_object_name(
self, object_list)
Inheritance:
CollectionEnumListView
.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:
CollectionEnumListView
.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_paginate_by(
self, queryset)
Inheritance:
CollectionEnumListView
.get_paginate_by
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)
Inheritance:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.get_queryset
def get_queryset(self): c = CollectionEnumListView() #id of value of enumeration i= self.request.path.split('/')[4] enumeration = c.get_enumeration( self.request.path.split('/')[3]) queryset = self.get_coll(enumeration.objects.filter(id=i).get(), c) return queryset
def get_template_names(
self)
Inheritance:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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:
CollectionEnumListView
.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 CollectionUnpublishedListView
class CollectionUnpublishedListView(CollectionListView): queryset = MediaCollection.objects.filter(code__contains='_I_')
Ancestors (in MRO)
- CollectionUnpublishedListView
- CollectionListView
- 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
Methods
def __init__(
self, **kwargs)
Inheritance:
CollectionListView
.__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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.get_context_data
def get_context_data(self, **kwargs): context = super(CollectionListView, self).get_context_data(**kwargs) context['count'] = self.object_list.count() return context
def get_context_object_name(
self, object_list)
Inheritance:
CollectionListView
.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:
CollectionListView
.get_paginate_by
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)
Inheritance:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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:
CollectionListView
.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 CollectionView
Provide Collections web UI methods
class CollectionView(object): """Provide Collections web UI methods""" def collection_detail(self, request, public_id, template='telemeta/collection_detail.html'): collection = MediaCollection.objects.get(public_id=public_id) items = collection.items.enriched() items = items.order_by('code', 'old_code') if collection.public_access == 'none' and not (request.user.is_staff or request.user.is_superuser): mess = ugettext('Access not allowed') title = ugettext('Collection') + ' : ' + 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}) playlists = get_playlists_names(request) related_media = MediaCollectionRelated.objects.filter(collection=collection) check_related_media(related_media) parents = MediaCorpus.objects.filter(children=collection) revisions = Revision.objects.filter(element_type='collection', element_id=collection.id).order_by('-time') if revisions: last_revision = revisions[0] else: last_revision = None return render(request, template, {'collection': collection, 'playlists': playlists, 'items': items, 'related_media': related_media, 'parents': parents, 'last_revision': last_revision}) @method_decorator(permission_required('telemeta.change_mediacollection')) def collection_edit(self, request, public_id, template='telemeta/collection_edit.html'): collection = MediaCollection.objects.get(public_id=public_id) if request.method == 'POST': form = MediaCollectionForm(data=request.POST, files=request.FILES, instance=collection) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id form.save() collection.set_revision(request.user) return redirect('telemeta-collection-detail', code) else: form = MediaCollectionForm(instance=collection) return render(request, template, {'collection': collection, "form": form, }) @method_decorator(permission_required('telemeta.add_mediacollection')) def collection_add(self, request, template='telemeta/collection_add.html'): collection = MediaCollection() if request.method == 'POST': form = MediaCollectionForm(data=request.POST, files=request.FILES, instance=collection) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id form.save() collection.set_revision(request.user) return redirect('telemeta-collection-detail', code) else: form = MediaCollectionForm(instance=collection) return render(request, template, {'collection': collection, "form": form, }) @method_decorator(permission_required('telemeta.add_mediacollection')) def collection_copy(self, request, public_id, template='telemeta/collection_edit.html'): if request.method == 'POST': collection = MediaCollection() form = MediaCollectionForm(data=request.POST, files=request.FILES, instance=collection) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id form.save() collection.set_revision(request.user) return redirect('telemeta-collection-detail', code) else: collection = MediaCollection.objects.get(public_id=public_id) form = MediaCollectionForm(instance=collection) return render(request, template, {'collection': collection, "form": form, }) def collection_playlist(self, request, public_id, template, mimetype): try: collection = MediaCollection.objects.get(public_id=public_id) except ObjectDoesNotExist: raise Http404 template = loader.get_template(template) context = RequestContext(request, {'collection': collection, 'host': request.META['HTTP_HOST']}) return HttpResponse(template.render(context), content_type=mimetype) @method_decorator(permission_required('telemeta.delete_mediacollection')) def collection_delete(self, request, public_id): """Delete a given collection""" collection = MediaCollection.objects.get(public_id=public_id) revisions = Revision.objects.filter(element_type='collection', element_id=collection.id) for revision in revisions: revision.delete() collection.delete() return redirect('telemeta-collections') def related_media_collection_stream(self, request, public_id, media_id): collection = MediaCollection.objects.get(public_id=public_id) media = MediaCollectionRelated.objects.get(collection=collection, id=media_id) response = serve_media(media.file.path, content_type=media.mime_type) return response def related_media_collection_download(self, request, public_id, media_id): collection = MediaCollection.objects.get(public_id=public_id) media = MediaCollectionRelated.objects.get(collection=collection, id=media_id) response = serve_media(media.file.path, content_type=media.mime_type) return response @method_decorator(permission_required('telemeta.change_mediacollection')) def related_media_edit(self, request, public_id, template): collection = MediaCollection.objects.get(public_id=public_id) MediaCollectionRelatedFormSet = inlineformset_factory(MediaCollection, MediaCollectionRelated, form=MediaCollectionRelatedForm) if request.method == 'POST': formset = MediaCollectionRelatedFormSet(data=request.POST, files=request.FILES, instance=collection) if formset.is_valid(): formset.save() collection.set_revision(request.user) return redirect('telemeta-collection-edit', public_id) else: formset = MediaCollectionRelatedFormSet(instance=collection) return render(request, template, {'collection': collection, 'formset': formset, })
Ancestors (in MRO)
- CollectionView
- __builtin__.object
Methods
def collection_add(
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 collection_copy(
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 collection_delete(
self, *args, **kwargs)
Delete a given collection
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 collection_detail(
self, request, public_id, template='telemeta/collection_detail.html')
def collection_detail(self, request, public_id, template='telemeta/collection_detail.html'): collection = MediaCollection.objects.get(public_id=public_id) items = collection.items.enriched() items = items.order_by('code', 'old_code') if collection.public_access == 'none' and not (request.user.is_staff or request.user.is_superuser): mess = ugettext('Access not allowed') title = ugettext('Collection') + ' : ' + 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}) playlists = get_playlists_names(request) related_media = MediaCollectionRelated.objects.filter(collection=collection) check_related_media(related_media) parents = MediaCorpus.objects.filter(children=collection) revisions = Revision.objects.filter(element_type='collection', element_id=collection.id).order_by('-time') if revisions: last_revision = revisions[0] else: last_revision = None return render(request, template, {'collection': collection, 'playlists': playlists, 'items': items, 'related_media': related_media, 'parents': parents, 'last_revision': last_revision})
def collection_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 collection_playlist(
self, request, public_id, template, mimetype)
def collection_playlist(self, request, public_id, template, mimetype): try: collection = MediaCollection.objects.get(public_id=public_id) except ObjectDoesNotExist: raise Http404 template = loader.get_template(template) context = RequestContext(request, {'collection': collection, 'host': request.META['HTTP_HOST']}) return HttpResponse(template.render(context), content_type=mimetype)
class CollectionViewMixin
class CollectionViewMixin(object): model = MediaCollection form_class = MediaCollectionForm 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)
- CollectionViewMixin
- __builtin__.object
Class variables
var form_class
var model
Methods
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
class CollectionZipView
class CollectionZipView(View): model = MediaCollection def get_object(self): return MediaCollection.objects.get(public_id=self.kwargs['public_id']) def get(self, request, *args, **kwargs): """ Stream a ZIP file of collection data without loading the whole file into memory. Based on ZipStream """ from telemeta.views import MarkerView from telemeta.backup import CollectionSerializer import zipstream from zipfile import ZIP_DEFLATED, ZIP_STORED import json zip_file = zipstream.ZipFile(mode='w', compression=ZIP_STORED, allowZip64=True) cache_data = TelemetaCache(settings.TELEMETA_DATA_CACHE_DIR) collection = self.get_object() serializer = CollectionSerializer(collection) data = collection.get_json().encode('utf-8') filename = collection.public_id + '.json' cache_data.write_bin(data, filename) path = cache_data.dir + os.sep + filename zip_file.write(path, arcname=collection.public_id + os.sep + filename) data = serializer.get_xml().encode('utf-8') filename = collection.public_id + '.xml' cache_data.write_bin(data, filename) path = cache_data.dir + os.sep + filename zip_file.write(path, arcname=collection.public_id + os.sep + filename) for item in collection.items.all(): if item.file: filename, ext = os.path.splitext(item.file.path.split(os.sep)[-1]) zip_file.write(item.file.path, arcname=collection.public_id + os.sep + item.code + ext) marker_view = MarkerView() markers = marker_view.get_markers(item.id) if markers: data = json.dumps(markers) filename = item.code + '.json' cache_data.write_bin(data, filename) path = cache_data.dir + os.sep + filename zip_file.write(path, arcname=collection.public_id + os.sep + filename) response = StreamingHttpResponse(zip_file, content_type='application/zip') response['Content-Disposition'] = "attachment; filename=%s.%s" % \ (collection.code, 'zip') return response @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(CollectionZipView, self).dispatch(*args, **kwargs)
Ancestors (in MRO)
- CollectionZipView
- django.views.generic.base.View
- __builtin__.object
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, *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 get(
self, request, *args, **kwargs)
Stream a ZIP file of collection data without loading the whole file into memory. Based on ZipStream
def get(self, request, *args, **kwargs): """ Stream a ZIP file of collection data without loading the whole file into memory. Based on ZipStream """ from telemeta.views import MarkerView from telemeta.backup import CollectionSerializer import zipstream from zipfile import ZIP_DEFLATED, ZIP_STORED import json zip_file = zipstream.ZipFile(mode='w', compression=ZIP_STORED, allowZip64=True) cache_data = TelemetaCache(settings.TELEMETA_DATA_CACHE_DIR) collection = self.get_object() serializer = CollectionSerializer(collection) data = collection.get_json().encode('utf-8') filename = collection.public_id + '.json' cache_data.write_bin(data, filename) path = cache_data.dir + os.sep + filename zip_file.write(path, arcname=collection.public_id + os.sep + filename) data = serializer.get_xml().encode('utf-8') filename = collection.public_id + '.xml' cache_data.write_bin(data, filename) path = cache_data.dir + os.sep + filename zip_file.write(path, arcname=collection.public_id + os.sep + filename) for item in collection.items.all(): if item.file: filename, ext = os.path.splitext(item.file.path.split(os.sep)[-1]) zip_file.write(item.file.path, arcname=collection.public_id + os.sep + item.code + ext) marker_view = MarkerView() markers = marker_view.get_markers(item.id) if markers: data = json.dumps(markers) filename = item.code + '.json' cache_data.write_bin(data, filename) path = cache_data.dir + os.sep + filename zip_file.write(path, arcname=collection.public_id + os.sep + filename) response = StreamingHttpResponse(zip_file, content_type='application/zip') response['Content-Disposition'] = "attachment; filename=%s.%s" % \ (collection.code, 'zip') return response
def get_object(
self)
def get_object(self): return MediaCollection.objects.get(public_id=self.kwargs['public_id'])
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