Extend the admin urls for the CompetitionEntryAdmin model
            to be able to invoke a CSV export view  on the admin model
544670
def get_urls(self):
        
        urls = super(CompetitionEntryAdmin, self).get_urls()
        csv_urls = patterns('',
            url(
                r'^exportcsv/$',
                self.admin_site.admin_view(self.csv_export),
                name='competition-csv-export'
            )
        )
        return csv_urls + urls
1140964
def changelist_view(self, request, extra_context=None):
        
        if self.model is not self.concrete_model:
            return HttpResponseRedirect(
                admin_url(self.concrete_model, "changelist"))

        extra_context = extra_context or {}
        extra_context["content_models"] = self.get_content_models()

        return super(ContentTypedAdmin, self).changelist_view(
            request, extra_context)
767267
protected function exportViews()
    {
        foreach ($this->views as $pathIn => $pathOut) {
            if ($this->files->exists($view = resource_path('views/'.$pathOut)) && ! $this->option('force')) {
                if (! $this->confirm("The [{$pathOut}] view already exists. Do you want to overwrite it?")) {
                    continue;
                }
            }

            $this->files->copy(
                __DIR__.'/stubs/make/views/'.$pathIn,
                $view
            );
        }
    }
981639
public function actionExport() {
        // Initialize export array.
        $data = [
            'siteGroups' => [],
            'sites' => [],
            'routes' => [],
            'fieldGroups' => [],
            'volumes' => [],
            'transforms' => [],
            'tagGroups' => [],
            'categoryGroups' => [],
            'sections' => [],
            'fields' => [],
            'entryTypes' => [],
            'globalSets' => [],
            'userGroups' => [],
            'users' => [],
        ];
        // The list of exportable items.
        $exportList = [
            'sites' => [
                'bodyParam' => 'siteSelection',
                'postProcess' => [
                    'groupId' => 'siteGroups'
                ],
            ],
            'sections' => [
                'bodyParam' => 'sectionSelection',
                'postProcess' => [
                    'entryTypes' => 'entryTypes'
                ],
            ],
            'routes' => [
                'bodyParam' => 'routeSelection',
            ],
            'volumes' => [
                'bodyParam' => 'volumeSelection',
            ],
            'transforms' => [
                'bodyParam' => 'assetTransformSelection',
            ],
            'tagGroups' => [
                'bodyParam' => 'tagSelection',
            ],
            'categoryGroups' => [
                'bodyParam' => 'categorySelection',
            ],
            'fields' => [
                'bodyParam' => 'fieldSelection',
                'postProcess' => [
                    'groupId' => 'fieldGroups'
                ],
            ],
            'globalSets' => [
                'bodyParam' => 'globalSelection',
            ],
            'userGroups' => [
                'bodyParam' => 'userGroupSelection',
            ],
            'users' => [
                'bodyParam' => 'userSelection',
            ]
        ];

        foreach ($exportList as $processorName => $processorInfo) {
            $exportIds = Craft::$app->request->getBodyParam($processorInfo['bodyParam']);
            if ($exportIds) {
                foreach ($exportIds as $exportId) {
                    if ($processorName === 'routes') {
                        $exportObj = Architect::$processors->$processorName->exportByUid($exportId);
                    } else {
                        $exportObj = Architect::$processors->$processorName->exportById($exportId);
                    }

                    if (isset($processorInfo['postProcess'])) {
                        foreach ($processorInfo['postProcess'] as $postProcessKey => $postProcessorName) {
                            switch ($postProcessKey) {
                                case 'groupId':
                                    $groupName = Architect::$processors->$postProcessorName->exportById($exportObj[$postProcessKey]);
                                    if (\in_array($groupName, $data[$postProcessorName], false) === false) {
                                        $data[$postProcessorName][] = $groupName;
                                    }
                                    unset($exportObj[$postProcessKey]);
                                    break;
                                case 'entryTypes':
                                    if (isset($exportObj[$postProcessKey]) && \is_array($exportObj[$postProcessKey])) {
                                        $data[$postProcessorName] = array_merge($data[$postProcessorName], $exportObj[$postProcessKey]);
                                        unset($exportObj[$postProcessKey]);
                                    }
                                    break;
                            }
                        }
                    }

                    $data[$processorName][] = $exportObj;
                }
            }
        }

        foreach ($data as $key => $value) {
            if (\count($value) <= 0) {
                unset($data[$key]);
            }
        }

        $this->renderTemplate('architect/export_results', [ 'dump' => json_encode($data, JSON_PRETTY_PRINT) ]);
    }
