def ready(self): # django-wiki needs a root page. # create_root emulates get_or_create, so this should only create # a new root file if none exists yet. from wiki.models import URLPath if db_table_exists('django_site'): # the following condition was needed for a wiki migration of wiki 0.3.1 if db_table_column_exists('wiki_urlpath', 'moved_to_id'): URLPath.create_root() # activate activity streams for WikiArticle from actstream import registry from .models import WikiArticle registry.register(WikiArticle) # register a custom notification """ from spaces_notifications.utils import register_notification from django.utils.translation import ugettext_noop as _ register_notification( 'spaces_wiki_create', _('A new article has been published.'), _('A new article has been published.') ) register_notification( 'spaces_wiki_modify', _('An article has been modified.'), _('An article has been modified.') ) """ post_migrate.connect(create_notice_types, sender=self)
def test_works_with_lazy_functions(self): URLPath.create_root() config = (('base_url', reverse_lazy('wiki:get', kwargs={'path': ''})), ) md = markdown.Markdown(extensions=['extra', WikiPathExtension(config)]) text = '[Français](wiki:/fr)' self.assertEqual( md.convert(text), '<p><a class="wikipath linknotfound" href="/fr">Français</a></p>', )
def test_works_with_lazy_functions(self): URLPath.create_root() config = (("base_url", reverse_lazy("wiki:get", kwargs={"path": ""})), ) md = markdown.Markdown(extensions=["extra", WikiPathExtension(config)]) text = "[Français](wiki:/fr)" self.assertEqual( md.convert(text), '<p><a class="wikipath linknotfound" href="/fr">Français</a></p>', ) URLPath.create_urlpath( URLPath.root(), "linktest", title="LinkTest", content="A page\n#A section\nA line", user_message="Comment1", ) # Link to an existing page text = "[Test link](wiki:/linktest)" self.assertEqual( md.convert(text), '<p><a class="wikipath" href="/linktest/">Test link</a></p>', ) # Link with an empty fragment text = "[Test link](wiki:/linktest#)" self.assertEqual( md.convert(text), '<p><a class="wikipath" href="/linktest/#">Test link</a></p>', ) # Link to a header in an existing page text = "[Test head](wiki:/linktest#wiki-toc-a-section)" self.assertEqual( md.convert(text), '<p><a class="wikipath" href="/linktest/#wiki-toc-a-section">Test head</a></p>', ) # Link to a header in a non existing page text = "[Test head nonExist](wiki:/linktesterr#wiki-toc-a-section)" self.assertEqual( md.convert(text), '<p><a class="wikipath linknotfound" href="/linktesterr#wiki-toc-a-section">Test head nonExist</a></p>', ) # Invalid Wiki link: The default markdown link parser takes over text = "[Test head err](wiki:/linktest#wiki-toc-a-section#err)" self.assertEqual( md.convert(text), '<p><a href="wiki:/linktest#wiki-toc-a-section#err">Test head err</a></p>', )
def test_works_with_lazy_functions(self): URLPath.create_root() config = ( ('base_url', reverse_lazy('wiki:get', kwargs={'path': ''})), ) md = markdown.Markdown( extensions=['extra', WikiPathExtension(config)] ) text = '[Français](wiki:/fr)' self.assertEqual( md.convert(text), '<p><a class="wikipath linknotfound" href="/fr">Français</a></p>', )
def setUp(self): config = (("base_url", reverse_lazy("wiki:get", kwargs={"path": ""})), ) self.md = markdown.Markdown( extensions=["extra", WikiPathExtension(config)]) URLPath.create_root() URLPath.create_urlpath( URLPath.root(), "linktest", title="LinkTest", content="A page\n#A section\nA line", user_message="Comment1", )
def test_manager(self): root = URLPath.create_root() child = URLPath.create_article(root, "child") self.assertEqual(root.parent, None) self.assertEqual(list(root.children.all().active()), [child])
def get_or_create_root(): """ Returns the root article, or creates it if it doesn't exist. """ try: root = URLPath.root() if not root.article: root.delete() raise NoRootURL return root except NoRootURL: pass starting_content = "\n".join(( _("Welcome to the {platform_name} Wiki").format( platform_name=configuration_helpers.get_value( 'PLATFORM_NAME', settings.PLATFORM_NAME), ), "===", _("Visit a course wiki to add an article."), )) root = URLPath.create_root(title=_("Wiki"), content=starting_content) article = root.article article.group = None article.group_read = True article.group_write = False article.other_read = True article.other_write = False article.save() return root
def get_or_create_root(): """ Returns the root article, or creates it if it doesn't exist. """ try: root = URLPath.root() if not root.article: root.delete() raise NoRootURL return root except NoRootURL: pass starting_content = "\n".join(( _("Welcome to the edX Wiki"), "===", _("Visit a course wiki to add an article."), )) root = URLPath.create_root(title=_("Wiki"), content=starting_content) article = root.article article.group = None article.group_read = True article.group_write = False article.other_read = True article.other_write = False article.save() return root
def get_or_create_root(): """ Returns the root article, or creates it if it doesn't exist. """ try: root = URLPath.root() if not root.article: root.delete() raise NoRootURL return root except NoRootURL: pass starting_content = "\n".join(( "Welcome to the edX Wiki", "===", "Visit a course wiki to add an article.")) root = URLPath.create_root(title="Wiki", content=starting_content) article = root.article article.group = None article.group_read = True article.group_write = False article.other_read = True article.other_write = False article.save() return root
def get_or_create_root(): """ Returns the root article, or creates it if it doesn't exist. """ try: root = URLPath.root() if not root.article: root.delete() raise NoRootURL return root except NoRootURL: pass starting_content = "\n".join(( _("Welcome to the {platform_name} Wiki").format(platform_name=get_themed_value('PLATFORM_NAME', settings.PLATFORM_NAME)), "===", _("Visit a course wiki to add an article."), )) root = URLPath.create_root(title=_("Wiki"), content=starting_content) article = root.article article.group = None article.group_read = True article.group_write = False article.other_read = True article.other_write = False article.save() return root
def test_manager(self): root = URLPath.create_root() child = URLPath.create_article(root, "child") self.assertEqual(root.parent, None) self.assertEqual(list(root.children.active()), [child])
def setUp(self): super(RequireRootArticleMixin, self).setUp() self.root = URLPath.create_root() self.root_article = URLPath.root().article rev = self.root_article.current_revision rev.title = "Root Article" rev.content = "root article content" rev.save()
def setUp(self): super().setUp() self.root = URLPath.create_root() self.root_article = URLPath.root().article rev = self.root_article.current_revision rev.title = "Root Article" rev.content = "root article content" rev.save()
def setUp(self): super(ArticleTestBase, self).setUp() self.root = URLPath.create_root() self.child1 = URLPath.create_article(self.root, 'test-slug', title="Test 1")
def main(): args = parser.parse_args() for r in args.root: if not r.endswith(MD_EXTENSION): parser.error('Must end with %s: %r' % (MD_EXTENSION, r)) files = list(find_files(args.root)) contents = list(read_contents(files)) from wiki.models import Article, ArticleRevision, URLPath if args.clear: if not contents: parser.error('--clear: No input files') hostname = socket.gethostname() if args.clear != hostname: parser.error('--clear: Please confirm by specifying ' + 'the current hostname %r as argument' % hostname) URLPath.objects.all().delete() ArticleRevision.objects.all().delete() Article.objects.all().delete() paths = {'': URLPath.create_root()} for i, (path, parent, title, content) in enumerate(contents): print('\r%s/%s %s\x1b[J' % (i + 1, len(contents), title), end='', flush=True, file=sys.stderr) parent_urlpath = paths[parent] paths[path] = URLPath.create_urlpath( parent=parent_urlpath, slug=os.path.basename(path), site=parent_urlpath.site, title=title, content=content, ) print('')
def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} extra_context['buttons'] = self.get_buttons(request, None) c_url = resolve(request.path_info) if c_url.namespace: url_name = '%s:%s' % (c_url.namespace, c_url.url_name) else: url_name = '%s' % c_url.url_name try: admin_config = UserAdminConfig.objects.filter(user=request.user, url_name=url_name)[0] admin_old_url = admin_config.url_full_path admin_config.url_name = url_name admin_config.url_full_path = request.get_full_path() admin_config.save() except IndexError: admin_old_url = None admin_config = UserAdminConfig.objects.create( user=request.user, url_name=url_name, url_full_path=request.get_full_path(), ) if admin_old_url == request.get_full_path(): admin_old_url = None extra_context['admin_old_url'] = admin_old_url opts = self.model._meta app_label = opts.app_label multi_search_fields = [] for field_opts in self.multi_search: attributes = { 'size': '40', } if len(field_opts) == 4: attributes.update(field_opts[3]) multi_search_fields.append({ 'name': field_opts[0], 'label': field_opts[1], 'value': request.GET.get(field_opts[0], ''), 'attributes': ' '.join(['%s="%s"' % (k, v) for k, v in attributes.items()]), }) buttons = self.get_buttons(request, None) if POWERADMIN_USE_WIKI: path = '{0}-{1}'.format(app_label.lower(), opts.object_name.lower()) from wiki.models import Article, ArticleRevision, URLPath from django.contrib.sites.shortcuts import get_current_site if not URLPath.objects.filter(slug=path).count(): if not URLPath.objects.count(): URLPath.create_root(site=get_current_site(request), title=u'Root', content=u"", request=request) root = URLPath.objects.order_by('id')[0] URLPath.create_article(root, path, site=get_current_site(request), title=path, content=u"", user_message=u"", user=request.user, ip_address=request.META['REMOTE_ADDR'], article_kwargs={'owner': request.user}) buttons.append( PowerButton(url=POWERADMIN_WIKI_ARTICLE_URL.format(path=path), label=u'Ajuda', attrs={'target': '_blank'})) context_data = { 'buttons': buttons, 'multi_search': True, 'multi_search_fields': multi_search_fields, 'admin_old_url': admin_old_url, } extra_context.update(context_data) return super(PowerModelAdmin, self).changelist_view(request, extra_context)
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): #Verifica se a tela é readonly if self.has_readonly_permission(request, obj): readonly = True else: readonly = False fields = [] for field in list( flatten_fieldsets(self.get_fieldsets(request, obj))): if isinstance(field, str): fields.append(field) else: fields += field readonly_fields = self.get_readonly_fields(request, obj) if set(fields) == set(readonly_fields).intersection(set(fields)): readonly = True for inline in context['inline_admin_formsets']: if set(flatten_fieldsets(inline.fieldsets)) != set( inline.readonly_fields).intersection( set(flatten_fieldsets(inline.fieldsets))): readonly = False opts = self.model._meta app_label = opts.app_label object_id = obj.pk if obj else obj buttons = self.get_buttons(request, object_id) if POWERADMIN_USE_WIKI: path = '{0}-{1}'.format(app_label.lower(), opts.object_name.lower()) from wiki.models import Article, ArticleRevision, URLPath from django.contrib.sites.shortcuts import get_current_site if not URLPath.objects.filter(slug=path).count(): if not URLPath.objects.count(): URLPath.create_root(site=get_current_site(request), title=u'Root', content=u"", request=request) root = URLPath.objects.order_by('id')[0] URLPath.create_article(root, path, site=get_current_site(request), title=path, content=u"", user_message=u"", user=request.user, ip_address=request.META['REMOTE_ADDR'], article_kwargs={'owner': request.user}) buttons.append( PowerButton(url=POWERADMIN_WIKI_ARTICLE_URL.format(path=path), label=u'Ajuda')) context.update({ 'buttons': buttons, 'readonly': readonly, }) return super(PowerModelAdmin, self).render_change_form(request, context, add, change, form_url, obj)
def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): """ Método padrão do ModelAdmin, cutomizado para pegar o template do get_change_form_template() criado para classe. """ #Verifica se a tela é readonly readonly = False readonly_fields = list(self.get_readonly_fields(request, obj)) fields = list(flatten_fieldsets(self.get_fieldsets(request, obj))) if set(fields) == set(readonly_fields).intersection(set(fields)): readonly = True for inline in context['inline_admin_formsets']: if set(flatten_fieldsets(inline.fieldsets)) != set(inline.readonly_fields).intersection(set(flatten_fieldsets(inline.fieldsets))): readonly = False opts = self.model._meta app_label = opts.app_label ordered_objects = opts.get_ordered_objects() object_id = obj.pk if obj else obj buttons = self.get_buttons(request, object_id) if POWERADMIN_USE_WIKI: path = '{0}-{1}'.format(app_label.lower(), opts.object_name.lower()) from wiki.models import Article, ArticleRevision, URLPath from django.contrib.sites.models import get_current_site if not URLPath.objects.filter(slug=path).count(): if not URLPath.objects.count(): URLPath.create_root( site=get_current_site(request), title=u'Root', content=u"", request=request ) root = URLPath.objects.order_by('id')[0] URLPath.create_article( root, path, site=get_current_site(request), title=path, content=u"", user_message=u"", user=request.user, ip_address=request.META['REMOTE_ADDR'], article_kwargs={ 'owner': request.user } ) buttons.append(PowerButton(url=POWERADMIN_WIKI_ARTICLE_URL.format(path=path), label=u'Ajuda')) context.update({ 'buttons': buttons, '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': True, # FIXME - this should check if form or formsets have a FileField, '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': getattr(self.admin_site, 'root_path', None), 'readonly': readonly, }) context_instance = template.RequestContext(request, current_app=self.admin_site.name) return render_to_response(self.get_change_form_template(), context, context_instance=context_instance)
def get_context_data(self, tag, **kwargs): context = super(TagPageView, self).get_context_data(**kwargs) current_site = Site.objects.get_current() current_language_code = translation.get_language() tag_instance = get_tag(tag) if tag_instance is None: raise Http404(_('No Tag found matching "%s".') % tag) try: article = Article.get_for_object(tag_instance) except ArticleForObject.DoesNotExist: # Get or create root try: root_path = URLPath.root() except NoRootURL: root_path = URLPath.create_root(site=current_site) # Get current language namespace. E.g. "/fr" try: language_ns_path = URLPath.get_by_path("/%s" % current_language_code) except URLPath.DoesNotExist: language_ns_path = URLPath.create_article( parent=root_path, slug=current_language_code, site=current_site, title=current_language_code ) # Get or create the article from django.template.defaultfilters import slugify tag_slug = slugify(tag_instance.name) try: article_path = URLPath.get_by_path("/%s/%s" % (current_language_code, tag_slug)) except URLPath.DoesNotExist: article_path = URLPath.create_article( parent=language_ns_path, slug=tag_slug, site=current_site, title=tag_instance.name ) # Get the wiki article itself article = article_path.article article.add_object_relation(tag_instance) context["article"] = article # XXX: site not taken in account context["tag"] = tag_instance context["related_tags"] = list( reversed( sorted(Tag.objects.related_for_model(tag_instance, I4pProject, counts=True), key=attrgetter("count")) ) )[:15] # Get project sheets tagged with this tag XXX: site=site may # not be correct 4 Random projects with at least one picture. # It's not possible to mix distinct and order by random, so # use a trick hilighted_projects = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations() .filter(language_code=current_language_code, master__site=current_site, master__pictures__isnull=False) .distinct(), tag_instance, ).distinct() context["picture_projects"] = random.sample(hilighted_projects, min(4, len(hilighted_projects))) # Mature projects mature_projects = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations() .filter(master__site=current_site, master__status__in=("WIP", "END")) .distinct(), tag_instance, ).distinct() context["num_mature_projects_projects_with_tag"] = len(mature_projects) context["mature_projects"] = random.sample(mature_projects, min(4, len(mature_projects))) # Starting projects starting_projects = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations() .filter(master__site=current_site, master__status__in=("IDEA", "BEGIN")) .distinct(), tag_instance, ).distinct() context["num_starting_projects_projects_with_tag"] = len(starting_projects) context["starting_projects"] = random.sample(starting_projects, min(4, len(starting_projects))) # New projects context["new_projects"] = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter(master__site=current_site).distinct(), tag_instance ).order_by("-master__created")[:4] # Latest modifications context["modified_projects"] = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter(master__site=current_site).distinct(), tag_instance ).order_by("-modified")[:4] # Related people # List is to force evaluation to avoid a sql bug in queryset combining later (project__in=projects) projects = list( TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter(master__site=current_site).distinct(), tag_instance ).all() ) # While we're at it, let's count them for free context["num_projects_with_tag"] = len(projects) context["people"] = ProjectMember.objects.filter(project__in=projects).order_by("?")[:6] return context
def scrape(request): # init path = os.path.abspath("core") os.chdir('/home/admin/Workspace/app/core') # delete all wiki/categories URLPath.objects.all().delete() ArticleRevision.objects.all().delete() Article.objects.all().delete() AnswerVersion.objects.all().delete() QuestionVersion.objects.all().delete() Question.objects.all().delete() # Create root article root_url = URLPath.create_root(title="StGB") root_url.save() # prepare module base_dir = "stgb" # get = lambda node_id: Category.objects.get(pk=node_id) # root_node = Category.add_root(name="StGB", slug="stgb") # preprocess total file count # Preprocess the total files count filecounter = 0 for filepath in os.walk(base_dir): filecounter += 1 # run main code #for root, dirs, files in os.walk(base_dir, topdown=True, onerror=on_error): for root, dirs, files in tqdm(os.walk(base_dir, topdown=True, onerror=on_error), total=filecounter, unit=" files"): #if "grundlagen" in root: if True: for file in files: path = os.path.join(root, file) html = open(path).read() soup = BeautifulSoup(html, "html.parser") print("=> {}".format(path)) # create categories if "category" in get_type(soup): cat = { "root": root, "slug": root.split("/")[-1], "name": soup.article.h1.text.strip(), #"long_name": extract("long_name", soup), } create_category(cat) # create wikis if "problem" in get_type(soup): wiki = { "root": root, "slug": root.split("/")[-1], "name": soup.article.h1.text.strip(), #"long_name": extract("long_name", soup), "tags": extract("tags", soup), "content": extract("content", soup), } create_wiki(wiki) # create mct if "frage" in get_type(soup): question = { "root": root, "slug": root.split("/")[-1], "category": "", #Category #"title": extract("question", soup), "answers": extract("answers", soup), #"description": extract("description", soup), "order": extract("order", soup), } question = create_question(question) question_version = { "question_id": question.id, "title": extract("question", soup), "answers": extract("answers", soup), "description": extract("description", soup), } create_question_version(question_version) # output #categories = Category.objects.all() return render(request, "core/categories.html", { "categories": [], "wikis": [], "questions": [], })
def get_context_data(self, tag, **kwargs): context = super(TagPageView, self).get_context_data(**kwargs) current_site = Site.objects.get_current() current_language_code = translation.get_language() tag_instance = get_tag(tag) if tag_instance is None: raise Http404(_('No Tag found matching "%s".') % tag) try: article = Article.get_for_object(tag_instance) except ArticleForObject.DoesNotExist: # Get or create root try: root_path = URLPath.root() except NoRootURL: root_path = URLPath.create_root(site=current_site) # Get current language namespace. E.g. "/fr" try: language_ns_path = URLPath.get_by_path("/%s" % current_language_code) except URLPath.DoesNotExist: language_ns_path = URLPath.create_article( parent=root_path, slug=current_language_code, site=current_site, title=current_language_code) # Get or create the article from django.template.defaultfilters import slugify tag_slug = slugify(tag_instance.name) try: article_path = URLPath.get_by_path( "/%s/%s" % (current_language_code, tag_slug)) except URLPath.DoesNotExist: article_path = URLPath.create_article(parent=language_ns_path, slug=tag_slug, site=current_site, title=tag_instance.name) # Get the wiki article itself article = article_path.article article.add_object_relation(tag_instance) context['article'] = article # XXX: site not taken in account context['tag'] = tag_instance context['related_tags'] = list( reversed( sorted( Tag.objects.related_for_model(tag_instance, I4pProject, counts=True), key=attrgetter('count'), )))[:15] # Get project sheets tagged with this tag XXX: site=site may # not be correct 4 Random projects with at least one picture. # It's not possible to mix distinct and order by random, so # use a trick hilighted_projects = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter( language_code=current_language_code, master__site=current_site, master__pictures__isnull=False).distinct(), tag_instance).distinct() context['picture_projects'] = random.sample( hilighted_projects, min(4, len(hilighted_projects))) # Mature projects mature_projects = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter( master__site=current_site, master__status__in=('WIP', 'END')).distinct(), tag_instance).distinct() context['num_mature_projects_projects_with_tag'] = len(mature_projects) context['mature_projects'] = random.sample( mature_projects, min(4, len(mature_projects))) # Starting projects starting_projects = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter( master__site=current_site, master__status__in=('IDEA', 'BEGIN')).distinct(), tag_instance).distinct() context['num_starting_projects_projects_with_tag'] = len( starting_projects) context['starting_projects'] = random.sample( starting_projects, min(4, len(starting_projects))) # New projects context['new_projects'] = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter( master__site=current_site, ).distinct(), tag_instance).order_by('-master__created')[:4] # Latest modifications context['modified_projects'] = TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter( master__site=current_site, ).distinct(), tag_instance).order_by('-modified')[:4] # Related people # List is to force evaluation to avoid a sql bug in queryset combining later (project__in=projects) projects = list( TaggedItem.objects.get_by_model( I4pProject.objects.using_translations().filter( master__site=current_site, ).distinct(), tag_instance).all()) # While we're at it, let's count them for free context['num_projects_with_tag'] = len(projects) context['people'] = ProjectMember.objects.filter( project__in=projects).order_by('?')[:6] return context
def get_context_data(self, tag, **kwargs): context = super(TagPageView, self).get_context_data(**kwargs) current_site = Site.objects.get_current() current_language_code = translation.get_language() tag_instance = get_tag(tag) if tag_instance is None: raise Http404(_('No Tag found matching "%s".') % tag) try: article = Article.get_for_object(tag_instance) except ArticleForObject.DoesNotExist: # Get or create root try: root_path = URLPath.root() except NoRootURL: root_path = URLPath.create_root(site=current_site) # Get current language namespace. E.g. "/fr" try: language_ns_path = URLPath.get_by_path("/%s" % current_language_code) except URLPath.DoesNotExist: language_ns_path = URLPath.create_article( parent=root_path, slug=current_language_code, site=current_site, title=current_language_code ) # Get or create the article from django.template.defaultfilters import slugify tag_slug = slugify(tag_instance.name) try: article_path = URLPath.get_by_path("/%s/%s" % (current_language_code, tag_slug) ) except URLPath.DoesNotExist: article_path = URLPath.create_article( parent=language_ns_path, slug=tag_slug, site=current_site, title=tag_instance.name ) # Get the wiki article itself article = article_path.article article.add_object_relation(tag_instance) context['article'] = article # XXX: site not taken in account context['tag'] = tag_instance context['related_tags'] = list( reversed( sorted(Tag.objects.related_for_model(tag_instance, I4pProjectTranslation, counts=True), key=attrgetter('count'), ) ) )[:15] # Get project sheets tagged with this tag XXX: site=site may # not be correct 4 Random projects with at least one picture. # It's not possible to mix distinct and order by random, so # use a trick hilighted_projects= TaggedItem.objects.get_by_model(I4pProjectTranslation.objects.filter( language_code=current_language_code, project__site=current_site, project__pictures__isnull=False ).distinct(), tag_instance).distinct() context['picture_project_translations'] = random.sample(hilighted_projects, min(4, len(hilighted_projects))) # Mature projects mature_project_translations = TaggedItem.objects.get_by_model(I4pProjectTranslation.objects.filter( language_code=current_language_code, project__site=current_site, project__status__in=('WIP', 'END') ).distinct(), tag_instance).distinct() context['mature_project_translations'] = random.sample(mature_project_translations, min(4, len(mature_project_translations))) # Starting projects starting_project_translations = TaggedItem.objects.get_by_model(I4pProjectTranslation.objects.filter( language_code=current_language_code, project__site=current_site, project__status__in=('IDEA', 'BEGIN') ).distinct(), tag_instance).distinct() context['starting_project_translations'] = random.sample(starting_project_translations, min(4, len(starting_project_translations))) # New projects context['new_project_translations'] = TaggedItem.objects.get_by_model(I4pProjectTranslation.objects.filter( language_code=current_language_code, project__site=current_site, ).distinct(), tag_instance).order_by('-project__created')[:4] # Latest modifications context['modified_project_translations'] = TaggedItem.objects.get_by_model(I4pProjectTranslation.objects.filter( language_code=current_language_code, project__site=current_site, ).distinct(), tag_instance).order_by('-modified')[:4] # Related people project_translations = ModelTaggedItemManager().with_any([tag_instance.name], I4pProjectTranslation.objects.filter( language_code=current_language_code, project__site=current_site, ) ).distinct() projects = [p.project for p in project_translations] context['people'] = ProjectMember.objects.filter( project__in=projects ).order_by('?')[:6] return context
def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} extra_context['buttons'] = self.get_buttons(request, None) c_url = resolve(request.path_info) if c_url.namespace: url_name = '%s:%s' % (c_url.namespace, c_url.url_name) else: url_name = '%s' % c_url.url_name try: admin_config = UserAdminConfig.objects.filter(user=request.user, url_name=url_name)[0] admin_old_url = admin_config.url_full_path admin_config.url_name = url_name admin_config.url_full_path = request.get_full_path() admin_config.save() except IndexError: admin_old_url = None admin_config = UserAdminConfig.objects.create( user=request.user, url_name=url_name, url_full_path=request.get_full_path(), ) if admin_old_url == request.get_full_path(): admin_old_url = None extra_context['admin_old_url'] = admin_old_url opts = self.model._meta app_label = opts.app_label multi_search_fields = [] for field_opts in self.multi_search: attributes = { 'size': '40', } if len(field_opts) == 4: attributes.update(field_opts[3]) multi_search_fields.append({ 'name': field_opts[0], 'label': field_opts[1], 'value': request.GET.get(field_opts[0], ''), 'attributes': ' '.join(['%s="%s"' % (k, v) for k, v in attributes.items()]), }) buttons = self.get_buttons(request, None) if POWERADMIN_USE_WIKI: path = '{0}-{1}'.format(app_label.lower(), opts.object_name.lower()) from wiki.models import Article, ArticleRevision, URLPath from django.contrib.sites.models import get_current_site if not URLPath.objects.filter(slug=path).count(): if not URLPath.objects.count(): URLPath.create_root( site=get_current_site(request), title=u'Root', content=u"", request=request ) root = URLPath.objects.order_by('id')[0] URLPath.create_article( root, path, site=get_current_site(request), title=path, content=u"", user_message=u"", user=request.user, ip_address=request.META['REMOTE_ADDR'], article_kwargs={ 'owner': request.user } ) buttons.append(PowerButton(url=POWERADMIN_WIKI_ARTICLE_URL.format(path=path), label=u'Ajuda', attrs={'target': '_blank'})) context_data = { 'buttons': buttons, 'multi_search': True, 'multi_search_keys': multi_search_fields, 'admin_old_url': admin_old_url, } self.change_list_template = self.get_changelist_template() extra_context.update(context_data) return super(PowerModelAdmin, self).changelist_view(request, extra_context)