def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." from keops.modules.base.auth import UserLog # First check if the user can see this history. model = self.model obj = get_object_or_404(model, pk=unquote(object_id)) #if not self.has_change_permission(request, obj): # raise PermissionDenied # Then get the history for this object. opts = model._meta app_label = opts.app_label action_list = UserLog.objects.filter( object_id=unquote(object_id), content_type__id__exact=ContentType.objects.get_for_model(model).id ).select_related().order_by('action_time') context = { 'title': _('Change history: %s') % force_text(obj), 'action_list': action_list, 'module_name': capfirst(force_text(opts.verbose_name_plural)), 'object': obj, 'app_label': app_label, 'opts': opts, 'preserved_filters': self.get_preserved_filters(request), } context.update(extra_context or {}) return TemplateResponse(request, self.object_history_template or [ "keops/%s/%s/object_history.html" % (app_label, opts.model_name), "keops/%s/object_history.html" % app_label, "keops/object_history.html" ], context, current_app=self.admin_site.name)
def __call__(self, request, url): # Check that LogEntry, ContentType and the auth context processor are installed. from django.conf import settings if settings.DEBUG: from django.contrib.admin.models import LogEntry if not LogEntry._meta.installed: raise ImproperlyConfigured( "Put 'django.contrib.admin' in your INSTALLED_APPS setting in order to use the admin application." ) if not ContentType._meta.installed: raise ImproperlyConfigured( "Put 'django.contrib.contenttypes' in your INSTALLED_APPS setting in order to use the admin application." ) if 'django.core.context_processors.auth' not in settings.TEMPLATE_CONTEXT_PROCESSORS: raise ImproperlyConfigured( "Put 'django.core.context_processors.auth' in your TEMPLATE_CONTEXT_PROCESSORS setting in order to use the admin application." ) # Delegate to the appropriate method, based on the URL. if url is None: return self.changelist_view(request) elif url.endswith('add'): return self.add_view(request) elif url.endswith('history'): return self.history_view(request, unquote(url[:-8])) elif url.endswith('delete'): return self.delete_view(request, unquote(url[:-7])) else: return self.change_view(request, unquote(url))
def __call__(self, request, url): """ Delegate to the appropriate method, based on the URL. """ if url is None: return self.list_pages(request) elif url.endswith('add-plugin'): return add_plugin(request) elif 'edit-plugin' in url: plugin_id = url.split("/")[-1] return edit_plugin(request, plugin_id, self.admin_site) elif 'remove-plugin' in url: return remove_plugin(request) elif 'move-plugin' in url: return move_plugin(request) elif url.endswith('/move-page'): return self.move_page(request, unquote(url[:-10])) elif url.endswith('/copy-page'): return self.copy_page(request, unquote(url[:-10])) elif url.endswith('/change-status'): return change_status(request, unquote(url[:-14])) elif url.endswith('/change-navigation'): return change_innavigation(request, unquote(url[:-18])) elif url.endswith('jsi18n') or url.endswith('jsi18n/'): return HttpResponseRedirect("../../../jsi18n/") elif ('history' in url or 'recover' in url) and request.method == "POST": resp = super(PageAdmin, self).__call__(request, url) if resp.status_code == 302: version = int(url.split("/")[-1]) revert_plugins(request, version) return resp if len(url.split("/?")):# strange bug in 1.0.2 if post and get variables in the same request url = url.split("/?")[0] return super(PageAdmin, self).__call__(request, url)
def mark_as_complete(self, request, prescription_id): """ Mark a treatment as dealt with. """ object_id = request.POST.get('id') obj = self.get_object(request, unquote(object_id)) current = self.get_prescription(request, unquote(prescription_id)) if ((obj is not None and self.has_change_permission(request, obj) and request.method == "POST" and current.is_draft)): # NOTE: instantiating the ModelForm below was still resulting in # a form with the 'locations' field (same as the TreatmentForm). # This would fail validation on the submit in section B2. # Workaround was to create and use the TreatmentCompleteForm instead. # Might be refactored by a better Django dev than I. #ModelForm = self.get_form(request, obj, fields=('complete',)) #form = ModelForm(request.POST, request.FILES, instance=obj) form = TreatmentCompleteForm(request.POST, request.FILES, instance=obj) complete = obj.complete # form.is_valid() updates the obj if form.is_valid(): obj = self.save_form(request, form, change=True) self.save_model(request, obj, form, change=True) else: obj.complete = complete return HttpResponse(json.dumps({'complete': obj.complete, 'description': obj.description})) return HttpResponse( 'Sorry, this endpoint only accepts valid POST requests.')
def audit_view(self, request, object_id, extra_context=None): from audit.models import LogItem # First check if the user can see this history. model = self.model obj = get_object_or_404(self.get_queryset(request), pk=unquote(object_id)) if not self.has_change_permission(request, obj): raise PermissionDenied # Then get the history for this object. opts = model._meta app_label = opts.app_label action_list = LogItem.objects.filter( object_id=unquote(object_id), content_type__id__exact=ContentType.objects.get_for_model(model).id ).select_related().order_by('action_time') context = dict(self.admin_site.each_context(), title=_('Change history: %s') % force_text(obj), action_list=action_list, module_name=capfirst(force_text(opts.verbose_name_plural)), object=obj, app_label=app_label, opts=opts, preserved_filters=self.get_preserved_filters(request), ) context.update(extra_context or {}) return TemplateResponse(request, self.object_history_template or [ "admin/%s/%s/audit_history.html" % (app_label, opts.module_name), "admin/%s/audit_history.html" % app_label, "admin/audit_history.html" ], context, current_app=self.admin_site.name)
def button_view_dispatcher(self, request, url): # Dispatch the url to a function call if url is not None: import re res = re.match('(.*/)?(?P<id>\d+)/(?P<command>.*)', url) if res: if res.group('command') in [b.func_name for b in self.change_buttons]: obj = self.model._default_manager.get(pk=res.group('id')) response = getattr(self, res.group('command'))(request, obj) if response is None: from django.http import HttpResponseRedirect return HttpResponseRedirect(request.META['HTTP_REFERER']) return response else: res = re.match('(.*/)?(?P<command>.*)', url) if res: if res.group('command') in [b.func_name for b in self.list_buttons]: response = getattr(self, res.group('command'))(request) if response is None: from django.http import HttpResponseRedirect return HttpResponseRedirect(request.META['HTTP_REFERER']) return response # Delegate to the appropriate method, based on the URL. from django.contrib.admin.util import unquote if url is None: return self.changelist_view(request) elif url == "add": return self.add_view(request) elif url.endswith('/history'): return self.history_view(request, unquote(url[:-8])) elif url.endswith('/delete'): return self.delete_view(request, unquote(url[:-7])) else: return self.change_view(request, unquote(url))
def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." # First check if the object exists and the user can see its history. model = self.model obj = get_object_or_404(model.objects.using(request.database), pk=unquote(object_id)) if not self.has_change_permission(request, obj): raise PermissionDenied # Then get the history for this object. opts = model._meta app_label = opts.app_label action_list = LogEntry.objects.using(request.database).filter( object_id=unquote(object_id), content_type__id__exact=ContentType.objects.get_for_model(model).id ).select_related().order_by('action_time') context = { 'title': capfirst(force_text(opts.verbose_name) + " " + object_id), 'action_list': action_list, 'module_name': capfirst(force_text(opts.verbose_name_plural)), 'object': obj, 'app_label': app_label, 'opts': opts, 'active_tab': 'history', 'object_id': object_id, 'model': ContentType.objects.get_for_model(model).model, } context.update(extra_context or {}) return TemplateResponse(request, self.object_history_template or [ "admin/%s/%s/object_history.html" % (app_label, opts.model_name), "admin/%s/object_history.html" % app_label, "admin/object_history.html" ], context, current_app=self.admin_site.name)
def revision_view(self, request, object_id, version_id, extra_context=None): if not self.has_change_permission(request): raise PermissionDenied() obj = get_object_or_404(self.model, pk=unquote(object_id)) version = get_object_or_404(Version, pk=unquote(version_id), object_id=force_text(obj.pk)) revision = version.revision if request.method == "POST": revision.revert() opts = self.model._meta pk_value = obj._get_pk_val() preserved_filters = self.get_preserved_filters(request) msg_dict = { 'name': force_text(opts.verbose_name), 'obj': force_text(obj) } msg = _('The %(name)s "%(obj)s" was successfully reverted. ' 'You may edit it again below.') % msg_dict self.message_user(request, msg, messages.SUCCESS) redirect_url = reverse('admin:%s_%s_change' % (opts.app_label, opts.model_name), args=(pk_value,), current_app=self.admin_site.name) redirect_url = add_preserved_filters({ 'preserved_filters': preserved_filters, 'opts': opts, }, redirect_url) return HttpResponseRedirect(redirect_url) else: context = { 'object': obj, 'version': version, 'revision': revision, 'revision_date': revision.date_created, 'versions': revision.version_set.order_by( 'content_type__name', 'object_id_int').all, 'object_name': force_text(self.model._meta.verbose_name), 'app_label': self.model._meta.app_label, 'opts': self.model._meta, 'add': False, 'change': True, 'save_as': False, 'has_add_permission': self.has_add_permission(request), 'has_change_permission': self.has_change_permission( request, obj), 'has_delete_permission': self.has_delete_permission( request, obj), 'has_file_field': True, 'has_absolute_url': False, 'original': obj, } return render_to_response(self.revision_confirmation_template, context, RequestContext(request))
def create_preview(self, request, object_id, form_url="", extra_context=None): """ Create preview (including permissions and groups/plugins) """ model = self.model opts = model._meta container = Container.objects.get(id=unquote(object_id)) # check permissions if not self.has_preview_permission(request, container): raise PermissionDenied # pre signal signals.vola_pre_create_preview.send(sender=request, container=container) # temporarily save given values name = container.name slug = container.slug cache_key = container.cache_key transfer_container_id = container.id # new container container.pk = None now = datetime.datetime.now() container.name = "%s (%s)" % (container.name, time.time()) container.slug = "%s_%s" % (container.slug, time.time()) container.cache_key = "%s_%s" % (container.cache_key, time.time()) container.preview = True container.save() # set new name/slug/cache_key container.name = "%s (%s)" % (name, container.id) container.slug = "%s_%s" % (slug, container.id) container.cache_key = "%s_%s" % (cache_key, container.id) container.transfer_container_id = transfer_container_id container.save() # new permissions for permission in Permission.objects.filter(container__id=unquote(object_id)): permission.pk = None permission.container = container permission.save() # new groups and new plugins for group in Group.objects.filter(container__id=unquote(object_id)): group_id = group.id group.pk = None group.container = container group.save() for plugin in Plugin.objects.filter(container__id=unquote(object_id), group=group_id): p = eval("plugin."+plugin.model_name) p.pk = None p.id = None p.container = container p.group = group p.save() # post signal signals.vola_post_create_preview.send(sender=request, container=container) # message and redirect msg_dict = {"name": force_text(opts.verbose_name), "obj": force_text(container)} msg = _("The %(obj)s was added successfully. You may edit it again below.") % msg_dict self.message_user(request, msg) post_url_continue = reverse("admin:%s_%s_change" % (opts.app_label, opts.module_name), args=(container.id,), current_app=self.admin_site.name) return HttpResponseRedirect(post_url_continue)
def edit_option(self, request, object_id, option_id): model = self.model opts = model._meta obj = self.get_object(request, unquote(object_id)) if not self.has_change_permission(request, obj): raise PermissionDenied if obj is None: raise Http404( _('%(name)s object with primary key %(key)r does not exist.') % { 'name': force_unicode(opts.verbose_name), 'key': escape(object_id) }) try: option = obj.option_set.get(id=unquote(option_id)) except ObjectDoesNotExist: raise Http404( _('Option %(option)d for question %(question)s does not exist.' ) % { 'option': escape(object_id), 'question': escape(option_id) }) if request.method == 'PUT': data = simplejson.loads(request.raw_post_data) for key, value in data.items(): if key != 'id': setattr(option, key, value) option.save() return HttpResponse(simplejson.dumps(data), mimetype='application/json') elif request.method == 'DELETE': option.delete() return HttpResponse('') elif request.method == 'GET': data = { 'id': option.id, 'optiontype': option.optiontype, 'solution': option.solution, 'feedback': option.feedback, 'text': option.text, 'x': option.x, 'y': option.y, 'width': option.width, 'height': option.height, } return HttpResponse(simplejson.dumps(data), mimetype='application/json')
def __call__(self, request, url): # Delegate to the appropriate method, based on the URL. if url is None: return self.changelist_view(request) elif url == "add": return self.add_view(request) elif url.endswith('/history'): return self.history_view(request, unquote(url[:-8])) elif url.endswith('/delete'): return self.delete_view(request, unquote(url[:-7])) else: return self.change_view(request, unquote(url))
def __call__(self, request, url): # Delegate to the appropriate method, based on the URL. if url is None: return self.changelist_view(request) elif url == "add": return self.add_view(request) elif url.endswith('/history'): return self.history_view(request, [unquote(part) for part in url[:-8].split(PRIMARY_KEY_URL_SEPARATOR)]) elif url.endswith('/delete'): return self.delete_view(request, [unquote(part) for part in url[:-7].split(PRIMARY_KEY_URL_SEPARATOR)]) else: return self.change_view(request, [unquote(part) for part in url.split(PRIMARY_KEY_URL_SEPARATOR)])
def delete_view(self, request, object_id, extra_context=None): "The 'delete' admin view for this model." opts = self.model._meta app_label = opts.app_label obj = self.get_object(request, unquote(object_id)) if not self.has_delete_permission(request, obj): raise PermissionDenied if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)}) # frePPLe specific selection of the database using = request.database # Populate deleted_objects, a data structure of all related objects that # will also be deleted. (deleted_objects, perms_needed, protected) = get_deleted_objects( [obj], opts, request.user, self.admin_site, using) if request.POST: # The user has already confirmed the deletion. if perms_needed: raise PermissionDenied obj_display = force_text(obj) self.log_deletion(request, obj, obj_display) self.delete_model(request, obj) self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_text(opts.verbose_name), 'obj': force_text(obj_display)}) # Redirect to previous crumb return HttpResponseRedirect(request.session['crumbs'][request.prefix][-3][2]) object_name = force_text(opts.verbose_name) context = { "title": capfirst(object_name + ' ' + unquote(object_id)), "object_name": object_name, "object": obj, "deleted_objects": deleted_objects, "perms_lacking": perms_needed, "protected": protected, "opts": opts, "app_label": app_label, } context.update(extra_context or {}) return TemplateResponse(request, self.delete_confirmation_template or [ "admin/%s/%s/delete_confirmation.html" % (app_label, opts.object_name.lower()), "admin/%s/delete_confirmation.html" % app_label, "admin/delete_confirmation.html" ], context, current_app=self.admin_site.name)
def diff_view(self, request, object_id, version_id, extra_context=None): """Generate a diff between document versions.""" opts = self.model._meta app_label = opts.app_label obj = get_object_or_404(self.model, pk=unquote(object_id)) obj_old = get_object_or_404(Version, pk=unquote(version_id), object_id=force_text(obj.pk)) try: logger.debug("{0} views diff_view of {1}".format( request.user.fullname, obj)) except: logger.debug("DocumentAdmin diff_view called without " "object or request.") fieldsets = self.get_fieldsets(request, obj) # inline_instances = self.get_inline_instances(request, obj) d = diff_match_patch() diffs = [] for (name, field_options) in fieldsets: if 'fields' in field_options: for f in field_options['fields']: field = getattr(obj, f) if (not field) or (type(field) not in (str, unicode)): continue diff = d.diff_main(obj_old.field_dict[f] or '', field) d.diff_cleanupSemantic(diff) diffs.append((opts.get_field_by_name(f)[0].verbose_name, mark_safe(d.diff_prettyHtml(diff)))) context = { 'breadcrumbs': self.get_breadcrumbs(request, obj), 'diffs': diffs, 'object': obj, 'opts': self.model._meta, 'version_date': obj_old.revision.date_created, } context.update(extra_context or {}) return TemplateResponse(request, self.object_diff_template or [ 'admin/%s/%s/object_diff.html' % (app_label, opts.object_name.lower()), 'admin/%s/object_diff.html' % app_label, 'admin/object_diff.html' ], context, current_app=self.admin_site.name)
def get_object(self, queryset=None): self.nueva_ip = False try: reserva = ReservaIp.objects.get(pk=self.kwargs['pk']) #IGNORE:no-member except ReservaIp.DoesNotExist: #IGNORE:no-member reserva = ReservaIp(ip_int=self.kwargs['pk'],red_id=self.kwargs['red_id']) reserva.notas = unquote(self.request.GET.get('notas',reserva.notas)) reserva.no_peticion = unquote(self.request.GET.get('no_peticion',reserva.no_peticion)) self.nueva_ip = True #IGNORE:attribute-defined-outside-init #Tanto si ya existe la reserva como si es nueva, modificamos el usario y la fecha de modificación. reserva.usuario = self.request.user.username reserva.ultima_modificacion = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") return reserva
def revision_view(self, request, object_id, version_id, extra_context=None): """Custom revision_view.""" obj = get_object_or_404(self.model, pk=unquote(object_id)) version = get_object_or_404(Version, pk=unquote(version_id), object_id=force_text(obj.pk)) context = { 'object': obj, 'version_date': version.revision.date_created } context.update(extra_context or {}) return super(BaseAdmin, self).revision_view(request, object_id, version_id, extra_context=context)
def ajaxdelete_view(self, request, object_id): "The 'delete' admin view for this model." opts = self.model._meta app_label = opts.app_label obj = self.get_object(request, unquote(object_id)) if not self.has_delete_permission(request, obj): raise PermissionDenied if obj is None: raise Http404( _('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': escape(object_id)} ) using = router.db_for_write(self.model) # Populate deleted_objects, a data structure of all related objects that # will also be deleted. (deleted_objects, perms_needed, protected) = get_deleted_objects( [obj], opts, request.user, self.admin_site, using) if perms_needed: return PermissionDenied obj_display = force_text(obj) self.log_deletion(request, obj, obj_display) self.delete_model(request, obj) return HttpResponse('<html><body>OK</body></html>')
def change_view(self, request, object_id, extra_context=None): opts = self.model._meta obj = self.get_object(request, unquote(object_id)) if not self.has_change_permission(request, obj): raise PermissionDenied if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_unicode(opts.verbose_name), 'key': escape(object_id)}) if request.method == 'POST' and "_saveasnew" in request.POST: return self.add_view(request, form_url='../add/') ModelForm = self.get_form(request, obj) form = ModelForm(request.POST or None, request.FILES or None, instance=obj) if form.is_valid(): return self.form_valid_change(form, request) adminForm = self.get_admin_form(form, request, obj) context = { 'title': _('Change %s') % force_unicode(opts.verbose_name), 'adminform': adminForm, 'object_id': object_id, 'original': obj, 'is_popup': "_popup" in request.REQUEST, 'media': mark_safe(self.media + adminForm.media), 'inline_admin_formsets': [], 'errors': helpers.AdminErrorList(form, []), 'root_path': self.admin_site.root_path, 'app_label': opts.app_label, } context.update(extra_context or {}) return self.render_change_form(request, context, change=True, obj=obj)
def delete_view(self, request, object_id, extra_context=None): """ Overrides the default to enable redirecting to the directory view after deletion of a folder. we need to fetch the object and find out who the parent is before super, because super will delete the object and make it impossible to find out the parent folder to redirect to. """ parent_folder = None try: obj = self.queryset(request).get(pk=unquote(object_id)) parent_folder = obj.parent except self.model.DoesNotExist: obj = None r = super(FolderAdmin, self).delete_view(request=request, object_id=object_id, extra_context=extra_context) url = r.get("Location", None) if url in ["../../../../", "../../"]: if parent_folder: url = reverse("admin:filer-directory_listing", kwargs={"folder_id": parent_folder.id}) else: url = reverse("admin:filer-directory_listing-root") return HttpResponseRedirect(url) return r
def log_clicks_view(self, request, object_id, extra_context=None): model = self.model opts = model._meta app_label = opts.app_label obj = get_object_or_404(model, pk=unquote(object_id)) context = { 'title': _('Log clicks'), 'module_name': capfirst(opts.verbose_name_plural), 'object': obj, 'app_label': app_label, 'log_clicks': Click.objects.filter(banner=obj).order_by('-datetime') } context.update(extra_context or {}) context_instance = template.RequestContext( request, current_app=self.admin_site.name) return render_to_response(self.object_log_clicks_template or [ "admin/%s/%s/object_log_clicks.html" % (app_label, opts.object_name.lower()), "admin/%s/object_log_clicks.html" % app_label, ], context, context_instance=context_instance)
def run_view(self, request, query_hash, extra_context=None): obj = self.get_object(request, unquote(query_hash)) data = obj.query_data query_key = "qbe_query_%s" % query_hash if not query_key in request.session: request.session[query_key] = data return redirect("qbe_results", query_hash)
def move_view(self, request, object_id): instance = self.get_object(request, unquote(object_id)) if not self.has_change_permission(request, instance): raise PermissionDenied() if request.method != 'POST': raise SuspiciousOperation() target_id = int(request.POST['target_id']) position = request.POST['position'] target_instance = self.get_object(request, target_id) if position == 'before': instance.move_to(target_instance, 'left') elif position == 'after': instance.move_to(target_instance, 'right') elif position == 'inside': instance.move_to(target_instance) else: raise Exception('Unknown position') return util.JsonResponse( dict(success=True) )
def change_view(self, request, object_id, **kwargs): if request.is_ajax(): return self.change_content( request, self.get_object(request, unquote(object_id))) else: return super(DataIdAdmin, self).change_view(request, object_id, **kwargs)
def change_view(self, request, object_id, *args, **kwargs): obj = self.get_object(request, unquote(object_id)) opts = self.model._meta headers = obj.submissions.get_formfield_labels() rows = obj.submissions.as_ordered_dictionaries(headers.keys()) return render( request, 'admin/form_builder/form/change_form.html', { 'title': _('View %s submissions') % force_text(opts.verbose_name), 'object_id': object_id, 'original': obj, 'is_popup': "_popup" in request.REQUEST, 'app_label': opts.app_label, 'headers': headers, 'rows': rows, 'csv_file_name': self.csv_file_name(obj), 'download_url': reverse('admin:{0}'.format(self.download_url_name), args=[object_id]) })
def move_view(self, request, object_id, direction): obj = get_object_or_404(self.model, pk=unquote(object_id)) if direction == 'up': obj.move_up() else: obj.move_down() return HttpResponseRedirect('../../')
def move_view(self, request, object_id): instance = self.get_object(request, unquote(object_id)) if not self.has_change_permission(request, instance): raise PermissionDenied() if request.method != 'POST': raise SuspiciousOperation() target_id = request.POST['target_id'] position = request.POST['position'] target_instance = self.get_object(request, target_id) if position == 'before': instance.move_to(target_instance, 'left') elif position == 'after': instance.move_to(target_instance, 'right') elif position == 'inside': instance.move_to(target_instance) else: raise Exception('Unknown position') if self.trigger_save_after_move: instance.save() return util.JsonResponse(dict(success=True))
def history_view(self, request, object_id, extra_context=None): """Renders the history view.""" # check if user has change or add permissions for model if not self.has_change_permission(request): raise PermissionDenied object_id = unquote( object_id) # Underscores in primary key get quoted to "_5F" opts = self.model._meta action_list = [{ "revision": version.revision, "url": reverse("%s:%s_%s_revision" % (self.admin_site.name, opts.app_label, opts.model_name), args=(quote(version.object_id), version.id)), } for version in self._order_version_queryset( self.revision_manager.get_for_object_reference( self.model, object_id, ).select_related("revision__user"))] # Compile the context. context = {"action_list": action_list} context.update(extra_context or {}) return super(VersionAdmin, self).history_view(request, object_id, context)
def revision_view(self, request, object_id, version_id, extra_context=None): """Displays the contents of the given revision.""" # check if user has change or add permissions for model if not self.has_change_permission(request): raise PermissionDenied object_id = unquote( object_id) # Underscores in primary key get quoted to "_5F" obj = get_object_or_404(self.model, pk=object_id) version = get_object_or_404(Version, pk=version_id, object_id=force_text(obj.pk)) # Generate the context. context = { "title": _("Revert %(name)s") % { "name": force_text(self.model._meta.verbose_name) }, } context.update(extra_context or {}) return self.render_revision_form(request, obj, version, context, revert=True)
def delete_view(self, request, object_id, extra_context=None): # overrided delete_view method opts = self.model._meta obj = self.get_object(request, unquote(object_id)) if not self.has_delete_permission(request, obj): raise PermissionDenied if obj is None: raise Http404( _('%(name)s object with primary key %(key)r does not exist.') % { 'name': force_unicode(opts.verbose_name), 'key': escape(object_id) }) using = router.db_for_write(self.model) # Populate deleted_objects, a data structure of all related objects that # will also be deleted. (deleted_objects, perms_needed, protected) = get_deleted_objects([obj], opts, request.user, self.admin_site, using) new_deletable_objects = parse_deletable_list(deleted_objects) extra_context = {'deleted_objects': [new_deletable_objects]} return super(DideAdmin, self).delete_view(request, object_id, extra_context)
def history_view(self, request, object_id, extra_context=None): "The 'history' admin view for this model." model = self.model opts = model._meta app_label = opts.app_label pk_name = opts.pk.attname history = getattr(model, model._meta.simple_history_manager_attribute) action_list = history.filter(**{pk_name: object_id}) # If no history was found, see whether this object even exists. obj = get_object_or_404(model, pk=unquote(object_id)) content_type = ContentType.objects.get_for_model(User) admin_user_view = 'admin:%s_%s_change' % (content_type.app_label, content_type.model) context = { 'title': _('Change history: %s') % force_text(obj), 'action_list': action_list, 'module_name': capfirst(force_text(opts.verbose_name_plural)), 'object': obj, 'root_path': getattr(self.admin_site, 'root_path', None), 'app_label': app_label, 'opts': opts, 'admin_user_view': admin_user_view } context.update(extra_context or {}) context_instance = template.RequestContext( request, current_app=self.admin_site.name) return render_to_response(self.object_history_template, context, context_instance=context_instance)
def change_view(self, request, object_id, extra_context=None): obj = self.queryset(request).get(pk=unquote(object_id)) my_context = { 'xml': obj.get_xml(), } return super(MenuAdmin, self).change_view(request, object_id, extra_context=my_context)
def change_view(self, request, object_id, form_url='', extra_context={}): obj = self.get_object(request, unquote(object_id)) if request.user.is_superuser: has_object_change_permission = True elif not request.user.has_perm('coop_local.change_organization'): has_object_change_permission = False elif request.user.has_perm('coop_local.change_only_his_organization'): has_object_change_permission = request.user in obj.authors.all() else: has_object_change_permission = True if not has_object_change_permission and request.method == 'POST': opts = obj._meta module_name = opts.module_name if "_continue" in request.POST: if "_popup" in request.REQUEST: return HttpResponseRedirect(request.path + "?_popup=1") else: return HttpResponseRedirect(request.path) elif "_saveasnew" in request.POST: return HttpResponseRedirect(reverse('admin:%s_%s_change' % (opts.app_label, module_name), args=(pk_value,), current_app=self.admin_site.name)) elif "_addanother" in request.POST: return HttpResponseRedirect(reverse('admin:%s_%s_add' % (opts.app_label, module_name), current_app=self.admin_site.name)) else: return HttpResponseRedirect(reverse('admin:%s_%s_changelist' % (opts.app_label, module_name), current_app=self.admin_site.name)) extra_context['has_object_change_permission'] = has_object_change_permission return super(OrganizationAdmin, self).change_view(request, object_id, form_url, extra_context)
def log_clicks_view(self, request, object_id, extra_context=None): model = self.model opts = model._meta app_label = opts.app_label obj = get_object_or_404(model, pk=unquote(object_id)) context = { "title": _("Log clicks"), "module_name": capfirst(force_unicode(opts.verbose_name_plural)), "object": obj, "app_label": app_label, "log_clicks": Click.objects.filter(banner=obj).order_by("-datetime"), } context.update(extra_context or {}) context_instance = template.RequestContext(request, current_app=self.admin_site.name) return render_to_response( self.object_log_clicks_template or [ "admin/%s/%s/object_log_clicks.html" % (app_label, opts.object_name.lower()), "admin/%s/object_log_clicks.html" % app_label, ], context, context_instance=context_instance, )
def folder_expand_view(self, request, object_id, extra_context=None): node = get_object_or_404(FileNode, pk=unquote(object_id), node_type=FileNode.FOLDER) expand = list(node.get_ancestors()) expand.append(node) response = HttpResponseRedirect('%s#%s' % (reverse('admin:media_tree_filenode_changelist'), self.anchor_name(node))); self.set_expanded_folders_pk(response, [expanded.pk for expanded in expand]) return response
def refresh_lock_view(self, request, object_id, extra_context=None): obj = self.get_object(request, unquote(object_id)) if not self.has_change_permission(request, obj): raise PermissionDenied try: obj.lock_for(request.user) except ObjectLockedError: # The user tried to overwrite an existing lock by another user. # No can do, pal! return HttpResponse(status=409) # Conflict # Format date like a DateTimeInput would have done format = formats.get_format('DATETIME_INPUT_FORMATS')[0] original_locked_at = obj.locked_at.strftime(format) original_modified_at = obj.modified_at.strftime(format) response = simplejson.dumps({ 'original_locked_at': original_locked_at, 'original_modified_at': original_modified_at, }) return HttpResponse(response, mimetype="application/json")
def detail_view(self, request, object_id, extra_context=None): opts = self.opts obj = self.get_object(request, unquote(object_id)) if obj is None: raise Http404( _('%(name)s object with primary key %(key)r does ' 'not exist.') % { 'name': force_text(opts.verbose_name), 'key': escape(object_id) }) observations = obj.penguinobservation_set.filter(site=obj)[:10] # Define a set of videos to pass into the view on load. # All cameras, today's date. cams = obj.camera_set.all() initial_videos = Video.objects.filter(camera__in=cams, date=datetime.date.today()) context = { 'title': obj.name, 'select_date': SelectDateForm, 'initial_videos': initial_videos, 'recent_observations': observations } context.update(extra_context or {}) return super(SiteAdmin, self).detail_view(request, object_id, context)
def delete_view(self, request, object_id, extra_context=None): """ Overrides the default to enable redirecting to the directory view after deletion of a image. we need to fetch the object and find out who the parent is before super, because super will delete the object and make it impossible to find out the parent folder to redirect to. """ parent_folder = None try: obj = self.get_queryset(request).get(pk=unquote(object_id)) parent_folder = obj.folder except self.model.DoesNotExist: obj = None r = super(FileAdmin, self).delete_view( request=request, object_id=object_id, extra_context=extra_context) url = r.get("Location", None) # Check against filer_file_changelist as file deletion is always made by # the base class if (url in ["../../../../", "../../"] or url == reverse("admin:media_file_changelist") or url == reverse("admin:media_image_changelist")): if parent_folder: url = reverse('admin:filer-directory_listing', kwargs={'folder_id': parent_folder.id}) else: url = reverse('admin:filer-directory_listing-unfiled_images') url = "%s%s%s" % (url,popup_param(request), selectfolder_param(request,"&")) return HttpResponseRedirect(url) return r
def delete_view(self, request, object_id, extra_context=None): ''' Overrides the default to enable redirecting to the directory view after deletion of a folder. we need to fetch the object and find out who the parent is before super, because super will delete the object and make it impossible to find out the parent folder to redirect to. ''' parent_folder = None try: obj = self.queryset(request).get(pk=unquote(object_id)) parent_folder = obj.parent except self.model.DoesNotExist: obj = None r = super(FolderAdmin, self).delete_view(request=request, object_id=object_id, extra_context=extra_context) url = r.get("Location", None) if url in ["../../../../","../../"]: if parent_folder: url = reverse('admin:filer-directory_listing', kwargs={'folder_id': parent_folder.id}) else: url = reverse('admin:filer-directory_listing-root') return HttpResponseRedirect(url) return r
def category_view(self, request, prescription_id, category_name, extra_context=None): """ Wraps the change list with some extra category related information. """ opts = DocumentCategory._meta category_name = unquote(category_name.replace("_", " ")) try: category = DocumentCategory.objects.get(name__iexact=category_name) except DocumentCategory.DoesNotExist: raise Http404( _('%(name)s object with primary key %(key)r does not exist.') % { 'name': force_text(opts.verbose_name), 'key': escape(category_name) }) context = { "title": category.name, "tags": category.documenttag_set.all() } context.update(extra_context or {}) return self.changelist_view(request, prescription_id, context)
def change_view(self, request, object_id, extra_context=None): """ Wrap the change view to do permissions checking. """ if request.method == 'POST' and not request.user.is_superuser: if not self.has_publish_permission(request): # This check is less comprehensive than the following one, but # it requires no database lookup of the original object. if request.POST.get('status') == PUBLISHED_STATE: raise PermissionDenied(( "You do not have permission to publish %s objects " "or edit published objects." ) % self.model._meta.verbose_name) # Lookup the object pre-change and see if it was alreay # published. If so: permission denied. obj = self.get_object(request, unquote(object_id)) if obj.is_published(): raise PermissionDenied(( "You do not have permission to edit published %s" " objects." ) % self.model._meta.verbose_name) else: extra_context = extra_context or {} extra_context.update({ 'draft_copy_allowed': self.draft_copy_allowed, 'no_publish_perm': not self.has_publish_permission(request) }) return super(WorkflowAdmin, self).change_view(request, object_id, extra_context=extra_context )
def change_view(self, request, object_id, extra_context=None): item = self.get_object(request, unquote(object_id)) order = item.order OrderOpts = order._meta has_change_permission_for_order = request.user.has_perm( OrderOpts.app_label + '.' + OrderOpts.get_change_permission()) context = { 'OrderItem': item, 'Order': order, 'OrderOpts': OrderOpts, 'has_change_permission_for_order': has_change_permission_for_order, 'line_item': self.line_item(item) } context.update(extra_context or {}) response = super(OrderItemAdmin, self).change_view(request, object_id, extra_context=context) if isinstance(response, HttpResponseRedirect): if item: order = item.order to = reverse("admin:%s_%s_change" % (order._meta.app_label, order._meta.module_name), args=(order.pk, )) response = redirect(to) return response
def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} obj = self.get_object(request, unquote(object_id)) extra_context[ 'social_media_publication'] = obj.social_media_publications.all( ).order_by('-publish_at') extra_context['share_form'] = SocialMediaForm( initial={ 'content_type': ContentType.objects.get(app_label=self.opts.app_label, model=self.opts.model_name), 'object_id': object_id, 'link': 'http://' + settings.FACEBOOK_REDIRECT_DOMAIN + self.model.objects.get(pk=object_id).get_absolute_url() }) return super(SocialMediaMixin, self).change_view(request, object_id, form_url=form_url, extra_context=extra_context)
def delete_view(self, request, object_id, extra_context=None): if request.method == 'POST': # The user has already confirmed the deletion. opts = self.model._meta obj = self.get_object(request, unquote(object_id)) if not self.has_delete_permission(request, obj): raise PermissionDenied if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(opts.verbose_name), 'key': re.escape(object_id)}) using = router.db_for_write(self.model) # Populate deleted_objects, a data structure of all related objects that # will also be deleted. (deleted_objects, model_count, perms_needed, protected) = get_deleted_objects( [obj], opts, request.user, self.admin_site, using) if perms_needed: raise PermissionDenied obj_display = force_text(obj) self.log_deletion(request, obj, obj_display) self.delete_model(request, obj) self.message_user(request, _('The %(name)s "%(obj)s" was deleted successfully.') % {'name': force_text(opts.verbose_name), 'obj': force_text(obj_display)}) if not self.has_change_permission(request, None): return HttpResponseRedirect(reverse('admin:index', current_app=self.admin_site.name)) return HttpResponseRedirect("../../../") else: # Show confirmation page return super(MenuItemAdmin, self).delete_view(request, object_id, extra_context)
def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} obj = self.get_object(request, util.unquote(object_id)) ExtraForm = obj.project.extraform() try: extra_data = ast.literal_eval(obj.extradata) except SyntaxError: extra_data = {} if request.method == 'POST': extra_form = ExtraForm(request.POST) if extra_form.is_valid(): obj.extradata = extra_form.clean() obj.save() else: extra_form = ExtraForm(initial=extra_data) extra_context['extraform'] = extra_form return super(PledgeAdmin, self).change_view(request, object_id, form_url, extra_context=extra_context)
def __call__(self, request, url): ''' DEPRECATED!! More recent versions of Django use the get_urls method instead. Overriden to route extra URLs. ''' if url: if url.endswith('items/add'): return self.add_menu_item(request, unquote(url[:-10])) if url.endswith('items'): return HttpResponseRedirect('../') match = re.match('^(?P<menu_pk>[-\w]+)/items/(?P<menu_item_pk>[-\w]+)$', url) if match: return self.edit_menu_item(request, match.group('menu_pk'), match.group('menu_item_pk')) match = re.match('^(?P<menu_pk>[-\w]+)/items/(?P<menu_item_pk>[-\w]+)/delete$', url) if match: return self.delete_menu_item(request, match.group('menu_pk'), match.group('menu_item_pk')) match = re.match('^(?P<menu_pk>[-\w]+)/items/(?P<menu_item_pk>[-\w]+)/history$', url) if match: return self.history_menu_item(request, match.group('menu_pk'), match.group('menu_item_pk')) match = re.match('^(?P<menu_pk>[-\w]+)/items/(?P<menu_item_pk>[-\w]+)/move_up$', url) if match: return self.move_up_item(request, match.group('menu_pk'), match.group('menu_item_pk')) match = re.match('^(?P<menu_pk>[-\w]+)/items/(?P<menu_item_pk>[-\w]+)/move_down$', url) if match: return self.move_down_item(request, match.group('menu_pk'), match.group('menu_item_pk')) return super(MenuAdmin, self).__call__(request, url)
def detail_view(self, request, object_id, extra_context=None): opts = self.opts obj = self.get_object(request, unquote(object_id)) if not self.has_view_permission(request, obj): raise PermissionDenied if obj is None: raise Http404(_('%(name)s object with primary key %(key)r does ' 'not exist.') % { 'name': force_text(opts.verbose_name), 'key': escape(object_id)}) context = { 'title': _('Detail %s') % force_text(opts.verbose_name), 'object_id': object_id, 'original': obj, 'is_popup': "_popup" in request.REQUEST, 'media': self.media, 'app_label': opts.app_label, 'opts': opts, 'has_change_permission': self.has_change_permission(request, obj), } context.update(extra_context or {}) return TemplateResponse(request, self.detail_template or [ "admin/%s/%s/detail.html" % (opts.app_label, opts.object_name.lower()), "admin/%s/detail.html" % opts.app_label, "admin/detail.html" ], context, current_app=self.admin_site.name)
def change_view(self, request, object_id, extra_context=None): item = self.get_object(request, unquote(object_id)) order = item.order OrderOpts = order._meta has_change_permission_for_order = request.user.has_perm(OrderOpts.app_label + '.' + OrderOpts.get_change_permission()) context = { 'OrderItem': item, 'Order': order, 'OrderOpts': OrderOpts, 'has_change_permission_for_order': has_change_permission_for_order, 'line_item': self.line_item(item) } context.update(extra_context or {}) response = super(OrderItemAdmin, self).change_view(request, object_id, extra_context=context) if isinstance(response, HttpResponseRedirect): if item: order = item.order to = reverse("admin:%s_%s_change" % ( order._meta.app_label, order._meta.module_name ), args=(order.pk,) ) response = redirect(to) return response
def change_view(self, request, object_id, extra_context={}): obj = self.get_object(request, unquote(object_id)) extra_context['can_send'] = obj.can_send() request._pennyblack_job_obj = obj # add object to request for the mail inline return super(JobAdmin, self).change_view(request, object_id, extra_context=extra_context)
def delete_view(self, request, object_id, extra_context=None): """ Overrides the default to enable redirecting to the directory view after deletion of a image. we need to fetch the object and find out who the parent is before super, because super will delete the object and make it impossible to find out the parent folder to redirect to. """ parent_folder = None try: obj = self.get_queryset(request).get(pk=unquote(object_id)) parent_folder = obj.folder except self.model.DoesNotExist: obj = None r = super(FileAdmin, self).delete_view( request=request, object_id=object_id, extra_context=extra_context) url = r.get("Location", None) # Check against filer_file_changelist as file deletion is always made by # the base class if (url in ["../../../../", "../../"] or url == reverse("admin:filer_file_changelist") or url == reverse("admin:filer_image_changelist")): if parent_folder: url = reverse('admin:filer-directory_listing', kwargs={'folder_id': parent_folder.id}) else: url = reverse('admin:filer-directory_listing-unfiled_images') url = "%s%s%s" % (url,popup_param(request), selectfolder_param(request,"&")) return HttpResponseRedirect(url) return r
def change_view(self, request, object_id, form_url='', extra_context=None): """ Add InlineDevilryUserProfile to change form. """ self.inlines = [InlineDevilryUserProfile] if request.method == 'POST': if request.POST.get('dangerous_changes_cancel'): del request.session['before_confirm_request_data'] messages.add_message(request, messages.INFO, _('Save cancelled by user. Nothing was saved.')) urlname = '{site_name}:auth_user_change'.format(site_name=self.admin_site.name) return redirect(urlname, object_id) if request.POST.get('dangerous_changes_confirmed'): request.POST = request.session['before_confirm_request_data'] del request.session['before_confirm_request_data'] else: # Check if any dangerous attributes have been changed, and show confirm page if so try: obj, changed_dangerous_attributes = self._check_for_changes_to_dangerous_attributes(request, object_id) if changed_dangerous_attributes: return self._show_confirm_view(request, obj, changed_dangerous_attributes) except ValidationError: pass # Ignore errors, since they are handled in super.change_view() user_obj = self.get_object(request, unquote(object_id)) extra_extra_context = {'sysadmin_message': get_setting('DEVILRY_USERADMIN_USER_CHANGE_VIEW_MESSAGE', ''), 'user_obj': user_obj} if extra_context: extra_extra_context.update(extra_context) return super(UserAdmin, self).change_view(request, object_id, form_url, extra_extra_context)
def send_newsletter_view(self,request, object_id): obj = self.get_object(request, unquote(object_id)) if request.method == 'POST' and request.POST.has_key("_send"): obj.status = 11 obj.save() self.message_user(request, _("Newsletter has been marked for delivery.")) return HttpResponseRedirect(reverse('admin:%s_%s_changelist' %(self.model._meta.app_label, self.model._meta.module_name)))
def delete_view(self, request, object_id, extra_context=None): ''' copy from admin.ModelAdmin; adapted: do not checkl references: no cascading deletes; no confirmation.''' opts = self.model._meta app_label = opts.app_label try: obj = self.queryset(request).get(pk=unquote(object_id)) except self.model.DoesNotExist: obj = None if not self.has_delete_permission(request, obj): raise PermissionDenied if obj is None: raise Http404( _('%(name)s object with primary key %(key)r does not exist.') % { 'name': force_unicode(opts.verbose_name), 'key': escape(object_id) }) obj_display = force_unicode(obj) self.log_deletion(request, obj, obj_display) obj.delete() self.message_user( request, _('The %(name)s "%(obj)s" was deleted successfully.') % { 'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj_display) }) if not self.has_change_permission(request, None): return HttpResponseRedirect("../../../../") return HttpResponseRedirect("../../")
def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = extra_context or {} obj = self.get_object(request, util.unquote(object_id)) if not obj: raise Http404() ExtraForm = obj.project.extraform() try: extra_data = ast.literal_eval(obj.extradata) except SyntaxError: extra_data = {} if request.method == 'POST': extra_form = ExtraForm(request.POST) if extra_form.is_valid(): obj.extradata = extra_form.clean() obj.save() else: extra_form = ExtraForm(initial=extra_data) extra_context['extraform'] = extra_form return super(PledgeAdmin, self).change_view(request, object_id, form_url, extra_context=extra_context)
def _toggle_boolean(self, request): """ Handle an AJAX toggle_boolean request """ self._collect_editable_booleans() item_id = request.POST.get('item_id') attr = request.POST.get('attr') if not self._ajax_editable_booleans.has_key(attr): return HttpResponseBadRequest("not a valid attribute %s" % attr) try: obj = self.model._default_manager.get(pk=unquote(item_id)) attr = str(attr) before_data = self._ajax_editable_booleans[attr](self, obj) setattr(obj, attr, not getattr(obj, attr)) obj.save() self._refresh_changelist_caches() # ???: Perhaps better a post_save signal? # Construct html snippets to send back to client for status update data = self._ajax_editable_booleans[attr](self, obj) except Exception, e: return HttpResponse("FAILED " + unicode(e), mimetype="text/plain")
def detail_view(self, request, object_id, extra_context=None): opts = self.opts obj = self.get_object(request, unquote(object_id)) obj.views += 1 obj.save() if not self.has_view_permission(request, obj): raise PermissionDenied if obj is None: raise Http404( _('%(name)s object with primary key %(key)r does ' 'not exist.') % { 'name': force_text(opts.verbose_name), 'key': escape(object_id) }) observations = obj.camera.penguinobservation_set.filter( observer=request.user, date__range=(datetime.datetime.combine(obj.date, obj.start_time), datetime.datetime.combine(obj.date, obj.end_time))) context = {'title': "View video", 'user_observations': observations} context.update(extra_context or {}) return super(VideoAdmin, self).detail_view(request, object_id, context)