1226911
def exportCustomers(self, outPath):
        
        url = "%s/customers/export" % self.root
        params = {"f":"csv"}
        dirPath = None
        fileName = None
        if outPath is not None:
            dirPath = os.path.dirname(outPath)
            fileName = os.path.basename(outPath)
        return self._get(url=url,
                         param_dict=params,
                         securityHandler=self._securityHandler, proxy_url=self._proxy_url,
                        proxy_port=self._proxy_port,
                        out_folder=dirPath,
                        file_name=fileName)
261038
def change_view(self, request, object_id, form_url='', extra_context={}):
        
        extra_context['buttons_link'] = self.buttons_link
        extra_context['buttons_form'] = self.buttons_form
        extra_context['button_object_id'] = object_id
        return super(ButtonableModelAdmin, self).change_view(request, object_id, form_url, extra_context)
1239378
def get_admin_urls_for_registration(self):
        
        urls = (
            url(get_url_pattern(self.opts),
                self.index_view, name=get_url_name(self.opts)),
            url(get_url_pattern(self.opts, 'create'),
                self.create_view, name=get_url_name(self.opts, 'create')),
            url(get_object_specific_url_pattern(self.opts, 'edit'),
                self.edit_view, name=get_url_name(self.opts, 'edit')),
            url(get_object_specific_url_pattern(self.opts, 'confirm_delete'),
                self.confirm_delete_view,
                name=get_url_name(self.opts, 'confirm_delete')),
        )
        if self.inspect_view_enabled:
            urls = urls + (
                url(get_object_specific_url_pattern(self.opts, 'inspect'),
                    self.inspect_view,
                    name=get_url_name(self.opts, 'inspect')),
            )
        if self.is_pagemodel:
            urls = urls + (
                url(get_url_pattern(self.opts, 'choose_parent'),
                    self.choose_parent_view,
                    name=get_url_name(self.opts, 'choose_parent')),
                url(get_object_specific_url_pattern(self.opts, 'unpublish'),
                    self.unpublish_view,
                    name=get_url_name(self.opts, 'unpublish')),
                url(get_object_specific_url_pattern(self.opts, 'copy'),
                    self.copy_view,
                    name=get_url_name(self.opts, 'copy')),
            )
        return urls

        def construct_main_menu(self, request, menu_items):
            warnings.warn((
                "The 'construct_main_menu' method is now deprecated. You "
                "should also remove the construct_main_menu hook from "
                "wagtail_hooks.py in your app folder."), DeprecationWarning)
            return menu_items
