telemeta.views.resource 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> from telemeta.views.core import * from telemeta.views.core import serve_media from telemeta.views.epub import BaseEpubMixin from django.utils.translation import ugettext_lazy as _ class ResourceView(object): """Provide Resource web UI methods""" types = {'corpus': {'model': MediaCorpus, 'form': MediaCorpusForm, 'related': MediaCorpusRelated, 'parent': MediaFonds, }, 'fonds': {'model': MediaFonds, 'form': MediaFondsForm, 'related': MediaFondsRelated, 'parent': None, } } def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.type = type def detail(self, request, type, public_id, template='telemeta/resource_detail.html'): self.setup(type) resource = self.model.objects.get(code=public_id) children = resource.children.all() children = children.order_by('code') related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists(request) revisions = Revision.objects.filter(element_type=type, element_id=resource.id).order_by('-time') if revisions: last_revision = revisions[0] else: last_revision = None if self.parent: parents = self.parent.objects.filter(children=resource) else: parents = [] return render(request, template, {'resource': resource, 'type': type, 'children': children, 'related_media': related_media, 'parents': parents, 'playlists': playlists, 'last_revision': last_revision}) def edit(self, request, type, public_id, template='telemeta/resource_edit.html'): self.setup(type) resource = self.model.objects.get(code=public_id) if request.method == 'POST': form = self.form(data=request.POST, files=request.FILES, instance=resource) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id form.save() resource.set_revision(request.user) return redirect('telemeta-resource-detail', self.type, code) else: form = self.form(instance=resource) return render(request, template, {'resource': resource, 'type': type, 'form': form, }) def add(self, request, type, template='telemeta/resource_add.html'): self.setup(type) resource = self.model() if request.method == 'POST': form = self.form(data=request.POST, files=request.FILES, instance=resource) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id form.save() resource.set_revision(request.user) return redirect('telemeta-resource-detail', self.type, code) else: form = self.form(instance=resource) return render(request, template, {'resource': resource, 'type': type, 'form': form, }) def copy(self, request, type, public_id, template='telemeta/resource_edit.html'): self.setup(type) if request.method == 'POST': resource = self.model() form = self.form(data=request.POST, files=request.FILES, instance=resource) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id resource.save() resource.set_revision(request.user) return redirect('telemeta-resource-detail', self.type, code) else: resource = self.model.objects.get(code=public_id) form = self.form(instance=resource) return render(request, template, {'resource': resource, 'type': type, "form": form, }) def playlist(self, request, type, public_id, template, mimetype): self.setup(type) try: resource = self.model.objects.get(code=public_id) except ObjectDoesNotExist: raise Http404 template = loader.get_template(template) context = RequestContext(request, {'resource': resource, 'host': request.META['HTTP_HOST']}) return HttpResponse(template.render(context), content_type=mimetype) def delete(self, request, type, public_id): self.setup(type) resource = self.model.objects.get(code=public_id) revisions = Revision.objects.filter(element_type='resource', element_id=resource.id) for revision in revisions: revision.delete() resource.delete() return HttpResponseRedirect('/archives/' + self.type + '/') def related_stream(self, request, type, public_id, media_id): self.setup(type) resource = self.model.objects.get(code=public_id) media = self.related.objects.get(resource=resource, id=media_id) if media.file: response = serve_media(media.file.path, content_type=media.mime_type) else: raise Http404 return response def related_download(self, request, type, public_id, media_id): self.setup(type) resource = self.model.objects.get(code=public_id) media = self.related.objects.get(resource=resource, id=media_id) if media.file: response = serve_media(media.file.path, content_type=media.mime_type) else: raise Http404 return response class ResourceMixin(View): types = {'corpus': {'model': MediaCorpus, 'form': MediaCorpusForm, 'related': MediaCorpusRelated, 'parent': MediaFonds, 'inlines': [CorpusRelatedInline, ] }, 'fonds': {'model': MediaFonds, 'form': MediaFondsForm, 'related': MediaFondsRelated, 'parent': None, 'inlines': [FondsRelatedInline, ] } } def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[0] return obj def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) context['type'] = self.type return context class ResourceSingleMixin(ResourceMixin): def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) resource = self.get_object() related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists_names(self.request) revisions = Revision.objects.filter(element_type=self.type, element_id=resource.pk).order_by('-time') context['resource'] = resource context['type'] = self.type context['related_media'] = related_media context['revisions'] = revisions if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None if self.parent: context['parents'] = self.parent.objects.filter(children=resource) else: context['parents'] = [] return context class ResourceListView(ResourceMixin, ListView): template_name = "telemeta/resource_list.html" paginate_by = 20 def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self.model.objects.all().order_by('code') def get_context_data(self, **kwargs): context = super(ResourceListView, self).get_context_data(**kwargs) context['count'] = self.object_list.count() return context class ResourceDetailView(ResourceSingleMixin, DetailView): template_name = "telemeta/resource_detail.html" class ResourceDetailDCView(ResourceDetailView): template_name = "telemeta/resource_detail_dc.html" class ResourceAddView(ResourceMixin, CreateView): template_name = 'telemeta/resource_add.html' def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self def get_success_url(self): return reverse_lazy('telemeta-resource-list', kwargs={'type': self.kwargs['type']}) @method_decorator(permission_required('telemeta.add_mediacorpus')) @method_decorator(permission_required('telemeta.add_mediafonds')) def dispatch(self, *args, **kwargs): return super(ResourceAddView, self).dispatch(*args, **kwargs) class ResourceCopyView(ResourceSingleMixin, ResourceAddView): template_name = 'telemeta/resource_edit.html' def get_initial(self): return model_to_dict(self.get_object()) def get_success_url(self): return reverse_lazy('telemeta-resource-list', kwargs={'type': self.kwargs['type']}) # return reverse_lazy('telemeta-resource-detail', kwargs={'type':self.kwargs['type'], 'public_id':self.kwargs['public_id']}) @method_decorator(permission_required('telemeta.add_mediacorpus')) @method_decorator(permission_required('telemeta.add_mediafonds')) def dispatch(self, *args, **kwargs): return super(ResourceCopyView, self).dispatch(*args, **kwargs) class ResourceDeleteView(ResourceSingleMixin, DeleteView): template_name = 'telemeta/resource_confirm_delete.html' def get_success_url(self): return reverse_lazy('telemeta-resource-list', kwargs={'type': self.kwargs['type']}) @method_decorator(permission_required('telemeta.delete_mediacorpus')) @method_decorator(permission_required('telemeta.delete_mediafonds')) def dispatch(self, *args, **kwargs): return super(ResourceDeleteView, self).dispatch(*args, **kwargs) class ResourceEditView(ResourceSingleMixin, UpdateWithInlinesView): template_name = 'telemeta/resource_edit.html' def get_success_url(self): return reverse_lazy('telemeta-resource-detail', kwargs={'type': self.kwargs['type'], 'public_id': self.kwargs['public_id']}) @method_decorator(permission_required('telemeta.change_mediacorpus')) @method_decorator(permission_required('telemeta.change_mediafonds')) def dispatch(self, *args, **kwargs): return super(ResourceEditView, self).dispatch(*args, **kwargs) class ResourceEpubView(ResourceSingleMixin, BaseEpubMixin, View): "Download corpus data embedded in an EPUB3 file" def get(self, request, *args, **kwargs): self.setup_epub(self.get_object()) 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 class ResourceEpubPasswordView(ResourceSingleMixin, FormView): template_name = 'telemeta/resource_epub_password.html' form_class = EpubPasswordForm def get_success_url(self): return reverse_lazy('telemeta-resource-epub-list', kwargs={'type': self.kwargs['type'], 'public_id': self.kwargs['public_id']}) def form_valid(self, form): self.password = form.cleaned_data['password'] if self.password != unicode('mélodie'.decode('utf-8')): messages.info(self.request, _("Bad password, please try again.")) return redirect('telemeta-resource-password-epub', self.kwargs['type'], self.kwargs['public_id']) else: return redirect('telemeta-resource-epub-list', self.kwargs['type'], self.kwargs['public_id']) return super(ResourceEpubPasswordView, self).form_valid(form) def dispatch(self, *args, **kwargs): return super(ResourceEpubPasswordView, self).dispatch(*args, **kwargs) class ResourceEpubListView(ResourceDetailView): template_name = 'telemeta/resource_epub_list.html'
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 ResourceAddView
class ResourceAddView(ResourceMixin, CreateView): template_name = 'telemeta/resource_add.html' def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self def get_success_url(self): return reverse_lazy('telemeta-resource-list', kwargs={'type': self.kwargs['type']}) @method_decorator(permission_required('telemeta.add_mediacorpus')) @method_decorator(permission_required('telemeta.add_mediafonds')) def dispatch(self, *args, **kwargs): return super(ResourceAddView, self).dispatch(*args, **kwargs)
Ancestors (in MRO)
- ResourceAddView
- ResourceMixin
- django.views.generic.edit.CreateView
- django.views.generic.detail.SingleObjectTemplateResponseMixin
- django.views.generic.base.TemplateResponseMixin
- django.views.generic.edit.BaseCreateView
- django.views.generic.edit.ModelFormMixin
- 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 form_class
var initial
var model
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)
Inheritance:
ResourceMixin
.__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:
ResourceMixin
.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, *args, **kwargs)
Inheritance:
ResourceMixin
.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)
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 get(
self, request, *args, **kwargs)
def get(self, request, *args, **kwargs): self.object = None return super(BaseCreateView, self).get(request, *args, **kwargs)
def get_context_data(
self, **kwargs)
Inheritance:
ResourceMixin
.get_context_data
def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) context['type'] = self.type 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_object(
self)
Inheritance:
ResourceMixin
.get_object
def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[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)
def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self
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-resource-list', kwargs={'type': self.kwargs['type']})
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)
Inheritance:
ResourceMixin
.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:
ResourceMixin
.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)
def post(self, request, *args, **kwargs): self.object = None return super(BaseCreateView, 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 )
def setup(
self, type)
Inheritance:
ResourceMixin
.setup
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type
class ResourceCopyView
class ResourceCopyView(ResourceSingleMixin, ResourceAddView): template_name = 'telemeta/resource_edit.html' def get_initial(self): return model_to_dict(self.get_object()) def get_success_url(self): return reverse_lazy('telemeta-resource-list', kwargs={'type': self.kwargs['type']}) # return reverse_lazy('telemeta-resource-detail', kwargs={'type':self.kwargs['type'], 'public_id':self.kwargs['public_id']}) @method_decorator(permission_required('telemeta.add_mediacorpus')) @method_decorator(permission_required('telemeta.add_mediafonds')) def dispatch(self, *args, **kwargs): return super(ResourceCopyView, self).dispatch(*args, **kwargs)
Ancestors (in MRO)
- ResourceCopyView
- ResourceSingleMixin
- ResourceAddView
- ResourceMixin
- django.views.generic.edit.CreateView
- django.views.generic.detail.SingleObjectTemplateResponseMixin
- django.views.generic.base.TemplateResponseMixin
- django.views.generic.edit.BaseCreateView
- django.views.generic.edit.ModelFormMixin
- 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:
ResourceSingleMixin
.__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:
ResourceSingleMixin
.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, *args, **kwargs)
Inheritance:
ResourceSingleMixin
.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:
ResourceAddView
.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:
ResourceAddView
.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 get(
self, request, *args, **kwargs)
Inheritance:
ResourceAddView
.get
def get(self, request, *args, **kwargs): self.object = None return super(BaseCreateView, self).get(request, *args, **kwargs)
def get_context_data(
self, **kwargs)
Inheritance:
ResourceSingleMixin
.get_context_data
def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) resource = self.get_object() related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists_names(self.request) revisions = Revision.objects.filter(element_type=self.type, element_id=resource.pk).order_by('-time') context['resource'] = resource context['type'] = self.type context['related_media'] = related_media context['revisions'] = revisions if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None if self.parent: context['parents'] = self.parent.objects.filter(children=resource) else: context['parents'] = [] return context
def get_context_object_name(
self, obj)
Inheritance:
ResourceAddView
.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:
ResourceAddView
.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:
ResourceAddView
.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:
ResourceAddView
.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:
ResourceAddView
.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_object(
self)
Inheritance:
ResourceSingleMixin
.get_object
def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[0] return obj
def get_prefix(
self)
Inheritance:
ResourceAddView
.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:
ResourceSingleMixin
.get_queryset
def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self
def get_slug_field(
self)
Inheritance:
ResourceAddView
.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:
ResourceAddView
.get_success_url
def get_success_url(self): return reverse_lazy('telemeta-resource-list', kwargs={'type': self.kwargs['type']})
def get_template_names(
self)
Inheritance:
ResourceAddView
.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:
ResourceSingleMixin
.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:
ResourceSingleMixin
.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:
ResourceAddView
.post
def post(self, request, *args, **kwargs): self.object = None return super(BaseCreateView, self).post(request, *args, **kwargs)
def put(
self, *args, **kwargs)
Inheritance:
ResourceAddView
.put
def put(self, *args, **kwargs): return self.post(*args, **kwargs)
def render_to_response(
self, context, **response_kwargs)
Inheritance:
ResourceAddView
.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 )
def setup(
self, type)
Inheritance:
ResourceSingleMixin
.setup
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type
class ResourceDeleteView
class ResourceDeleteView(ResourceSingleMixin, DeleteView): template_name = 'telemeta/resource_confirm_delete.html' def get_success_url(self): return reverse_lazy('telemeta-resource-list', kwargs={'type': self.kwargs['type']}) @method_decorator(permission_required('telemeta.delete_mediacorpus')) @method_decorator(permission_required('telemeta.delete_mediafonds')) def dispatch(self, *args, **kwargs): return super(ResourceDeleteView, self).dispatch(*args, **kwargs)
Ancestors (in MRO)
- ResourceDeleteView
- ResourceSingleMixin
- ResourceMixin
- django.views.generic.edit.DeleteView
- django.views.generic.detail.SingleObjectTemplateResponseMixin
- django.views.generic.base.TemplateResponseMixin
- django.views.generic.edit.BaseDeleteView
- django.views.generic.edit.DeletionMixin
- 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 model
var pk_url_kwarg
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)
Inheritance:
ResourceSingleMixin
.__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:
ResourceSingleMixin
.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 delete(
self, request, *args, **kwargs)
Calls the delete() method on the fetched object and then redirects to the success URL.
def delete(self, request, *args, **kwargs): """ Calls the delete() method on the fetched object and then redirects to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.delete() return HttpResponseRedirect(success_url)
def dispatch(
self, *args, **kwargs)
Inheritance:
ResourceSingleMixin
.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 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)
Inheritance:
ResourceSingleMixin
.get_context_data
def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) resource = self.get_object() related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists_names(self.request) revisions = Revision.objects.filter(element_type=self.type, element_id=resource.pk).order_by('-time') context['resource'] = resource context['type'] = self.type context['related_media'] = related_media context['revisions'] = revisions if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None if self.parent: context['parents'] = self.parent.objects.filter(children=resource) else: context['parents'] = [] 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:
ResourceSingleMixin
.get_object
def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[0] return obj
def get_queryset(
self)
Inheritance:
ResourceSingleMixin
.get_queryset
def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self
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-resource-list', kwargs={'type': self.kwargs['type']})
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)
Inheritance:
ResourceSingleMixin
.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:
ResourceSingleMixin
.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)
def post(self, request, *args, **kwargs): return self.delete(request, *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 )
def setup(
self, type)
Inheritance:
ResourceSingleMixin
.setup
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type
class ResourceDetailDCView
class ResourceDetailDCView(ResourceDetailView): template_name = "telemeta/resource_detail_dc.html"
Ancestors (in MRO)
- ResourceDetailDCView
- ResourceDetailView
- ResourceSingleMixin
- ResourceMixin
- 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:
ResourceDetailView
.__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:
ResourceDetailView
.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:
ResourceDetailView
.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:
ResourceDetailView
.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:
ResourceDetailView
.get_context_data
def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) resource = self.get_object() related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists_names(self.request) revisions = Revision.objects.filter(element_type=self.type, element_id=resource.pk).order_by('-time') context['resource'] = resource context['type'] = self.type context['related_media'] = related_media context['revisions'] = revisions if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None if self.parent: context['parents'] = self.parent.objects.filter(children=resource) else: context['parents'] = [] return context
def get_context_object_name(
self, obj)
Inheritance:
ResourceDetailView
.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:
ResourceDetailView
.get_object
def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[0] return obj
def get_queryset(
self)
Inheritance:
ResourceDetailView
.get_queryset
def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self
def get_slug_field(
self)
Inheritance:
ResourceDetailView
.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:
ResourceDetailView
.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:
ResourceDetailView
.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:
ResourceDetailView
.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:
ResourceDetailView
.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 )
def setup(
self, type)
Inheritance:
ResourceDetailView
.setup
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type
class ResourceDetailView
class ResourceDetailView(ResourceSingleMixin, DetailView): template_name = "telemeta/resource_detail.html"
Ancestors (in MRO)
- ResourceDetailView
- ResourceSingleMixin
- ResourceMixin
- 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 model
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)
Inheritance:
ResourceSingleMixin
.__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:
ResourceSingleMixin
.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:
ResourceSingleMixin
.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)
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:
ResourceSingleMixin
.get_context_data
def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) resource = self.get_object() related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists_names(self.request) revisions = Revision.objects.filter(element_type=self.type, element_id=resource.pk).order_by('-time') context['resource'] = resource context['type'] = self.type context['related_media'] = related_media context['revisions'] = revisions if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None if self.parent: context['parents'] = self.parent.objects.filter(children=resource) else: context['parents'] = [] 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:
ResourceSingleMixin
.get_object
def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[0] return obj
def get_queryset(
self)
Inheritance:
ResourceSingleMixin
.get_queryset
def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self
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)
Inheritance:
ResourceSingleMixin
.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:
ResourceSingleMixin
.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)
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 )
def setup(
self, type)
Inheritance:
ResourceSingleMixin
.setup
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type
class ResourceEditView
class ResourceEditView(ResourceSingleMixin, UpdateWithInlinesView): template_name = 'telemeta/resource_edit.html' def get_success_url(self): return reverse_lazy('telemeta-resource-detail', kwargs={'type': self.kwargs['type'], 'public_id': self.kwargs['public_id']}) @method_decorator(permission_required('telemeta.change_mediacorpus')) @method_decorator(permission_required('telemeta.change_mediafonds')) def dispatch(self, *args, **kwargs): return super(ResourceEditView, self).dispatch(*args, **kwargs)
Ancestors (in MRO)
- ResourceEditView
- ResourceSingleMixin
- ResourceMixin
- 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 form_class
var initial
var inlines
var model
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)
Inheritance:
ResourceSingleMixin
.__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:
ResourceSingleMixin
.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)
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:
ResourceSingleMixin
.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)
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)
If the form and formsets are valid, save the associated models.
def forms_valid(self, form, inlines): """ If the form and formsets are valid, save the associated models. """ self.object = form.save() for formset in inlines: formset.save() return HttpResponseRedirect(self.get_success_url())
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)
Inheritance:
ResourceSingleMixin
.get_context_data
def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) resource = self.get_object() related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists_names(self.request) revisions = Revision.objects.filter(element_type=self.type, element_id=resource.pk).order_by('-time') context['resource'] = resource context['type'] = self.type context['related_media'] = related_media context['revisions'] = revisions if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None if self.parent: context['parents'] = self.parent.objects.filter(children=resource) else: context['parents'] = [] 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:
ResourceSingleMixin
.get_object
def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[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)
Inheritance:
ResourceSingleMixin
.get_queryset
def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self
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-resource-detail', kwargs={'type': self.kwargs['type'], 'public_id': self.kwargs['public_id']})
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)
Inheritance:
ResourceSingleMixin
.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:
ResourceSingleMixin
.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)
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 )
def setup(
self, type)
Inheritance:
ResourceSingleMixin
.setup
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type
class ResourceEpubListView
class ResourceEpubListView(ResourceDetailView): template_name = 'telemeta/resource_epub_list.html'
Ancestors (in MRO)
- ResourceEpubListView
- ResourceDetailView
- ResourceSingleMixin
- ResourceMixin
- 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:
ResourceDetailView
.__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:
ResourceDetailView
.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:
ResourceDetailView
.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:
ResourceDetailView
.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:
ResourceDetailView
.get_context_data
def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) resource = self.get_object() related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists_names(self.request) revisions = Revision.objects.filter(element_type=self.type, element_id=resource.pk).order_by('-time') context['resource'] = resource context['type'] = self.type context['related_media'] = related_media context['revisions'] = revisions if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None if self.parent: context['parents'] = self.parent.objects.filter(children=resource) else: context['parents'] = [] return context
def get_context_object_name(
self, obj)
Inheritance:
ResourceDetailView
.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:
ResourceDetailView
.get_object
def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[0] return obj
def get_queryset(
self)
Inheritance:
ResourceDetailView
.get_queryset
def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self
def get_slug_field(
self)
Inheritance:
ResourceDetailView
.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:
ResourceDetailView
.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:
ResourceDetailView
.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:
ResourceDetailView
.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:
ResourceDetailView
.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 )
def setup(
self, type)
Inheritance:
ResourceDetailView
.setup
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type
class ResourceEpubPasswordView
class ResourceEpubPasswordView(ResourceSingleMixin, FormView): template_name = 'telemeta/resource_epub_password.html' form_class = EpubPasswordForm def get_success_url(self): return reverse_lazy('telemeta-resource-epub-list', kwargs={'type': self.kwargs['type'], 'public_id': self.kwargs['public_id']}) def form_valid(self, form): self.password = form.cleaned_data['password'] if self.password != unicode('mélodie'.decode('utf-8')): messages.info(self.request, _("Bad password, please try again.")) return redirect('telemeta-resource-password-epub', self.kwargs['type'], self.kwargs['public_id']) else: return redirect('telemeta-resource-epub-list', self.kwargs['type'], self.kwargs['public_id']) return super(ResourceEpubPasswordView, self).form_valid(form) def dispatch(self, *args, **kwargs): return super(ResourceEpubPasswordView, self).dispatch(*args, **kwargs)
Ancestors (in MRO)
- ResourceEpubPasswordView
- ResourceSingleMixin
- ResourceMixin
- django.views.generic.edit.FormView
- django.views.generic.base.TemplateResponseMixin
- django.views.generic.edit.BaseFormView
- django.views.generic.edit.FormMixin
- django.views.generic.base.ContextMixin
- django.views.generic.edit.ProcessFormView
- django.views.generic.base.View
- __builtin__.object
Class variables
var content_type
var form_class
var initial
var prefix
var response_class
var success_url
var template_name
Methods
def __init__(
self, **kwargs)
Inheritance:
ResourceSingleMixin
.__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:
ResourceSingleMixin
.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, *args, **kwargs)
Inheritance:
ResourceSingleMixin
.dispatch
def dispatch(self, *args, **kwargs): return super(ResourceEpubPasswordView, self).dispatch(*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)
def form_valid(self, form): self.password = form.cleaned_data['password'] if self.password != unicode('mélodie'.decode('utf-8')): messages.info(self.request, _("Bad password, please try again.")) return redirect('telemeta-resource-password-epub', self.kwargs['type'], self.kwargs['public_id']) else: return redirect('telemeta-resource-epub-list', self.kwargs['type'], self.kwargs['public_id']) return super(ResourceEpubPasswordView, self).form_valid(form)
def get(
self, request, *args, **kwargs)
Handles GET requests and instantiates a blank version of the form.
def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates a blank version of the form. """ form_class = self.get_form_class() form = self.get_form(form_class) return self.render_to_response(self.get_context_data(form=form))
def get_context_data(
self, **kwargs)
Inheritance:
ResourceSingleMixin
.get_context_data
def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) resource = self.get_object() related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists_names(self.request) revisions = Revision.objects.filter(element_type=self.type, element_id=resource.pk).order_by('-time') context['resource'] = resource context['type'] = self.type context['related_media'] = related_media context['revisions'] = revisions if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None if self.parent: context['parents'] = self.parent.objects.filter(children=resource) else: context['parents'] = [] return context
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 """ return self.form_class
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 = { 'initial': self.get_initial(), 'prefix': self.get_prefix(), } if self.request.method in ('POST', 'PUT'): kwargs.update({ 'data': self.request.POST, 'files': self.request.FILES, }) 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_object(
self)
Inheritance:
ResourceSingleMixin
.get_object
def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[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)
Inheritance:
ResourceSingleMixin
.get_queryset
def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self
def get_success_url(
self)
def get_success_url(self): return reverse_lazy('telemeta-resource-epub-list', kwargs={'type': self.kwargs['type'], 'public_id': self.kwargs['public_id']})
def get_template_names(
self)
Returns 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): """ Returns 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. """ if self.template_name is None: raise ImproperlyConfigured( "TemplateResponseMixin requires either a definition of " "'template_name' or an implementation of 'get_template_names()'") else: return [self.template_name]
def http_method_not_allowed(
self, request, *args, **kwargs)
Inheritance:
ResourceSingleMixin
.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:
ResourceSingleMixin
.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)
Handles POST requests, instantiating a form instance with the passed POST variables and then checked for validity.
def post(self, request, *args, **kwargs): """ Handles POST requests, instantiating a form instance with the passed POST variables and then checked for validity. """ form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form)
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 )
def setup(
self, type)
Inheritance:
ResourceSingleMixin
.setup
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type
class ResourceEpubView
Download corpus data embedded in an EPUB3 file
class ResourceEpubView(ResourceSingleMixin, BaseEpubMixin, View): "Download corpus data embedded in an EPUB3 file" def get(self, request, *args, **kwargs): self.setup_epub(self.get_object()) 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
Ancestors (in MRO)
- ResourceEpubView
- ResourceSingleMixin
- ResourceMixin
- telemeta.views.epub.BaseEpubMixin
- django.views.generic.base.View
- telemeta.views.core.TelemetaBaseMixin
- __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 local_path
var template
var template_cover
var template_preamble
Methods
def __init__(
self, **kwargs)
Inheritance:
ResourceSingleMixin
.__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:
ResourceSingleMixin
.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:
ResourceSingleMixin
.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)
def get(self, request, *args, **kwargs): self.setup_epub(self.get_object()) 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_context_data(
self, **kwargs)
Inheritance:
ResourceSingleMixin
.get_context_data
def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) resource = self.get_object() related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists_names(self.request) revisions = Revision.objects.filter(element_type=self.type, element_id=resource.pk).order_by('-time') context['resource'] = resource context['type'] = self.type context['related_media'] = related_media context['revisions'] = revisions if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None if self.parent: context['parents'] = self.parent.objects.filter(children=resource) else: context['parents'] = [] return context
def get_object(
self)
Inheritance:
ResourceSingleMixin
.get_object
def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[0] return obj
def get_queryset(
self)
Inheritance:
ResourceSingleMixin
.get_queryset
def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self
def http_method_not_allowed(
self, request, *args, **kwargs)
Inheritance:
ResourceSingleMixin
.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:
ResourceSingleMixin
.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 setup(
self, type)
Inheritance:
ResourceSingleMixin
.setup
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type
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 ResourceListView
class ResourceListView(ResourceMixin, ListView): template_name = "telemeta/resource_list.html" paginate_by = 20 def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self.model.objects.all().order_by('code') def get_context_data(self, **kwargs): context = super(ResourceListView, self).get_context_data(**kwargs) context['count'] = self.object_list.count() return context
Ancestors (in MRO)
- ResourceListView
- ResourceMixin
- 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 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)
Inheritance:
ResourceMixin
.__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:
ResourceMixin
.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:
ResourceMixin
.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)
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)
Inheritance:
ResourceMixin
.get_context_data
def get_context_data(self, **kwargs): context = super(ResourceListView, 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_object(
self)
Inheritance:
ResourceMixin
.get_object
def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[0] return obj
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)
def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self.model.objects.all().order_by('code')
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)
Inheritance:
ResourceMixin
.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:
ResourceMixin
.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)
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 )
def setup(
self, type)
Inheritance:
ResourceMixin
.setup
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type
class ResourceMixin
class ResourceMixin(View): types = {'corpus': {'model': MediaCorpus, 'form': MediaCorpusForm, 'related': MediaCorpusRelated, 'parent': MediaFonds, 'inlines': [CorpusRelatedInline, ] }, 'fonds': {'model': MediaFonds, 'form': MediaFondsForm, 'related': MediaFondsRelated, 'parent': None, 'inlines': [FondsRelatedInline, ] } } def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[0] return obj def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) context['type'] = self.type return context
Ancestors (in MRO)
- ResourceMixin
- django.views.generic.base.View
- __builtin__.object
Class variables
var http_method_names
var types
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_context_data(
self, **kwargs)
def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) context['type'] = self.type return context
def get_object(
self)
def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[0] return obj
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(
self, type)
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type
class ResourceSingleMixin
class ResourceSingleMixin(ResourceMixin): def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) resource = self.get_object() related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists_names(self.request) revisions = Revision.objects.filter(element_type=self.type, element_id=resource.pk).order_by('-time') context['resource'] = resource context['type'] = self.type context['related_media'] = related_media context['revisions'] = revisions if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None if self.parent: context['parents'] = self.parent.objects.filter(children=resource) else: context['parents'] = [] return context
Ancestors (in MRO)
- ResourceSingleMixin
- ResourceMixin
- django.views.generic.base.View
- __builtin__.object
Class variables
Methods
def __init__(
self, **kwargs)
Inheritance:
ResourceMixin
.__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:
ResourceMixin
.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:
ResourceMixin
.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_context_data(
self, **kwargs)
Inheritance:
ResourceMixin
.get_context_data
def get_context_data(self, **kwargs): context = super(ResourceMixin, self).get_context_data(**kwargs) resource = self.get_object() related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists_names(self.request) revisions = Revision.objects.filter(element_type=self.type, element_id=resource.pk).order_by('-time') context['resource'] = resource context['type'] = self.type context['related_media'] = related_media context['revisions'] = revisions if revisions: context['last_revision'] = revisions[0] else: context['last_revision'] = None if self.parent: context['parents'] = self.parent.objects.filter(children=resource) else: context['parents'] = [] return context
def get_object(
self)
Inheritance:
ResourceMixin
.get_object
def get_object(self): # super(CorpusDetailView, self).get_object() self.type = self.kwargs['type'] self.setup(self.type) objs = self.model.objects.filter(code=self.kwargs['public_id']) if not objs: try: obj = self.model.objects.get(id=self.kwargs['public_id']) except: raise Http404 else: obj = objs[0] return obj
def get_queryset(
self)
def get_queryset(self): self.type = self.kwargs['type'] self.setup(self.type) return self
def http_method_not_allowed(
self, request, *args, **kwargs)
Inheritance:
ResourceMixin
.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:
ResourceMixin
.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 setup(
self, type)
Inheritance:
ResourceMixin
.setup
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.form_class = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.inlines = self.types[type]['inlines'] self.type = type
class ResourceView
Provide Resource web UI methods
class ResourceView(object): """Provide Resource web UI methods""" types = {'corpus': {'model': MediaCorpus, 'form': MediaCorpusForm, 'related': MediaCorpusRelated, 'parent': MediaFonds, }, 'fonds': {'model': MediaFonds, 'form': MediaFondsForm, 'related': MediaFondsRelated, 'parent': None, } } def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.type = type def detail(self, request, type, public_id, template='telemeta/resource_detail.html'): self.setup(type) resource = self.model.objects.get(code=public_id) children = resource.children.all() children = children.order_by('code') related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists(request) revisions = Revision.objects.filter(element_type=type, element_id=resource.id).order_by('-time') if revisions: last_revision = revisions[0] else: last_revision = None if self.parent: parents = self.parent.objects.filter(children=resource) else: parents = [] return render(request, template, {'resource': resource, 'type': type, 'children': children, 'related_media': related_media, 'parents': parents, 'playlists': playlists, 'last_revision': last_revision}) def edit(self, request, type, public_id, template='telemeta/resource_edit.html'): self.setup(type) resource = self.model.objects.get(code=public_id) if request.method == 'POST': form = self.form(data=request.POST, files=request.FILES, instance=resource) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id form.save() resource.set_revision(request.user) return redirect('telemeta-resource-detail', self.type, code) else: form = self.form(instance=resource) return render(request, template, {'resource': resource, 'type': type, 'form': form, }) def add(self, request, type, template='telemeta/resource_add.html'): self.setup(type) resource = self.model() if request.method == 'POST': form = self.form(data=request.POST, files=request.FILES, instance=resource) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id form.save() resource.set_revision(request.user) return redirect('telemeta-resource-detail', self.type, code) else: form = self.form(instance=resource) return render(request, template, {'resource': resource, 'type': type, 'form': form, }) def copy(self, request, type, public_id, template='telemeta/resource_edit.html'): self.setup(type) if request.method == 'POST': resource = self.model() form = self.form(data=request.POST, files=request.FILES, instance=resource) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id resource.save() resource.set_revision(request.user) return redirect('telemeta-resource-detail', self.type, code) else: resource = self.model.objects.get(code=public_id) form = self.form(instance=resource) return render(request, template, {'resource': resource, 'type': type, "form": form, }) def playlist(self, request, type, public_id, template, mimetype): self.setup(type) try: resource = self.model.objects.get(code=public_id) except ObjectDoesNotExist: raise Http404 template = loader.get_template(template) context = RequestContext(request, {'resource': resource, 'host': request.META['HTTP_HOST']}) return HttpResponse(template.render(context), content_type=mimetype) def delete(self, request, type, public_id): self.setup(type) resource = self.model.objects.get(code=public_id) revisions = Revision.objects.filter(element_type='resource', element_id=resource.id) for revision in revisions: revision.delete() resource.delete() return HttpResponseRedirect('/archives/' + self.type + '/') def related_stream(self, request, type, public_id, media_id): self.setup(type) resource = self.model.objects.get(code=public_id) media = self.related.objects.get(resource=resource, id=media_id) if media.file: response = serve_media(media.file.path, content_type=media.mime_type) else: raise Http404 return response def related_download(self, request, type, public_id, media_id): self.setup(type) resource = self.model.objects.get(code=public_id) media = self.related.objects.get(resource=resource, id=media_id) if media.file: response = serve_media(media.file.path, content_type=media.mime_type) else: raise Http404 return response
Ancestors (in MRO)
- ResourceView
- __builtin__.object
Class variables
var types
Methods
def add(
self, request, type, template='telemeta/resource_add.html')
def add(self, request, type, template='telemeta/resource_add.html'): self.setup(type) resource = self.model() if request.method == 'POST': form = self.form(data=request.POST, files=request.FILES, instance=resource) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id form.save() resource.set_revision(request.user) return redirect('telemeta-resource-detail', self.type, code) else: form = self.form(instance=resource) return render(request, template, {'resource': resource, 'type': type, 'form': form, })
def copy(
self, request, type, public_id, template='telemeta/resource_edit.html')
def copy(self, request, type, public_id, template='telemeta/resource_edit.html'): self.setup(type) if request.method == 'POST': resource = self.model() form = self.form(data=request.POST, files=request.FILES, instance=resource) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id resource.save() resource.set_revision(request.user) return redirect('telemeta-resource-detail', self.type, code) else: resource = self.model.objects.get(code=public_id) form = self.form(instance=resource) return render(request, template, {'resource': resource, 'type': type, "form": form, })
def delete(
self, request, type, public_id)
def delete(self, request, type, public_id): self.setup(type) resource = self.model.objects.get(code=public_id) revisions = Revision.objects.filter(element_type='resource', element_id=resource.id) for revision in revisions: revision.delete() resource.delete() return HttpResponseRedirect('/archives/' + self.type + '/')
def detail(
self, request, type, public_id, template='telemeta/resource_detail.html')
def detail(self, request, type, public_id, template='telemeta/resource_detail.html'): self.setup(type) resource = self.model.objects.get(code=public_id) children = resource.children.all() children = children.order_by('code') related_media = self.related.objects.filter(resource=resource) check_related_media(related_media) playlists = get_playlists(request) revisions = Revision.objects.filter(element_type=type, element_id=resource.id).order_by('-time') if revisions: last_revision = revisions[0] else: last_revision = None if self.parent: parents = self.parent.objects.filter(children=resource) else: parents = [] return render(request, template, {'resource': resource, 'type': type, 'children': children, 'related_media': related_media, 'parents': parents, 'playlists': playlists, 'last_revision': last_revision})
def edit(
self, request, type, public_id, template='telemeta/resource_edit.html')
def edit(self, request, type, public_id, template='telemeta/resource_edit.html'): self.setup(type) resource = self.model.objects.get(code=public_id) if request.method == 'POST': form = self.form(data=request.POST, files=request.FILES, instance=resource) if form.is_valid(): code = form.cleaned_data['code'] if not code: code = public_id form.save() resource.set_revision(request.user) return redirect('telemeta-resource-detail', self.type, code) else: form = self.form(instance=resource) return render(request, template, {'resource': resource, 'type': type, 'form': form, })
def playlist(
self, request, type, public_id, template, mimetype)
def playlist(self, request, type, public_id, template, mimetype): self.setup(type) try: resource = self.model.objects.get(code=public_id) except ObjectDoesNotExist: raise Http404 template = loader.get_template(template) context = RequestContext(request, {'resource': resource, 'host': request.META['HTTP_HOST']}) return HttpResponse(template.render(context), content_type=mimetype)
def setup(
self, type)
def setup(self, type): self.model = self.types[type]['model'] self.form = self.types[type]['form'] self.related = self.types[type]['related'] self.parent = self.types[type]['parent'] self.type = type