Ejemplo n.º 1
0
Archivo: admin.py Proyecto: boar/boar
    def merge_user_view(self, request):
        if request.method == 'POST':
            form = MergeUserForm(request.POST)
            if form.is_valid():
                user = form.cleaned_data['user']
                for victim in form.cleaned_data['victims']:
                    # Simple stuff
                    for group in victim.groups.all():
                        if group not in user.groups.all():
                            user.groups.add(group)
                    if victim.email and not user.email:
                        user.email = victim.email
                    if victim.is_staff and not user.is_staff:
                        user.is_staff = True
                    if victim.is_superuser and not user.is_superuser:
                        user.is_superuser = True
                    if victim.is_active and not user.is_active:
                        user.is_active = True

                    # Transfer profile if user merging into doesn't have profile
                    # but victim does
                    try:
                        profile = user.get_profile()
                    except UserProfile.DoesNotExist:
                        try:
                            profile = victim.get_profile()
                        except UserProfile.DoesNotExist:
                            pass
                        else:
                            profile.user = user
                            profile.save()
                    try:
                        profile = user.facebookprofile
                    except FacebookProfile.DoesNotExist:
                        try:
                            profile = victim.facebookprofile
                        except FacebookProfile.DoesNotExist:
                            pass
                        else:
                            profile.user = user
                            profile.save()
                    # Articles
                    for a in Article.objects.filter(authors=victim):
                        a.authors.remove(victim)
                        if not a.authors.filter(pk=user.pk):
                            a.authors.add(user)
                        a.save()
                    Image.objects.filter(author=victim).update(author=user)
                    LogEntry.objects.filter(user=victim).update(user=user)
                    Cartoon.objects.filter(author=victim).update(author=user)
                    # Mailing lists
                    for ml in MailingList.objects.filter(subscribers=victim):
                        ml.subscribers.remove(victim)
                        if not ml.subscribers.filter(pk=user.pk):
                            ml.subscribers.add(user)
                        ml.save()
                    Comment.objects.filter(user=victim).update(user=user)

                    User.objects.get(pk=victim.pk).delete()
                user.save()
                self.message_user(
                    request, "Users successfully merged into %s." %
                    form.cleaned_data['user'].username)
                return HttpResponseRedirect('../')
        elif 'victims' in request.GET:
            form = MergeUserForm(
                initial={'victims': request.GET['victims'].split(',')})
        else:
            return HttpResponseRedirect('../')
        return render_to_response(
            'admin/auth/merge_user_form.html', {
                'title': _('Merge users'),
                'form': form,
                'is_popup': '_popup' in request.REQUEST,
                'add': True,
                'change': False,
                'has_add_permission': True,
                'has_delete_permission': False,
                'has_change_permission': True,
                'has_file_field': False,
                'has_absolute_url': False,
                'auto_populated_fields': (),
                'opts': self.model._meta,
                'save_as': False,
                'root_path': self.admin_site.root_path,
                'app_label': self.model._meta.app_label,
            },
            context_instance=template.RequestContext(request))
Ejemplo n.º 2
0
    def _frontend_editing_view(self, request, cms_id, content_type,
                               content_id):
        """
        This view is used strictly for frontend editing -- it is not used
        inside the standard administration interface.

        The code in feincms/templates/admin/feincms/fe_tools.html knows how to
        call this view correctly.
        """

        try:
            model_cls = loading.get_model(self.model._meta.app_label,
                                          content_type)
            obj = model_cls.objects.get(parent=cms_id, id=content_id)
        except:
            raise Http404()

        form_class_base = getattr(model_cls, 'feincms_item_editor_form',
                                  ItemEditorForm)

        ModelForm = modelform_factory(model_cls,
                                      exclude=('parent', 'region', 'ordering'),
                                      form=form_class_base,
                                      formfield_callback=curry(
                                          self.formfield_for_dbfield,
                                          request=request))

        # we do not want to edit these two fields in the frontend editing mode;
        # we are strictly editing single content blocks there.  We have to
        # remove them from the form because we explicitly redefined them in the
        # ItemEditorForm definition above. Just using exclude is not enough.
        del ModelForm.base_fields['region']
        del ModelForm.base_fields['ordering']

        if request.method == 'POST':
            # The prefix is used to replace the formset identifier from the
            # ItemEditor interface. Customization of the form is easily
            # possible through either matching the prefix (frontend editing) or
            # the formset identifier (ItemEditor) as it is done in the richtext
            # and mediafile init.html item editor includes.
            form = ModelForm(request.POST, instance=obj, prefix=content_type)

            if form.is_valid():
                obj = form.save()

                return render_to_response(
                    'admin/feincms/fe_editor_done.html', {
                        'content':
                        obj.render(request=request),
                        'identifier':
                        obj.fe_identifier(),
                        'FEINCMS_JQUERY_NO_CONFLICT':
                        settings.FEINCMS_JQUERY_NO_CONFLICT,
                    },
                    context_instance=template.RequestContext(request))
        else:
            form = ModelForm(instance=obj, prefix=content_type)

        context = self.get_extra_context(request)
        context.update({
            'frontend_editing':
            True,
            'title':
            _('Change %s') % force_text(model_cls._meta.verbose_name),
            'object':
            obj,
            'form':
            form,
            'is_popup':
            True,
            'media':
            self.media,
        })

        return render_to_response(
            'admin/feincms/fe_editor.html',
            context,
            context_instance=template.RequestContext(request))