310285
def post_manager_view(model, view="PostManager", template_dir=None):
    

    PostStruct = model.PostStruct

    Pylot.context_(COMPONENT_POST_MANAGER=True)

    if not template_dir:
        template_dir = "Pylot/PostManager"
    template_page = template_dir + "/%s.html"

    class PostManager(StorageUploadView):
        route_base = "post-manager"

        __session_edit_key = "post_manager_edit_post"

        def __init__(self):
            self.meta_(title=" | Post Manager", description="Post Manager to admin site")
            self.per_page = 25

        def index(self):
            """
            List all posts
            """
            self.meta_(title__prepend="All Posts")
            page = request.args.get("page", 1)
            id = request.args.get("id", None)
            slug = request.args.get("slug", None)
            status = request.args.get("status", "all")
            user_id = request.args.get("user_id", None)
            type_id = request.args.get("type_id", None)
            category_id = request.args.get("category_id", None)

            posts = PostStruct.Post.all()

            if id:
                posts = posts.filter(PostStruct.Post.id == id)
            if slug:
                posts = posts.filter(PostStruct.Post.slug == slug)
            if user_id:
                posts = posts.filter(PostStruct.Post.user_id == user_id)
            if type_id:
                posts = posts.filter(PostStruct.Post.type_id == type_id)
            if category_id:
                posts = posts.join(PostStruct.PostCategory)\
                    .join(PostStruct.Category)\
                    .filter(PostStruct.Category.id == category_id)
            if status == "publish":
                posts = posts.filter(PostStruct.Post.is_published == True)
            elif status == "draft":
                posts = posts.filter(PostStruct.Post.is_draft == True)
            elif status == "revision":
                posts = posts.filter(PostStruct.Post.is_revision == True)

            posts = posts.order_by(PostStruct.Post.id.desc())
            posts = posts.paginate(page=page, per_page=self.per_page)

            return self.render(posts=posts,
                               query_vars={
                                   "id": id,
                                   "slug": slug,
                                   "user_id": user_id,
                                   "type_id": type_id,
                                   "status": status
                               },
                               view_template=template_page % "index")

        def read(self, id):
            """
            Read Post
            """
            post = PostStruct.Post.get(id)
            if not post:
                abort(404, "Post doesn't exist")

            self.meta_(title__prepend=post.title)
            self.meta_(title__prepend="Read Post: ")

            return self.render(post=post,
                               view_template=template_page % "read")

        @route("upload-image", methods=["POST"])
        def upload_image(self):
            """
            Placeholder for markdown
            """

            url = ""
            if request.files.get("file"):
                url = storage.put(request.files.get('file'))

            else:
                return "Couldn't upload file. No file exist", 401

            return self.render(file_url=url)

            # For when there is an error
            error = False
            if error:
                return "error message", 401

            return jsonify({
                "id": "",
                "url": "", # full image url
            })

        @route("new", defaults={"id": None}, endpoint="PostManager:new")
        @route("edit/<id>", endpoint="PostManager:edit")
        def edit(self, id):
            """
            Create / Edit Post
            """
            self.meta_(title__prepend="Edit Post")

            types = [(t.id, t.name) for t in PostStruct.Type.all().order_by(PostStruct.Type.name.asc())]
            categories = [(c.id, c.name) for c in PostStruct.Category.all().order_by(PostStruct.Category.name.asc())]
            checked_cats = []
            post = {
                "id": 0,
                "title": "",
                "content": "",
                "slug": "",
                "type_id": 0
            }

            # saved in session
            if request.args.get("error") and self.__session_edit_key in session:
                post = session[self.__session_edit_key]
                checked_cats = post["post_categories"]
                del session[self.__session_edit_key]

            elif id:
                post = PostStruct.Post.get(id)
                if not post or post.is_revision:
                    abort(404, "Post doesn't exist")
                checked_cats = [c.id for c in post.categories]

            return self.render(post=post,
                               types=types,
                               categories=categories,
                               checked_categories=checked_cats,
                               view_template=template_page % "edit"
                              )

        def post(self):
            """
            Submit
            """
            id = request.form.get("id", None)
            title = request.form.get("title", None)
            slug = request.form.get("slug", None)
            content = request.form.get("content", None)
            type_id = request.form.get("type_id", None)
            post_categories = request.form.getlist("post_categories")
            published_date = request.form.get("published_date", None)
            status = request.form.get("status", "draft")
            is_published = True if status == "publish" else False
            is_draft = True if status == "draft" else False
            is_public = request.form.get("is_public", True)

            if status in ["draft", "publish"] and (not title or not type_id):
                if not title:
                    self.error_("Post Title is missing ")
                if not type_id:
                    self.error_("Post type is missing")

                session[self.__session_edit_key] = {
                    "id": id,
                    "title": title,
                    "content": content,
                    "slug": slug,
                    "type_id": type_id,
                    "published_date": published_date,
                    "post_categories": post_categories
                }
                if id:
                    url = url_for("PostManager:edit", id=id, error=1)
                else:
                    url = url_for("PostManager:new", error=1)
                return redirect(url)

            data = {
                "title": title,
                "content": content,
                "type_id": type_id
            }

            if published_date:
                published_date = datetime.datetime.strptime(published_date, "%Y-%m-%d %H:%M:%S")
            else:
                published_date = datetime.datetime.now()

            if id and status in ["delete", "revision"]:
                post = PostStruct.Post.get(id)
                if not post:
                    abort(404, "Post '%s' doesn't exist" % id)

                if status == "delete":
                    post.delete()
                    self.success_("Post deleted successfully!")
                    return redirect(url_for("%s:index" % view ))

                elif status == "revision":
                    data.update({
                        "user_id": current_user.id,
                        "parent_id": id,
                        "is_revision": True,
                        "is_draft": False,
                        "is_published": False,
                        "is_public": False
                    })
                    post = PostStruct.Post.create(**data)
                    return jsonify({"revision_id": post.id})

            elif status in ["draft", "publish"]:
                data.update({
                    "is_published": is_published,
                    "is_draft": is_draft,
                    "is_revision": False,
                    "is_public": is_public
                })
                if id:
                    post = PostStruct.Post.get(id)
                    if not post:
                        abort(404, "Post '%s' doesn't exist" % id)
                    elif post.is_revision:
                        abort(403, "Can't access this post")
                    else:
                        post.update(**data)
                else:
                    data["user_id"] = current_user.id
                    if is_published:
                        data["published_date"] = published_date
                    post = PostStruct.Post.create(**data)

                post.set_slug(slug or title)

                post.replace_categories(map(int, post_categories))

                if post.is_published and not post.published_date:
                    post.update(published_date=published_date)

                self.success_("Post saved successfully!")

                endpoint = "read" if post.is_published else "edit"
                return redirect(url_for("%s:%s" % (view, endpoint), id=post.id))

            else:
                abort(400, "Invalid post status")

        @route("categories", methods=["GET", "POST"])
        def categories(self):
            self.meta_(title__prepend="Post Categories")
            if request.method == "POST":
                id = request.form.get("id", None)
                action = request.form.get("action")
                name = request.form.get("name")
                slug = request.form.get("slug", None)
                ajax = request.form.get("ajax", False)
                try:
                    if not id:
                        cat = PostStruct.Category.new(name=name, slug=slug)
                        if ajax:
                            return jsonify({
                                "id": cat.id,
                                "name": cat.name,
                                "slug": cat.slug,
                                "status": "OK"
                            })
                        self.success_("New category '%s' added" % name)
                    else:
                        post_cat = PostStruct.Category.get(id)
                        if post_cat:
                            if action == "delete":
                                post_cat.delete()
                                self.success_("Category '%s' deleted successfully!" % post_cat.name)
                            else:
                                post_cat.update(name=name, slug=slug)
                                self.success_("Category '%s' updated successfully!" % post_cat.name)
                except Exception as ex:
                    if ajax:
                        return jsonify({
                            "error": True,
                            "error_message": ex.message
                        })

                    self.error_("Error: %s" % ex.message)
                return redirect(url_for("%s:categories" % view))

            else:
                cats = PostStruct.Category.all().order_by(PostStruct.Category.name.asc())
                return self.render(categories=cats,
                                   view_template=template_page % "categories")

        @route("types", methods=["GET", "POST"])
        def types(self):
            self.meta_(title__prepend="Post Types")
            if request.method == "POST":
                try:
                    id = request.form.get("id", None)
                    action = request.form.get("action")
                    name = request.form.get("name")
                    slug = request.form.get("slug", None)
                    if not id:
                        PostStruct.Type.new(name=name, slug=slug)
                        self.success_("New type '%s' added" % name)
                    else:
                        post_type = PostStruct.Type.get(id)
                        if post_type:
                            if action == "delete":
                                post_type.delete()
                                self.success_("Type '%s' deleted successfully!" % post_type.name)
                            else:
                                post_type.update(name=name, slug=slug)
                                self.success_("Type '%s' updated successfully!" % post_type.name)
                except Exception as ex:
                    self.error_("Error: %s" % ex.message)
                return redirect(url_for("%s:types" % view))
            else:
                types = PostStruct.Type.all().order_by(PostStruct.Type.name.asc())
                return self.render(types=types,
                                   view_template=template_page % "types")

    return PostManager
1026270
def get_urls(self):
        
        urls = super(FormAdmin, self).get_urls()
        extra_urls = [
            re_path("^(?P<form_id>\d+)/entries/$",
                self.admin_site.admin_view(self.entries_view),
                name="form_entries"),
            re_path("^(?P<form_id>\d+)/entries/show/$",
                self.admin_site.admin_view(self.entries_view),
                {"show": True}, name="form_entries_show"),
            re_path("^(?P<form_id>\d+)/entries/export/$",
                self.admin_site.admin_view(self.entries_view),
                {"export": True}, name="form_entries_export"),
            re_path("^file/(?P<field_entry_id>\d+)/$",
                self.admin_site.admin_view(self.file_view),
                name="form_file"),
        ]
        return extra_urls + urls
1342865
def add_request_type_view(request):
    '''  '''
    form = RequestTypeForm(request.POST or None)
    if form.is_valid():
        rtype = form.save()
        messages.add_message(request, messages.SUCCESS,
                             MESSAGES['REQUEST_TYPE_ADDED'].format(typeName=rtype.name))
        return HttpResponseRedirect(reverse('managers:manage_request_types'))
    return render_to_response('edit_request_type.html', {
        'page_name': "Admin - Add Request Type",
        'request_types': RequestType.objects.all(),
        'form': form,
        }, context_instance=RequestContext(request))