Ejemplo n.º 3
0
def _delete_selected(modeladmin, request, queryset):
    """
    Default action which deletes the selected objects.

    This action first displays a confirmation page whichs shows all the
    deleteable objects, or, if the user has no permission one of the related
    childs (foreignkeys), a "permission denied" message.

    Next, it delets all selected objects and redirects back to the change list.
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied

    using = router.db_for_write(modeladmin.model)

    # Populate deletable_objects, a data structure of all related objects that
    # will also be deleted.
    # TODO: Permissions would be so cool...
    deletable_objects, perms_needed, protected = get_deleted_objects(
        queryset, opts, request.user, modeladmin.admin_site, using)

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        if perms_needed:
            raise PermissionDenied
        n = len(queryset)
        if n:
            for obj in queryset:
                obj_display = force_text(obj)
                modeladmin.log_deletion(request, obj, obj_display)
                # call the objects delete method to ensure signals are
                # processed.
                obj.delete()
            # This is what you get if you have to monkey patch every object in a changelist
            # No queryset object, I can tell ya. So we get a new one and delete that.
            #pk_list = [o.pk for o in queryset]
            #klass = queryset[0].__class__
            #qs = klass.objects.filter(pk__in=pk_list)
            #qs.delete()
            modeladmin.message_user(request, _("Successfully deleted %(count)d %(items)s.") % {
                "count": n, "items": model_ngettext(modeladmin.opts, n)
            })
        # Return None to display the change list page again.
        return None

    if len(queryset) == 1:
        objects_name = force_text(opts.verbose_name)
    else:
        objects_name = force_text(opts.verbose_name_plural)

    if perms_needed or protected:
        title = _("Cannot delete %(name)s") % {"name": objects_name}
    else:
        title = _("Are you sure?")

    context = {
        "title": title,
        "objects_name": objects_name,
        "deletable_objects": [deletable_objects],
        'queryset': queryset,
        "perms_lacking": perms_needed,
        "protected": protected,
        "opts": opts,
        "root_path": modeladmin.admin_site.root_path,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return render_to_response(modeladmin.delete_selected_confirmation_template or [
        "admin/%s/%s/delete_selected_confirmation.html" % (app_label, opts.object_name.lower()),
        "admin/%s/delete_selected_confirmation.html" % app_label,
        "admin/delete_selected_confirmation.html"
    ], context, context_instance=template.RequestContext(request))
Ejemplo n.º 4
0
                assert form_data['user_id'] == apply_job.user_id and form_data[
                    'job_id'] == apply_job.job_id
            except Apply_job.DoesNotExist, AssertionError:
                return render_to_response('message.html',
                                          {'msg_subject': u'数据错误,提交失败'})
            del form_data['key_id']
            feedback = Feedback(send_date=datetime.date.today(), **form_data)
            feedback.save()
            apply_job.feedback_id = feedback.id
            apply_job.save()
            return render_to_response('message.html', {'msg_subject': u'提交成功'})
        else:
            form_action_path = '/job/feedback/'
            t = template.loader.get_template('repost.html')
            c = template.RequestContext(request, {
                'form_action_path': form_action_path,
                'form': form
            })
            html = t.render(c)
            return HttpResponse(html)


@login_required
def read_feedback(request, offset):
    user_id = request.session['_auth_user_id']
    if request.method == 'GET':
        try:
            feedback = Feedback.objects.get(id=offset, user_id=user_id)
        except Feedback.DoesNotExist:
            return render_to_response('message.html',
                                      {'msg_subject': u'无此回执信息'})
        feedback.is_read = True
Ejemplo n.º 5
0
    def merge_view(self, request, object_id, extra_context=None):
        """
        The 'merge' admin view for this model. Allows a user to merge a draft
        copy back over the original.
        """
        opts = self.model._meta
        app_label = opts.app_label

        obj = self.get_object(request, unquote(object_id))

        # For our purposes, permission to merge is equivalent to
        # has_change_permisison and has_delete_permission.
        if not self.has_change_permission(request, obj) \
            or 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)
                })

        if not obj.is_draft_copy:
            return HttpResponseBadRequest(
                _('The %s object could not be merged because it is not a'
                  'draft copy. There is nothing to merge it into.') %
                force_unicode(opts.verbose_name))

        # Populate deleted_objects, a data structure of all related objects
        # that will also be deleted when this copy is deleted.
        all_objects = introspect.get_referencing_objects(obj.copy_of)
        all_objects.insert(0, obj.copy_of)
        using = router.db_for_write(self.model)
        (deleted_objects, perms_needed,
         protected) = get_deleted_objects(all_objects, opts, request.user,
                                          self.admin_site, using)
        # Flatten nested list:
        deleted_objects = map(lambda i: hasattr(i, '__iter__') and i or [i],
                              deleted_objects)
        deleted_objects = chain(*deleted_objects)
        deleted_objects = list(deleted_objects)
        # ``get_deleted_objects`` is zealous and will add the draft copy to
        # the list of things to be deleted. This needs to be removed.
        obj_url = reverse("admin:pagemanager_page_change", args=(obj.pk, ))
        deleted_objects = filter(lambda link: obj_url not in link,
                                 deleted_objects)
        # Filter out child pages: these will be preserved too.
        for child in obj.copy_of.children.all():
            child_url = reverse("admin:pagemanager_page_change",
                                args=(child.pk, ))
            deleted_objects = filter(lambda link: child_url not in link,
                                     deleted_objects)
        # Populate replacing_objects, a data structure of all related objects
        # that will be replacing the originals.
        replacing_objects = introspect.get_referencing_objects(obj)
        replacing_objects.insert(0, obj)
        (replacing_objects, perms_needed,
         protected) = get_deleted_objects(replacing_objects, opts,
                                          request.user, self.admin_site, using)
        # Flatten nested list:
        replacing_objects = map(lambda i: hasattr(i, '__iter__') and i or [i],
                                replacing_objects)
        replacing_objects = chain(*replacing_objects)
        replacing_objects = list(replacing_objects)

        if request.POST:  # The user has already confirmed the merge.
            if perms_needed:
                raise PermissionDenied
            obj_display = force_unicode(obj) + " merged."
            self.log_change(request, obj, obj_display)

            original = obj.copy_of
            original_pk = original.pk
            original_layout_pk = original.page_layout.pk
            self._merge_item(original, obj)
            # Look up admin log entries for the old object and reassign them
            # to the new object.
            page_ctype = ContentType.objects.get_for_model(original)
            layout_ctype = ContentType.objects.get_for_model(
                original.page_layout)
            LogEntry.objects.filter(
                content_type=page_ctype,
                object_id=original_pk).update(object_id=obj.pk)
            LogEntry.objects.filter(content_type=layout_ctype,
                                    object_id=original_layout_pk).update(
                                        object_id=obj.page_layout.pk)
            self.message_user(
                request,
                _('The %(name)s "%(obj)s" was merged successfully.') % {
                    'name': force_unicode(opts.verbose_name),
                    'obj': force_unicode(obj_display)
                })
            redirect_url = reverse("admin:pagemanager_page_change",
                                   args=(original.pk, ))
            return HttpResponseRedirect(redirect_url)

        context = {
            "title": _("Are you sure?"),
            "object_name": force_unicode(opts.verbose_name),
            "object": obj,
            "escaped_original": force_unicode(obj.copy_of),
            "deleted_objects": deleted_objects,
            "replacing_objects": replacing_objects,
            "perms_lacking": perms_needed,
            "opts": opts,
            "root_path": self.admin_site.root_path,
            "app_label": app_label,
        }
        context.update(extra_context or {})
        context_instance = template.RequestContext(
            request, current_app=self.admin_site.name)
        return render_to_response(self.merge_form_template,
                                  context,
                                  context_instance=context_instance)
Ejemplo n.º 6
0
 def render(self):
     """Renders the step."""
     step_template = template.loader.get_template(self.template_name)
     extra_context = {"form": self.action, "step": self}
     context = template.RequestContext(self.workflow.request, extra_context)
     return step_template.render(context)
Ejemplo n.º 7
0
    def index(self, request, extra_context=None):
        """
        Displays the main admin index page, which lists all of the installed
        apps that have been registered in this site.
        """
        app_dict = {}
        user = request.user
        for model, model_admin in self._registry.items():
            try:
                app_label = model._meta.app_label
            except AttributeError:
                app_label = model_admin.opts.app_label
            has_module_perms = user.has_module_perms(app_label)

            if has_module_perms:
                perms = model_admin.get_model_perms(request)

                # Check whether user has any perm for this module.
                # If so, add the module to the model_list.
                if True in perms.values():
                    try:
                        name = capfirst(model._meta.verbose_name_plural)
                    except AttributeError:
                        name = capfirst(model_admin.opts.verbose_name_plural)
                    model_dict = {
                        'name':
                        name,
                        'admin_url':
                        mark_safe('%s/%s/' %
                                  (app_label, model.__name__.lower())),
                        'perms':
                        perms,
                    }
                    if app_label in app_dict:
                        app_dict[app_label]['models'].append(model_dict)
                    else:
                        app_dict[app_label] = {
                            'name': app_label.title(),
                            'app_url': app_label + '/',
                            'has_module_perms': has_module_perms,
                            'models': [model_dict],
                        }

        # Sort the apps alphabetically.
        app_list = app_dict.values()
        sorted(app_list, key=lambda x: x['name'])

        # Sort the models alphabetically within each app.
        for app in app_list:
            app['models'].sort(key=lambda x: x['name'])

        context = {
            'title': _('Site administration'),
            'app_list': app_list,
            'root_path': self.root_path,
        }
        context.update(extra_context or {})
        context_instance = template.RequestContext(request,
                                                   current_app=self.name)
        return render_to_response(self.index_template or 'admin/index.html',
                                  context,
                                  context_instance=context_instance)
Ejemplo n.º 8
0
    def display_view(self, request, object_id, extra_context=None):

        opts = self.model._meta
        app_label = opts.app_label
        media = self.media

        try:
            obj = self.model._default_manager.get(pk=object_id)
        except:
            raise Http404

        ModelForm = self.get_form(request, obj)
        formsets = []

        form = ModelForm(instance=obj)
        prefixes = {}
        for FormSet, inline in zip(self.get_formsets(request, obj),
                                   self.inline_instances):
            prefix = FormSet.get_default_prefix()
            prefixes[prefix] = prefixes.get(prefix, 0) + 1
            if prefixes[prefix] != 1:
                prefix = "%s-%s" % (prefix, prefixes[prefix])
            formset = FormSet(instance=obj,
                              prefix=prefix,
                              queryset=inline.queryset(request))
            formsets.append(formset)

        adminForm = helpers.AdminForm(form,
                                      self.get_fieldsets(request, obj),
                                      self.prepopulated_fields,
                                      self.get_readonly_fields(request, obj),
                                      model_admin=self)
        media = self.media + adminForm.media

        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              readonly,
                                                              model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media

        context = {
            'title': _('View %s') % (obj),
            'opts': opts,
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': "_popup" in request.REQUEST,
            'media': mark_safe(media),
            'inline_admin_formsets': inline_admin_formsets,
            'has_change_permission': self.has_change_permission(request),
            'root_path': self.admin_site.root_path,
            'app_label': opts.app_label,
        }

        context.update(extra_context or {})
        context_instance = template.RequestContext(
            request, current_app=self.admin_site.name)
        return render_to_response(self.change_list_template or [
            'admin/%s/%s/view_form.html' %
            (app_label, opts.object_name.lower()),
            'admin/%s/view_form.html' % app_label, 'admin/view_form.html'
        ],
                                  context,
                                  context_instance=context_instance)
Ejemplo n.º 9
0
    def upload_xml(self, request, extra_context=None):
        """
        Allows to upload a resource description into the Django database.
        """
        # Check if the current user is actually allowed to upload...
        if not request.user.is_superuser and not request.user.has_perm(
                'repository.add_resourceinfotype_model'):
            raise PermissionDenied

        if request.method == 'POST':
            form = ResourceDescriptionUploadForm(request.POST, request.FILES)
            if form.is_valid():
                # Retrieve the upload resource description file.
                description = request.FILES['description']
                from metashare.xml_utils import import_from_file
                successes, failures = \
                  import_from_file(description, description.name, INTERNAL, MASTER, request.user.id)

                if len(successes) == 1 and len(
                        failures
                ) == 0:  # single resource successfully uploaded
                    resource_object = successes[0]
                    # Construct redirect URL for the new object.
                    redirect_url = reverse(
                        'editor:repository_resourceinfotype_model_change',
                        args=[resource_object.id])
                    messages.info(
                        request, u'Successfully uploaded file: {}'.format(
                            description.name))
                else:
                    # Default case: either at least one failure, or more than one success
                    # We will redirect to upload page if we have no successes at all,
                    # or to "my resources" if there is at least one success
                    redirect_url = reverse('editor:upload_xml')
                    if len(successes) > 0:
                        redirect_url = reverse(
                            'editor:repository_resourceinfotype_model_myresources'
                        )
                        messages.info(
                            request,
                            u'Successfully uploaded {} resource descriptions'.
                            format(len(successes)))
                    if len(failures) > 0:
                        _msg = u'Import failed for {} files:\n'.format(
                            len(failures))
                        for descriptor, exception in failures:
                            _msg += u'\t{}: '.format(descriptor)
                            if isinstance(exception.args, tuple):
                                _msg += u'{}\n'.format(' '.join(
                                    [str(a) for a in exception.args]))
                            else:
                                _msg += u'{}\n'.format(exception.args)
                        messages.error(request, _msg)
                return HttpResponseRedirect(redirect_url)
        else:  # not a POST request
            form = ResourceDescriptionUploadForm()

        context = {
            'title': _('Upload new resource description(s)'),
            'form': form,
            'form_url': request.path,
            'root_path': self.root_path,
        }
        context.update(extra_context or {})
        context_instance = template.RequestContext(request,
                                                   current_app=self.name)
        return render_to_response([
            'admin/repository/resourceinfotype_model/upload_description.html'
        ], context, context_instance)
Ejemplo n.º 10
0
 def render(self):
     """ Renders the table using the template from the table options. """
     table_template = template.loader.get_template(self._meta.template)
     extra_context = {self._meta.context_var_name: self}
     context = template.RequestContext(self._meta.request, extra_context)
     return table_template.render(context)
Ejemplo n.º 11
0
    def render_change_form(self,
                           request,
                           context,
                           add=False,
                           change=False,
                           form_url='',
                           obj=None,
                           has_file_field=True):
        opts = self.model._meta
        app_label = opts.app_label
        ordered_objects = opts.get_ordered_objects()

        if has_file_field:
            if not form_url:
                form_url = request.get_full_path()
            form_url, upload_data = prepare_upload(request, form_url)
            context.update({
                'file_upload_data':
                self.get_filetransfer_data(upload_data),
            })
        context.update({
            'add':
            add,
            'change':
            change,
            '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':
            has_file_field,
            'has_absolute_url':
            hasattr(self.model, 'get_absolute_url'),
            'ordered_objects':
            ordered_objects,
            'form_url':
            mark_safe(form_url),
            'opts':
            opts,
            'content_type_id':
            ContentType.objects.get_for_model(self.model).id,
            'save_as':
            self.save_as,
            'save_on_top':
            self.save_on_top,
            'root_path':
            self.admin_site.root_path,
        })
        if add and self.add_form_template is not None:
            form_template = self.add_form_template
        else:
            form_template = self.change_form_template
        context_instance = template.RequestContext(
            request, current_app=self.admin_site.name)
        return render_to_response(form_template or [
            "admin/%s/%s/change_form.html" %
            (app_label, opts.object_name.lower()),
            "admin/%s/change_form.html" % app_label, "admin/change_form.html"
        ],
                                  context,
                                  context_instance=context_instance)
Ejemplo n.º 12
0
    def changelist_view(self, request, extra_context=None):
        "The 'change list' admin view for this model."
        from feeddb.feed.extension.changelist import FeedChangeList
        opts = self.model._meta
        app_label = opts.app_label
        #if not self.has_change_permission(request, None):
        #    raise PermissionDenied
        # Check actions to see if any are available on this changelist
        actions = self.get_actions(request)
        # Remove action checkboxes if there aren't any actions available.
        list_display = list(self.list_display)
        if not actions:
            try:
                list_display.remove('action_checkbox')
            except ValueError:
                pass
        try:
            cl = FeedChangeList(request, self.model, list_display,
                                self.list_display_links, self.list_filter,
                                self.date_hierarchy, self.search_fields,
                                self.list_select_related, self.list_per_page,
                                self.list_max_show_all, self.list_editable,
                                self)
        except IncorrectLookupParameters:
            # Wacky lookup parameters were given, so redirect to the main
            # changelist page, without parameters, and pass an 'invalid=1'
            # parameter via the query string. If wacky parameters were given and
            # the 'invalid=1' parameter was already in the query string, something
            # is screwed up with the database, so display an error page.
            if ERROR_FLAG in request.GET.keys():
                return render_to_response('admin/invalid_setup.html',
                                          {'title': _('Database error')})
            return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')
        # If the request was POSTed, this might be a bulk action or a bulk edit.
        # Try to look up an action first, but if this isn't an action the POST
        # will fall through to the bulk edit check, below.
        if actions and request.method == 'POST':
            response = self.response_action(request,
                                            queryset=cl.get_query_set())
            if response:
                return response
        # If we're allowing changelist editing, we need to construct a formset
        # for the changelist given all the fields to be edited. Then we'll
        # use the formset to validate/process POSTed data.
        formset = cl.formset = None
        # Handle POSTed bulk-edit data.
        if request.method == "POST" and self.list_editable:
            FormSet = self.get_changelist_formset(request)
            formset = cl.formset = FormSet(request.POST,
                                           request.FILES,
                                           queryset=cl.result_list)
            if formset.is_valid():
                changecount = 0
                for form in formset.forms:
                    if form.has_changed():
                        obj = self.save_form(request, form, change=True)
                        self.save_model(request, obj, form, change=True)
                        form.save_m2m()
                        change_msg = self.construct_change_message(
                            request, form, None)
                        self.log_change(request, obj, change_msg)
                        changecount += 1
                if changecount:
                    if changecount == 1:
                        name = force_unicode(opts.verbose_name)
                    else:
                        name = force_unicode(opts.verbose_name_plural)
                    msg = ungettext(
                        "%(count)s %(name)s was changed successfully.",
                        "%(count)s %(name)s were changed successfully.",
                        changecount) % {
                            'count': changecount,
                            'name': name,
                            'obj': force_unicode(obj)
                        }
                    self.message_user(request, msg)
                return HttpResponseRedirect(request.get_full_path())
        # Handle GET -- construct a formset for display.
        elif self.list_editable:
            FormSet = self.get_changelist_formset(request)
            formset = cl.formset = FormSet(queryset=cl.result_list)
        # Build the list of media to be used by the formset.
        if formset:
            media = self.media + formset.media
        else:
            media = self.media
        # Build the action form and populate it with available actions.
        if actions:
            action_form = self.action_form(auto_id=None)
            action_form.fields['action'].choices = self.get_action_choices(
                request)
        else:
            action_form = None

        context = {
            'title': cl.title,
            'is_popup': cl.is_popup,
            'cl': cl,
            'media': media,
            'has_add_permission': self.has_add_permission(request),
            'has_change_permission': self.has_change_permission(request, None),
            'root_path': reverse('admin:index'),
            'app_label': app_label,
            'action_form': action_form,
            'actions_on_top': self.actions_on_top,
            'actions_on_bottom': self.actions_on_bottom,
            'change': False,
            'add': False,
            'view': True,
        }
        context.update(extra_context or {})
        context_instance = template.RequestContext(
            request, current_app=self.admin_site.name)

        return render_to_response(self.change_list_template or [
            'admin/%s/%s/change_list.html' %
            (app_label, opts.object_name.lower()),
            'admin/%s/change_list.html' % app_label, 'admin/change_list.html'
        ],
                                  context,
                                  context_instance=context_instance)
Ejemplo n.º 13
0
def publish_selected(modeladmin, request, queryset):
    with transaction.atomic():
        queryset = queryset.select_for_update()
        opts = modeladmin.model._meta
        app_label = opts.app_label

        all_published = NestedSet()
        for obj in queryset:
            obj.publish(dry_run=True, all_published=all_published)

        perms_needed = []
        _check_permissions(modeladmin, all_published, request, perms_needed)

        if request.POST.get('post'):
            if perms_needed:
                raise PermissionDenied

            n = queryset.count()
            if n:
                for object in all_published:
                    modeladmin.log_publication(request, object)

                queryset.publish()

                modeladmin.message_user(
                    request,
                    _("Successfully published %(count)d %(items)s.") % {
                        "count": n,
                        "items": model_ngettext(modeladmin.opts, n)
                    })
                # Return None to display the change list page again.
                return None

        admin_site = modeladmin.admin_site

        context = {
            "title":
            _("Publish?"),
            "object_name":
            force_unicode(opts.verbose_name),
            "all_published":
            _convert_all_published_to_html(admin_site, all_published),
            "perms_lacking":
            _to_html(admin_site, perms_needed),
            'queryset':
            queryset,
            "opts":
            opts,
            "root_path":
            _root_path(admin_site),
            "app_label":
            app_label,
            'action_checkbox_name':
            helpers.ACTION_CHECKBOX_NAME,
        }

        # Display the confirmation page
        return render_to_response(
            modeladmin.publish_confirmation_template or [
                "admin/%s/%s/publish_selected_confirmation.html" %
                (app_label, opts.object_name.lower()),
                "admin/%s/publish_selected_confirmation.html" % app_label,
                "admin/publish_selected_confirmation.html"
            ],
            context,
            context_instance=template.RequestContext(request))
Ejemplo n.º 14
0
def test(request):
    ctx = template.RequestContext(request, request.GET)

    return render_to_response("test.html", ctx)
Ejemplo n.º 15
0
    def change_view(self, request, object_id, form_url='', extra_context=None):
        """
        The 'change' admin view for this model.
        This follows closely the base implementation from Django 1.4's
        django.contrib.admin.options.ModelAdmin,
        with the explicitly marked modifications.
        """
        # pylint: disable-msg=C0103
        model = self.model
        opts = model._meta

        obj = self.get_object(request, unquote(object_id))

        if not self.has_change_permission(request, obj):
            raise PermissionDenied

        #### begin modification ####
        # make sure that the user has a full session length time for the current
        # edit activity
        request.session.set_expiry(settings.SESSION_COOKIE_AGE)
        #### end modification ####

        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=reverse('admin:%s_%s_add' %
                                 (opts.app_label, opts.module_name),
                                 current_app=self.admin_site.name))

        ModelForm = self.get_form(request, obj)
        formsets = []
        inline_instances = self.get_inline_instances(request)
        if request.method == 'POST':
            form = ModelForm(request.POST, request.FILES, instance=obj)
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
            else:
                form_validated = False
                new_object = obj
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, new_object),
                                       inline_instances):
                #### begin modification ####
                if getattr(FormSet, 'parent_fk_name', None) in self.no_inlines:
                    continue
                #### end modification ####
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(request.POST,
                                  request.FILES,
                                  instance=new_object,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                #### begin modification ####
                if prefix in self.model.get_fields()['required']:
                    self.set_required_formset(formset)
                #### end modification ####

                formsets.append(formset)

            if all_valid(formsets) and form_validated:
                #### begin modification ####
                for formset in formsets:
                    # this replaces the call to self.save_formsets()
                    changes = formset.save()
                    # if there are any changes in the current inline and if this
                    # inline is a reverse inline, then we need to manually make
                    # sure that the inline data is connected to the parent
                    # object:
                    if changes:
                        parent_fk_name = getattr(formset, 'parent_fk_name', '')
                        if parent_fk_name:
                            assert len(changes) == 1
                            setattr(new_object, parent_fk_name, changes[0])
                    # If we have deleted a one-to-one inline, we must manually unset the field value.
                    if formset.deleted_objects:
                        parent_fk_name = getattr(formset, 'parent_fk_name', '')
                        if parent_fk_name:
                            setattr(new_object, parent_fk_name, None)

                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                # for resource info, explicitly write its metadata XML and
                # storage object to the storage folder
                if self.model.__schema_name__ == "resourceInfo":
                    new_object.storage_object.update_storage()
                #### end modification ####

                change_message = self.construct_change_message(
                    request, form, formsets)
                self.log_change(request, new_object, change_message)
                return self.response_change(request, new_object)

        else:
            form = ModelForm(instance=obj)
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, obj),
                                       inline_instances):
                #### begin modification ####
                if getattr(FormSet, 'parent_fk_name', None) in self.no_inlines:
                    continue
                #### end modification ####
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1 or not prefix:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                formsets.append(formset)

        #### begin modification ####
        media = self.media or []
        #### end modification ####
        inline_admin_formsets = []
        for inline, formset in zip(inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            prepopulated = dict(inline.get_prepopulated_fields(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              prepopulated,
                                                              readonly,
                                                              model_admin=self)
            #### begin modification ####
            self.add_lang_templ_params(inline_admin_formset)
            #### end modification ####
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
        #### begin modification ####
        adminForm = OrderedAdminForm(
            form,
            self.get_fieldsets_with_inlines(request, obj),
            self.get_prepopulated_fields(request, obj),
            self.get_readonly_fields(request, obj),
            model_admin=self,
            inlines=inline_admin_formsets)
        media = media + adminForm.media
        #### end modification ####

        context = {
            'title': _('Change %s') % force_unicode(opts.verbose_name),
            'adminform': adminForm,
            'object_id': object_id,
            'original': obj,
            'is_popup': "_popup" in request.REQUEST or \
                        "_popup_o2m" in request.REQUEST,
            'media': media,
            'inline_admin_formsets': inline_admin_formsets,
            'errors': helpers.AdminErrorList(form, formsets),
            'app_label': opts.app_label,
            'kb_link': settings.KNOWLEDGE_BASE_URL,
            'comp_name': _('%s') % force_unicode(opts.verbose_name),
        }
        context.update(extra_context or {})

        #### begin modification ####
        # redirection for reusable entities which are no master copies:
        if hasattr(obj, 'copy_status') and obj.copy_status != MASTER:
            context['url'] = obj.source_url
            context_instance = template.RequestContext(
                request, current_app=self.admin_site.name)
            return render_to_response('admin/repository/cannot_edit.html',
                                      context,
                                      context_instance=context_instance)
        # redirection for resources and their parts which are no master copies:
        else:
            for res in [
                    r for r in get_root_resources(obj)
                    if not r.storage_object.master_copy
            ]:
                context['redirection_url'] = model_utils.get_lr_master_url(res)
                context['resource'] = res
                context_instance = template.RequestContext(
                    request, current_app=self.admin_site.name)
                return render_to_response('admin/repository/cannot_edit.html',
                                          context,
                                          context_instance=context_instance)
        #### end modification ####

        return self.render_change_form(request,
                                       context,
                                       change=True,
                                       obj=obj,
                                       form_url=form_url)
Ejemplo n.º 16
0
 def render(self):
     context = template.RequestContext(self.request)
     return render_to_string(self.get_template_name(self.request),
                             self.data,
                             context_instance=context)
Ejemplo n.º 17
0
def AccessDenied(request):
    """Returns a 403 response."""
    context = template.RequestContext(request)
    resp = shortcuts.render_to_response('403.html', context_instance=context)
    resp.status_code = 403
    return resp
Ejemplo n.º 18
0
            if request.user:
                token = securityservice.SecurityService.generate_user_token(
                    request.user)

            if not token:
                request.errors = 'Invalid username or password'
            else:
                request.errors = 'Login successful'
        except Exception, e:
            logging.error(str(e))
            request.errors = 'Failed to login'

    #if request.user:
    #  return http.HttpResponseRedirect('/login/logout')

    c = template.RequestContext(request, locals())
    t = loader.get_template('login/login.html')
    response = http.HttpResponse(t.render(c))
    if token:
        utils.set_cookie(response, 'token', token)
    return response


def login_logout(request):
    token = utils.get_request_value(request, 'token')
    if token:
        securityservice.SecurityService.logoff_user_token(token)

    c = template.RequestContext(request, locals())
    t = loader.get_template('login/logout.html')
Ejemplo n.º 19
0
        mimetype = "text/csv"
    else:
        template_name = 'syspanel/instances/tenant_usage.html'
        mimetype = "text/html"

    return render_to_response(
        template_name, {
            'dateform': dateform,
            'datetime_start': datetime_start,
            'datetime_end': datetime_end,
            'usage': usage,
            'csv_link': _csv_usage_link(date_start),
            'instances': running_instances + terminated_instances,
            'tenant_id': tenant_id,
        },
        context_instance=template.RequestContext(request),
        mimetype=mimetype)


def index(request):
    for f in (TerminateInstance, RebootInstance):
        form, handled = f.maybe_handle(request)
        if handled:
            return handled

    instances = []
    try:
        instances = api.admin_server_list(request)
    except Exception as e:
        LOG.exception('Unspecified error in instance index')
        if not hasattr(e, 'message'):
Ejemplo n.º 20
0
def Poll(request, document_id):
    """Displays static webpage on Android phones and web player on others."""
    data = {'android': _IsAndroid(request), 'document_id': document_id}
    context = template.RequestContext(request, data)
    return shortcuts.render_to_response('poll.html', context)
Ejemplo n.º 21
0
    def changelist_view(self, request, parent_id, extra_context=None):
        "The 'change list' admin view for this model."
        
        self.set_parrent_context_admin(request, parent_id)

        from django.contrib.admin.views.main import ERROR_FLAG
        opts = self.model._meta
        app_label = opts.app_label
        if not self.has_change_permission(request, None):
            raise PermissionDenied

        # Check actions to see if any are available on this changelist
        actions = self.get_actions(request)

        # Remove action checkboxes if there aren't any actions available.
        list_display = list(self.list_display)
        if not actions:
            try:
                list_display.remove('action_checkbox')
            except ValueError:
                pass

        ChangeList = self.get_changelist(request)
        try:
            cl = ChangeList(request, self.model, list_display, self.list_display_links,
                self.list_filter, self.date_hierarchy, self.search_fields,
                self.list_select_related, self.list_per_page, self.list_editable, self)
        except IncorrectLookupParameters:
            # Wacky lookup parameters were given, so redirect to the main
            # changelist page, without parameters, and pass an 'invalid=1'
            # parameter via the query string. If wacky parameters were given
            # and the 'invalid=1' parameter was already in the query string,
            # something is screwed up with the database, so display an error
            # page.
            if ERROR_FLAG in request.GET.keys():
                return render_to_response('admin/invalid_setup.html', {'title': _('Database error')})
            return HttpResponseRedirect(request.path + '?' + ERROR_FLAG + '=1')

        # If the request was POSTed, this might be a bulk action or a bulk
        # edit. Try to look up an action or confirmation first, but if this
        # isn't an action the POST will fall through to the bulk edit check,
        # below.
        action_failed = False
        selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)

        # Actions with no confirmation
        if (actions and request.method == 'POST' and
                'index' in request.POST and '_save' not in request.POST):
            if selected:
                response = self.response_action(request, queryset=cl.get_query_set())
                if response:
                    return response
                else:
                    action_failed = True
            else:
                msg = _("Items must be selected in order to perform "
                        "actions on them. No items have been changed.")
                self.message_user(request, msg)
                action_failed = True

        # Actions with confirmation
        if (actions and request.method == 'POST' and
                helpers.ACTION_CHECKBOX_NAME in request.POST and
                'index' not in request.POST and '_save' not in request.POST):
            if selected:
                response = self.response_action(request, queryset=cl.get_query_set())
                if response:
                    return response
                else:
                    action_failed = True

        # If we're allowing changelist editing, we need to construct a formset
        # for the changelist given all the fields to be edited. Then we'll
        # use the formset to validate/process POSTed data.
        formset = cl.formset = None

        # Handle POSTed bulk-edit data.
        if (request.method == "POST" and cl.list_editable and
                '_save' in request.POST and not action_failed):
            FormSet = self.get_changelist_formset(request)
            formset = cl.formset = FormSet(request.POST, request.FILES, queryset=cl.result_list)
            if formset.is_valid():
                changecount = 0
                for form in formset.forms:
                    if form.has_changed():
                        obj = self.save_form(request, form, change=True)
                        self.save_model(request, obj, form, change=True)
                        form.save_m2m()
                        change_msg = self.construct_change_message(request, form, None)
                        self.log_change(request, obj, change_msg)
                        changecount += 1

                if changecount:
                    if changecount == 1:
                        name = force_unicode(opts.verbose_name)
                    else:
                        name = force_unicode(opts.verbose_name_plural)
                    msg = ungettext("%(count)s %(name)s was changed successfully.",
                                    "%(count)s %(name)s were changed successfully.",
                                    changecount) % {'count': changecount,
                                                    'name': name,
                                                    'obj': force_unicode(obj)}
                    self.message_user(request, msg)

                return HttpResponseRedirect(request.get_full_path())

        # Handle GET -- construct a formset for display.
        elif cl.list_editable:
            FormSet = self.get_changelist_formset(request)
            formset = cl.formset = FormSet(queryset=cl.result_list)

        # Build the list of media to be used by the formset.
        if formset:
            media = self.media + formset.media
        else:
            media = self.media

        # Build the action form and populate it with available actions.
        if actions:
            action_form = self.action_form(auto_id=None)
            action_form.fields['action'].choices = self.get_action_choices(request)
        else:
            action_form = None

        selection_note_all = ungettext('%(total_count)s selected',
            'All %(total_count)s selected', cl.result_count)

        context = {
            'module_name': force_unicode(opts.verbose_name_plural),
            'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
            'selection_note_all': selection_note_all % {'total_count': cl.result_count},
            'title': cl.title,
            'is_popup': cl.is_popup,
            'cl': cl,
            'media': media,
            'has_add_permission': self.has_add_permission(request),
            'root_path': self.admin_site.root_path,
            'app_label': app_label,
            'action_form': action_form,
            'actions_on_top': self.actions_on_top,
            'actions_on_bottom': self.actions_on_bottom,
            'actions_selection_counter': self.actions_selection_counter,
        }
        context.update(extra_context or {})

        context['context_inner_model_admin'] = self

        context_instance = template.RequestContext(request, current_app=self.admin_site.name)
        return render_to_response(self.change_list_template or [
            'context_admin/%s/%s/inner_change_list.html' % (app_label, opts.object_name.lower()),
            'context_admin/%s/inner_change_list.html' % app_label,
            'context_admin/inner_change_list.html'
        ], context, context_instance=context_instance)
Ejemplo n.º 22
0
    def new_order(self, request, uid):
        from assopy import forms as aforms
        from conference.models import Fare
        from conference.settings import CONFERENCE

        user = get_object_or_404(models.User, user=uid)

        class FormTickets(aforms.FormTickets):
            coupon = forms.CharField(label='Coupon(s)', required=False)
            country = forms.CharField(max_length=2, required=False)
            address = forms.CharField(max_length=150, required=False)
            card_name = forms.CharField(max_length=200,
                                        required=True,
                                        initial=user.card_name or user.name())
            billing_notes = forms.CharField(
                required=False, widget=forms.Textarea(attrs={'rows': 3}))
            remote = forms.BooleanField(
                required=False,
                initial=True,
                help_text='debug only, fill the order on the remote backend')

            def __init__(self, *args, **kwargs):
                super(FormTickets, self).__init__(*args, **kwargs)
                self.fields['payment'].choices = (
                    ('admin', 'Admin'), ) + tuple(
                        self.fields['payment'].choices)
                self.fields['payment'].initial = 'admin'

            def available_fares(self):
                return Fare.objects.available(conference=CONFERENCE)

            def clean_country(self):
                data = self.cleaned_data.get('country')
                if data:
                    try:
                        data = models.Country.objects.get(pk=data)
                    except models.Country.DoesNotExist:
                        raise forms.ValidationError('Invalid country: %s' %
                                                    data)
                return data

            def clean_coupon(self):
                data = self.cleaned_data.get('coupon')
                output = []
                if data:
                    for c in data.split(' '):
                        try:
                            output.append(
                                models.Coupon.objects.get(
                                    conference=CONFERENCE, code=c))
                        except models.Coupon.DoesNotExist:
                            raise forms.ValidationError('invalid coupon "%s"' %
                                                        c)
                if self.cleaned_data.get('payment') == 'admin':
                    for c in output:
                        if c.value != '100%':
                            raise forms.ValidationError(
                                'admin orders must have a 100% discount coupon'
                            )
                return output

        if request.method == 'POST':
            form = FormTickets(data=request.POST)
            if form.is_valid():
                data = form.cleaned_data
                # non salvo l'utente per non sovrascrivere il suo card_name
                user.card_name = data['card_name']
                models.Order.objects.create(
                    user=user,
                    payment=data['payment'],
                    items=data['tickets'],
                    billing_notes=data['billing_notes'],
                    coupons=data['coupon'],
                    remote=data['remote'],
                    country=data['country'],
                    address=data['address'],
                )
                return redirect(
                    'admin:auth_user_change',
                    user.user_id,
                )
        else:
            form = FormTickets()
        ctx = {
            'user': user,
            'form': form,
        }
        return render_to_response(
            'admin/auth/user/new_order.html',
            ctx,
            context_instance=template.RequestContext(request))
Ejemplo n.º 23
0
    def copy_view(self, request, object_id, extra_context=None):
        """
        Create a draft copy of the item after user has confirmed.
        """
        opts = self.model._meta
        app_label = opts.app_label

        obj = self.get_object(request, unquote(object_id))

        # For our purposes, permission to copy is equivalent to
        # permission to add.
        if not self.has_add_permission(request):
            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.POST:  # The user has already confirmed the copy.
            if obj.is_draft_copy():
                self.message_user(request, _('You cannot copy a draft copy.'))
                return HttpResponseRedirect(request.path)

            if obj.get_draft_copy():
                self.message_user(request, _('A draft copy already exists.'))
                return HttpResponseRedirect(request.path)

            obj_display = force_unicode(obj) + " copied."
            self.log_change(request, obj, obj_display)
            copy = self._copy_page(obj)

            self.message_user(
                request,
                _('The %(name)s "%(obj)s" was copied successfully.') % {
                    'name': force_unicode(opts.verbose_name),
                    'obj': force_unicode(obj_display)
                })

            url = reverse("admin:%s_%s_change" %
                          (app_label, self.model._meta.module_name),
                          args=(copy.id, ))
            return HttpResponseRedirect(url)

        if self.model.objects.filter(copy_of=obj).exists():
            draft_already_exists = True
            title = _("Draft Copy Exists")
            edit_copy_url = reverse(
                "admin:%s_%s_change" %
                (app_label, self.model._meta.module_name),
                args=(self.model.objects.filter(copy_of=obj)[0].id, ))

        else:
            draft_already_exists = False
            title = _("Are you sure?")
            edit_copy_url = None
        context = {
            "title": title,
            "object_name": force_unicode(opts.verbose_name),
            "object": obj,
            "opts": opts,
            "root_path": self.admin_site.root_path,
            "app_label": app_label,
            'draft_already_exists': draft_already_exists,
            'edit_copy_url': edit_copy_url
        }
        context.update(extra_context or {})
        context_instance = template.RequestContext(
            request, current_app=self.admin_site.name)
        return render_to_response(self.copy_form_template,
                                  context,
                                  context_instance=context_instance)
Ejemplo n.º 24
0
    def render_revision_form(self,
                             request,
                             obj,
                             version,
                             context,
                             revert=False,
                             recover=False):
        """Renders the object revision form."""
        model = self.model
        opts = model._meta
        object_id = obj.pk
        # Generate the model form.
        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == "POST":
            # This section is copied directly from the model admin change view
            # method.  Maybe one day there will be a hook for doing this better.
            form = ModelForm(request.POST,
                             request.FILES,
                             instance=obj,
                             initial=self.get_revision_form_data(
                                 request, obj, version))
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
                # HACK: If the value of a file field is None, remove the file from the model.
                for field in new_object._meta.fields:
                    if isinstance(
                            field, models.FileField
                    ) and field.name in form.cleaned_data and form.cleaned_data[
                            field.name] is None:
                        setattr(new_object, field.name, None)
            else:
                form_validated = False
                new_object = obj
            prefixes = {}

            for FormSet, inline in zip(self.get_formsets(request, new_object),
                                       self.get_inline_instances(request)):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(request.POST,
                                  request.FILES,
                                  instance=new_object,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                self._hack_inline_formset_initial(inline, FormSet, formset,
                                                  obj, version, revert,
                                                  recover)
                # Add this hacked formset to the form.
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                for formset in formsets:
                    # HACK: If the value of a file field is None, remove the file from the model.
                    related_objects = formset.save(commit=False)
                    for related_obj, related_form in zip(
                            related_objects, formset.saved_forms):
                        for field in related_obj._meta.fields:
                            if isinstance(
                                    field, models.FileField
                            ) and field.name in related_form.cleaned_data and related_form.cleaned_data[
                                    field.name] is None:
                                setattr(related_obj, field.name, None)
                        related_obj.save()
                    formset.save_m2m()
                change_message = _(
                    "Reverted to previous version, saved on %(datetime)s") % {
                        "datetime": localize(version.revision.date_created)
                    }
                self.log_change(request, new_object, change_message)
                self.message_user(
                    request,
                    _('The %(model)s "%(name)s" was reverted successfully. You may edit it again below.'
                      ) % {
                          "model": force_text(opts.verbose_name),
                          "name": force_text(obj)
                      })
                # Redirect to the model change form.
                if revert:
                    return HttpResponseRedirect("../../")
                elif recover:
                    return HttpResponseRedirect("../../%s/" % quote(object_id))
                else:
                    assert False
        else:
            # This is a mutated version of the code in the standard model admin
            # change_view.  Once again, a hook for this kind of functionality
            # would be nice.  Unfortunately, it results in doubling the number
            # of queries required to construct the formets.
            form = ModelForm(instance=obj,
                             initial=self.get_revision_form_data(
                                 request, obj, version))
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, obj),
                                       self.get_inline_instances(request)):
                # This code is standard for creating the formset.
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                self._hack_inline_formset_initial(inline, FormSet, formset,
                                                  obj, version, revert,
                                                  recover)
                # Add this hacked formset to the form.
                formsets.append(formset)
        # Generate admin form helper.
        adminForm = helpers.AdminForm(form,
                                      self.get_fieldsets(request, obj),
                                      self.prepopulated_fields,
                                      self.get_readonly_fields(request, obj),
                                      model_admin=self)
        media = self.media + adminForm.media
        # Generate formset helpers.
        inline_admin_formsets = []
        for inline, formset in zip(self.get_inline_instances(request),
                                   formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            prepopulated = inline.get_prepopulated_fields(request, obj)
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              prepopulated,
                                                              readonly,
                                                              model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
        # Generate the context.
        context.update({
            "adminform":
            adminForm,
            "object_id":
            object_id,
            "original":
            obj,
            "is_popup":
            False,
            "media":
            mark_safe(media),
            "inline_admin_formsets":
            inline_admin_formsets,
            "errors":
            helpers.AdminErrorList(form, formsets),
            "app_label":
            opts.app_label,
            "add":
            False,
            "change":
            True,
            "revert":
            revert,
            "recover":
            recover,
            "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,
            "form_url":
            mark_safe(request.path),
            "opts":
            opts,
            "content_type_id":
            ContentType.objects.get_for_model(self.model).id,
            "save_as":
            False,
            "save_on_top":
            self.save_on_top,
            "changelist_url":
            reverse("%s:%s_%s_changelist" %
                    (self.admin_site.name, opts.app_label, opts.module_name)),
            "change_url":
            reverse("%s:%s_%s_change" %
                    (self.admin_site.name, opts.app_label, opts.module_name),
                    args=(quote(obj.pk), )),
            "history_url":
            reverse("%s:%s_%s_history" %
                    (self.admin_site.name, opts.app_label, opts.module_name),
                    args=(quote(obj.pk), )),
            "recoverlist_url":
            reverse("%s:%s_%s_recoverlist" %
                    (self.admin_site.name, opts.app_label, opts.module_name))
        })
        # Render the form.
        if revert:
            form_template = self.revision_form_template or self._get_template_list(
                "revision_form.html")
        elif recover:
            form_template = self.recover_form_template or self._get_template_list(
                "recover_form.html")
        else:
            assert False
        return render_to_response(form_template, context,
                                  template.RequestContext(request))
Ejemplo n.º 25
0
 def render(self):
     """ Renders the table using the template from the table options. """
     breadcrumb_template = template.loader.get_template(self.template)
     extra_context = {"breadcrumb": self}
     context = template.RequestContext(self.request, extra_context)
     return breadcrumb_template.render(context)
Ejemplo n.º 26
0
    def get_feed(self, obj, request):
        current_site = Site.objects.get_current()

        link = self._Feed__get_dynamic_attr('link', obj)
        link = add_domain(current_site.domain, link)
        feed = self.feed_type(
            title=self._Feed__get_dynamic_attr('title', obj),
            link=link,
            description=self._Feed__get_dynamic_attr('description', obj),
        )

        title_tmp = None
        if self.title_template is not None:
            try:
                title_tmp = template.loader.get_template(self.title_template)
            except template.TemplateDoesNotExist:
                pass

        description_tmp = None
        if self.description_template is not None:
            try:
                description_tmp = template.loader.get_template(
                    self.description_template)
            except template.TemplateDoesNotExist:
                pass

        for item in self._Feed__get_dynamic_attr('items', obj):
            if title_tmp is not None:
                title = title_tmp.render(
                    template.RequestContext(request, {
                        'obj': item,
                        'site': current_site
                    }))
            else:
                title = self._Feed__get_dynamic_attr('item_title', item)
            if description_tmp is not None:
                description = description_tmp.render(
                    template.RequestContext(request, {
                        'obj': item,
                        'site': current_site
                    }))
            else:
                description = self._Feed__get_dynamic_attr(
                    'item_description', item)
            link = add_domain(
                current_site.domain,
                self._Feed__get_dynamic_attr('item_link', item),
            )

            pubdate = self._Feed__get_dynamic_attr('item_pubdate', item)
            if pubdate and not hasattr(pubdate, 'tzinfo'):
                ltz = tzinfo.LocalTimezone(pubdate)
                pubdate = pubdate.replace(tzinfo=ltz)

            feed.add_item(title=title,
                          link=link,
                          description=description,
                          unique_id=self._Feed__get_dynamic_attr(
                              'item_guid', item, link),
                          pubdate=pubdate,
                          comment_status=self._Feed__get_dynamic_attr(
                              'item_comment_status', item, 'open'),
                          comments=self._get_comments(item))
        return feed
Ejemplo n.º 27
0
 def render(self):
     browser_template = template.loader.get_template(self.template)
     extra_context = {self.context_var_name: self}
     context = template.RequestContext(self.request, extra_context)
     return browser_template.render(context)
Ejemplo n.º 28
0
 def delete_view(self, request, object_id, extra_content=None):
     """Actually a “merge with duplicate” function. Kept the 
     name and most of the code."""
     opts = self.model._meta
     obj = self.get_object(request, object_id)
     errors = []
     
     if not self.has_delete_permission(request, obj):
         raise PermissionDenied
     
     if obj is None:
         raise Http404('%(name)s object with primary key %(key)s does not exist.' % {'name': unicode(opts.verbose_name), 'key': object_id})
     
     # Get all of the objects to be adjusted and check that 
     # we can alter them.
     rels = opts.get_all_related_objects()
     rel_obj = []
     lacking_perms = []
     for r in rels:
         count = getattr(obj, r.get_accessor_name()).all().count()
         if count == 0:
             continue
         if count == 1:
             rel_obj.append(u"%d %s will change its %s" % (count, r.model._meta.verbose_name, r.field.verbose_name))
         else:
             rel_obj.append(u"%d %s will change their %s" % (count, r.model._meta.verbose_name_plural, r.field.verbose_name))
         # Per object perms not avalable yet.
         if not request.user.has_perm(r.model._meta.app_label + '.' + r.model._meta.get_change_permission()):
             lacking_perms.append(r.name)
     
     
     if request.POST: 
         if lacking_perms:
             raise PermissionDenied
         
         form = FindOtherArtistForm(request.POST)
         
         if form.errors:
             errors = form.errors
         else:
             new_obj = form.cleaned_data['entry']
             if new_obj.pk == obj.pk:
                 errors = "You can't merge something with itself."
             else:
                     
                 # move everything over
                 for r in rels:
                     getattr(obj, r.get_accessor_name()).all().update(**{r.field.name : new_obj})
                 # copy artist info. 
                 if not new_obj.last_played or \
                     (obj.last_played and \
                     new_obj.last_played < obj.last_played):
                         new_obj.last_played = obj.last_played
                 if not new_obj.url:
                     new_obj.url = obj.url
                 new_obj.times_played += obj.times_played
                 new_obj.info = "%s\n%s" % (new_obj.info, obj.info)
                 
                 new_obj.save()
                 
                 self.log_deletion(request, obj, unicode(obj))
                 obj.delete()
         
                 self.message_user(request, u'The %(name)s "%(obj)s" was merged with "%(new)s" successfully.' % {'name': unicode(opts.verbose_name), 'obj': unicode(obj), 'new': unicode(new_obj)})
         
                 return HttpResponseRedirect("../../")
     else:
         form = FindOtherArtistForm()
     
     context = {
         "title": "Choose the other artist.",
         "object_name": unicode(opts.verbose_name),
         "object": obj,
         "form": form,
         "errors": errors,
         "media": unicode(form.media),
         "affected": rel_obj,
         "lacking_perms": lacking_perms,
         "opts": opts,
         "app_label": opts.app_label,
     }
     context.update(extra_content or {})
     context_instance = template.RequestContext(request, current_app=self.admin_site.name)
     return render_to_response("dj_pro/admin/merge_confirmation.html", context, context_instance=context_instance)
Ejemplo n.º 29
0
def delete_selected(modeladmin, request, queryset):
    """
    Default action which deletes the selected objects.

    This action first displays a confirmation page whichs shows all the
    deleteable objects, or, if the user has no permission one of the related
    childs (foreignkeys), a "permission denied" message.

    Next, it delets all selected objects and redirects back to the change list.
    
    Copy: django/contrib/admin/actions.py
    """
    opts = modeladmin.model._meta
    app_label = opts.app_label

    # Check that the user has delete permission for the actual model
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied

    using = router.db_for_write(modeladmin.model)

    # Populate deletable_objects, a data structure of all related objects that
    # will also be deleted.
    deletable_objects, perms_needed, protected = get_deleted_objects(
        queryset, opts, request.user, modeladmin.admin_site, using)

    # The user has already confirmed the deletion.
    # Do the deletion and return a None to display the change list view again.
    if request.POST.get('post'):
        if perms_needed:
            raise PermissionDenied
        n = queryset.count()
        if n:
            for obj in queryset:
                obj_display = force_unicode(obj)
                #modifikation
                obj.delete()
                modeladmin.log_deletion(request, obj, obj_display)
            modeladmin.message_user(
                request,
                _("Successfully deleted %(count)d %(items)s.") % {
                    "count": n,
                    "items": model_ngettext(modeladmin.opts, n)
                })
        # Return None to display the change list page again.
        return None

    if len(queryset) == 1:
        objects_name = force_unicode(opts.verbose_name)
    else:
        objects_name = force_unicode(opts.verbose_name_plural)

    if perms_needed or protected:
        title = _("Cannot delete %(name)s") % {"name": objects_name}
    else:
        title = _("Are you sure?")

    context = {
        "title": title,
        "objects_name": objects_name,
        "deletable_objects": [deletable_objects],
        'queryset': queryset,
        "perms_lacking": perms_needed,
        "protected": protected,
        "opts": opts,
        "app_label": app_label,
        'action_checkbox_name': helpers.ACTION_CHECKBOX_NAME,
    }

    # Display the confirmation page
    return render_to_response(
        modeladmin.delete_selected_confirmation_template or [
            "admin/%s/%s/delete_selected_confirmation.html" %
            (app_label, opts.object_name.lower()),
            "admin/%s/delete_selected_confirmation.html" % app_label,
            "admin/delete_selected_confirmation.html"
        ],
        context,
        context_instance=template.RequestContext(request))
Ejemplo n.º 30
0
    def render_revision_form(self,
                             request,
                             obj,
                             version,
                             context,
                             revert=False,
                             recover=False):
        """Renders the object revision form."""
        model = self.model
        opts = model._meta
        object_id = obj.pk
        # Generate the model form.
        ModelForm = self.get_form(request, obj)
        formsets = []
        if request.method == "POST":
            # This section is copied directly from the model admin change view
            # method.  Maybe one day there will be a hook for doing this better.
            form = ModelForm(request.POST,
                             request.FILES,
                             instance=obj,
                             initial=self.get_revision_form_data(
                                 request, obj, version))
            if form.is_valid():
                form_validated = True
                new_object = self.save_form(request, form, change=True)
                # HACK: If the value of a file field is None, remove the file from the model.
                for field in new_object._meta.fields:
                    if isinstance(field, models.FileField
                                  ) and form.cleaned_data[field.name] is None:
                        setattr(new_object, field.name, None)
            else:
                form_validated = False
                new_object = obj
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, new_object),
                                       self.inline_instances):
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(request.POST,
                                  request.FILES,
                                  instance=new_object,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                # Hack the formset to stuff in the new data.
                related_versions = self.get_related_versions(
                    obj, version, FormSet)
                formset.related_versions = related_versions
                new_forms = formset.forms[:len(related_versions)]
                for formset_form in formset.forms[len(related_versions):]:
                    if formset_form.fields["DELETE"].clean(
                            formset_form._raw_value("DELETE")):
                        new_forms.append(formset_form)
                formset.forms = new_forms

                def total_form_count_hack(count):
                    return lambda: count

                formset.total_form_count = total_form_count_hack(
                    len(new_forms))
                # Add this hacked formset to the form.
                formsets.append(formset)
            if all_valid(formsets) and form_validated:
                self.save_model(request, new_object, form, change=True)
                form.save_m2m()
                for formset in formsets:
                    # HACK: If the value of a file field is None, remove the file from the model.
                    related_objects = formset.save(commit=False)
                    for related_obj, related_form in zip(
                            related_objects, formset.saved_forms):
                        for field in related_obj._meta.fields:
                            if isinstance(
                                    field, models.FileField
                            ) and related_form._raw_value(field.name) is None:
                                related_info = formset.related_versions.get(
                                    unicode(related_obj.pk))
                                if related_info:
                                    setattr(
                                        related_obj, field.name,
                                        related_info.field_dict[field.name])
                        related_obj.save()
                    formset.save_m2m()
                change_message = _(
                    u"Reverted to previous version, saved on %(datetime)s") % {
                        "datetime":
                        format(version.revision.date_created,
                               _(settings.DATETIME_FORMAT))
                    }
                self.log_change(request, new_object, change_message)
                self.message_user(
                    request,
                    _(u'The %(model)s "%(name)s" was reverted successfully. You may edit it again below.'
                      ) % {
                          "model": force_unicode(opts.verbose_name),
                          "name": unicode(obj)
                      })
                # Redirect to the model change form.
                if revert:
                    return HttpResponseRedirect("../../")
                elif recover:
                    return HttpResponseRedirect("../../%s/" % object_id)
                else:
                    assert False
        else:
            # This is a mutated version of the code in the standard model admin
            # change_view.  Once again, a hook for this kind of functionality
            # would be nice.  Unfortunately, it results in doubling the number
            # of queries required to construct the formets.
            form = ModelForm(instance=obj,
                             initial=self.get_revision_form_data(
                                 request, obj, version))
            prefixes = {}
            for FormSet, inline in zip(self.get_formsets(request, obj),
                                       self.inline_instances):
                # This code is standard for creating the formset.
                prefix = FormSet.get_default_prefix()
                prefixes[prefix] = prefixes.get(prefix, 0) + 1
                if prefixes[prefix] != 1:
                    prefix = "%s-%s" % (prefix, prefixes[prefix])
                formset = FormSet(instance=obj,
                                  prefix=prefix,
                                  queryset=inline.queryset(request))
                # Now we hack it to push in the data from the revision!
                initial = []
                related_versions = self.get_related_versions(
                    obj, version, FormSet)
                for related_obj in formset.queryset:
                    if unicode(related_obj.pk) in related_versions:
                        initial.append(
                            related_versions.pop(unicode(
                                related_obj.pk)).field_dict)
                    else:
                        initial_data = model_to_dict(related_obj)
                        initial_data["DELETE"] = True
                        initial.append(initial_data)
                for related_version in related_versions.values():
                    initial_row = related_version.field_dict
                    pk_name = ContentType.objects.get_for_id(
                        related_version.content_type_id).model_class(
                        )._meta.pk.name
                    del initial_row[pk_name]
                    initial.append(initial_row)
                # Reconstruct the forms with the new revision data.
                formset.initial = initial
                formset.forms = [
                    formset._construct_form(n) for n in xrange(len(initial))
                ]

                def total_form_count_hack(count):
                    return lambda: count

                formset.total_form_count = total_form_count_hack(len(initial))
                # Add this hacked formset to the form.
                formsets.append(formset)
        # Generate admin form helper.
        adminForm = helpers.AdminForm(form,
                                      self.get_fieldsets(request, obj),
                                      self.prepopulated_fields,
                                      self.get_readonly_fields(request, obj),
                                      model_admin=self)
        media = self.media + adminForm.media
        # Generate formset helpers.
        inline_admin_formsets = []
        for inline, formset in zip(self.inline_instances, formsets):
            fieldsets = list(inline.get_fieldsets(request, obj))
            readonly = list(inline.get_readonly_fields(request, obj))
            inline_admin_formset = helpers.InlineAdminFormSet(inline,
                                                              formset,
                                                              fieldsets,
                                                              readonly,
                                                              model_admin=self)
            inline_admin_formsets.append(inline_admin_formset)
            media = media + inline_admin_formset.media
        # Generate the context.
        context.update({
            "adminform":
            adminForm,
            "object_id":
            object_id,
            "original":
            obj,
            "is_popup":
            False,
            "media":
            mark_safe(media),
            "inline_admin_formsets":
            inline_admin_formsets,
            "errors":
            helpers.AdminErrorList(form, formsets),
            "app_label":
            opts.app_label,
            "add":
            False,
            "change":
            True,
            "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,
            "ordered_objects":
            opts.get_ordered_objects(),
            "form_url":
            mark_safe(request.path),
            "opts":
            opts,
            "content_type_id":
            ContentType.objects.get_for_model(self.model).id,
            "save_as":
            False,
            "save_on_top":
            self.save_on_top,
            "changelist_url":
            reverse("%s:%s_%s_changelist" %
                    (self.admin_site.name, opts.app_label, opts.module_name)),
            "change_url":
            reverse("%s:%s_%s_change" %
                    (self.admin_site.name, opts.app_label, opts.module_name),
                    args=(obj.pk, )),
            "history_url":
            reverse("%s:%s_%s_history" %
                    (self.admin_site.name, opts.app_label, opts.module_name),
                    args=(obj.pk, )),
            "recoverlist_url":
            reverse("%s:%s_%s_recoverlist" %
                    (self.admin_site.name, opts.app_label, opts.module_name))
        })
        # Render the form.
        if revert:
            form_template = self.revision_form_template
        elif recover:
            form_template = self.recover_form_template
        else:
            assert False
        return render_to_response(form_template, context,
                                  template.RequestContext(request))