524033
def download_file(self, fname, output_dir):
    """"""
    if fname not in self.competition_files:  # pylint: disable=unsupported-membership-test
      raise ValueError("%s is not one of the competition's "
                       "files: %s" % (fname, self.competition_files))
    command = [
        "kaggle",
        "competitions",
        "download",
        "--file",
        fname,
        "--path",
        output_dir,
        "-c",
        self._competition_name,
    ]
    _run_kaggle_command(command, self._competition_name)
    return os.path.join(output_dir, fname)
589984
def share_extender(self, share: dict, results_filtered: dict):
        
        # add share administration URL
        creator_id = share.get("_creator").get("_tag")[6:]
        share["admin_url"] = "{}/groups/{}/admin/shares/{}".format(
            self.app_url, creator_id, share.get("_id")
        )
        # check if OpenCatalog is activated
        opencat_url = "{}/s/{}/{}".format(
            self.oc_url, share.get("_id"), share.get("urlToken")
        )
        if requests.head(opencat_url):
            share["oc_url"] = opencat_url
        else:
            pass
        # add metadata ids list
        share["mds_ids"] = (i.get("_id") for i in results_filtered)

        return share
890125
def admin_url(inst):
    
    if inst:
        t = Template("""{% load admin_urls %}{% url opts|admin_urlname:'change' inst.pk %}""")
        return t.render(Context({ 'inst': inst, 'opts': inst._meta}))
    return ""
53762
def get_urls(self):
        
        urlpatterns = super(TranslatableAdmin, self).get_urls()
        if not self._has_translatable_model():
            return urlpatterns
        else:
            opts = self.model._meta
            info = opts.app_label, opts.model_name
            return [url(
                r'^(.+)/change/delete-translation/(.+)/$',
                self.admin_site.admin_view(self.delete_translation),
                name='{0}_{1}_delete_translation'.format(*info)
            )] + urlpatterns
606381
def url2path(url, data=True, ext:str='.tgz'):
    ""
    name = url2name(url)
    return datapath4file(name, ext=ext, archive=False) if data else modelpath4file(name, ext=ext)
539184
def add_view(self, request, form_url='', extra_context=None):
        """"""
        extra_context = {
            'language': get_language_from_request(request),
            'page_languages': settings.PAGE_LANGUAGES,
        }
        return super(PageAdmin, self).add_view(request, form_url,
                                               extra_context)
20376
def user_admin_urlname(action):
    
    user = get_user_model()
    return 'admin:%s_%s_%s' % (
        user._meta.app_label, user._meta.model_name,
        action)