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 get_class(self, el): href = el.get("href") if not href: return # The autolinker turns email links into links with many HTML entities. # These entities are further escaped using markdown-specific codes. # First unescape the markdown-specific, then use html.unescape. href = AndSubstitutePostprocessor().run(href) href = html.unescape(href) try: url = urlparse(href) except ValueError: return if url.scheme == "mailto": return if url.scheme or url.netloc or url.path.startswith("/"): # Contains a hostname or is an absolute link => external return self.external_class # Ensure that path ends with a slash relpath = url.path.rstrip("/") + "/" target = urljoin_internal(self.my_urlpath.path, relpath) if target is None: # Relative path goes outside wiki URL space => external return self.external_class try: URLPath.get_by_path(target) except URLPath.DoesNotExist: return self.broken_class return self.internal_class
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 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 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 get_article(self, cont): urlpath = URLPath.create_urlpath( URLPath.root(), "html_attach", title="TestAttach", content=cont ) self._create_test_attachment(urlpath.path) return urlpath.article.render()
def get_article(self, cont, image): urlpath = URLPath.create_urlpath( URLPath.root(), "html_image", title="TestImage", content=cont ) if image: self._create_test_image(urlpath.path) return urlpath.article.render()
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_edit_save(self): old_revision = URLPath.root().article.current_revision self.get_url('wiki:edit', path='') self.fill({ '#id_content': 'Something 2', '#id_summary': 'why edited', '#id_title': 'wiki test' }) self.submit('#id_save') self.assertTextPresent('Something 2') self.assertTextPresent('successfully added') new_revision = URLPath.root().article.current_revision self.assertIn('Something 2', new_revision.content) self.assertEqual(new_revision.revision_number, old_revision.revision_number + 1)
def test_revision_conflict(self): """ Test the warning if the same article is being edited concurrently. """ example_data = { 'content': 'More modifications', 'current_revision': str(URLPath.root().article.current_revision.id), 'preview': '0', 'save': '1', 'summary': 'why edited', 'title': 'wiki test' } response = self.client.post( resolve_url('wiki:edit', path=''), example_data ) self.assertRedirects(response, resolve_url('wiki:root')) response = self.client.post( resolve_url('wiki:edit', path=''), example_data ) self.assertContains( response, 'While you were editing, someone else changed the revision.' )
def setUp(self): """Test setup.""" self.wiki = get_or_create_root() self.course_math101 = CourseFactory.create(org='edx', number='math101', display_name='2014', metadata={'use_unique_wiki_id': 'false'}) self.course_math101_instructor = InstructorFactory(course_key=self.course_math101.id, username='******', password='******') self.wiki_math101 = URLPath.create_article(self.wiki, 'math101', title='math101') self.client = Client() self.client.login(username='******', password='******')
def test_html_removal(self): urlpath = URLPath.create_article( self.root, 'html_removal', title="Test 1", content="</html>only_this" ) self.assertEqual(urlpath.article.render(), "<p></html>only_this</p>")
def get_urlpath(course_id): """Returns url path of root wiki page for course.""" # Offical edX way to replace slashes by dots: course_key.replace('/', '.') course_key = CourseKey.from_string(course_id) course = get_course_by_id(course_key) course_slug = course_wiki_slug(course) try: urlpath = URLPath.get_by_path(course_slug) except URLPath.DoesNotExist: urlpath = None return urlpath
def create(cls, user, regional_level, title, question, topics, organisation=None): try: root_path = URLPath.objects.get(parent_id=None) except Exception: pass else: # Construct arguments user_regional_levels = { '1': user.personalid.municipality, '2': user.personalid.province, '3': user.personalid.country } regional_name = user_regional_levels[regional_level] slug = str(regional_level) + '_' + regional_name + '_' + slugify(title) content = '# Context\r\n# Consequences\r\n' user_message = 'Initiated \'{}\''.format(title) article_kwargs = { 'owner': user, 'group': None, 'group_read': True, 'group_write': False, 'other_read': False, 'other_write': False } # Make new wiki URLPath new_url_path = URLPath.create_article(root_path, slug, title=title, article_kwargs=article_kwargs, content=content, user_message=user_message, user=user) new_url_path.save() try: # Make new ConstructionProposal construction_proposal = cls(regional_level=regional_level, regional_name=regional_name, title=title, slug=slug, question=question, creator=user, organisation=organisation, wiki=new_url_path) construction_proposal.save() except Exception: pass else: # Add topics construction_proposal.topics.add(*topics) # Return partially saved instance return construction_proposal return None
def test_preview_and_save(self): self.get_url('wiki:edit', path='') self.fill({ '#id_content': 'Some changed stuff', '#id_summary': 'why edited', '#id_title': 'wiki test' }) self.click('#id_preview') self.submit('#id_preview_save_changes') new_revision = URLPath.root().article.current_revision self.assertIn("Some changed stuff", new_revision.content)
def setUp(self): super(ArticleWebTestBase, self).setUp() response = self.c.post( reverse('wiki:root_create'), {'content': 'root article content', 'title': 'Root Article'}, follow=True ) self.assertEqual(response.status_code, 200) # sanity check self.root_article = URLPath.root().article
def setUp(self): """Test setup.""" self.wiki = get_or_create_root() self.course_math101 = CourseFactory.create( org="edx", number="math101", display_name="2014", metadata={"use_unique_wiki_id": "false"} ) self.course_math101_instructor = InstructorFactory( course=self.course_math101.location, username="******", password="******" ) self.wiki_math101 = URLPath.create_article(self.wiki, "math101", title="math101") self.client = Client() self.client.login(username="******", password="******")
def setUp(self): super(ArticleTestBase, self).setUp() response = self.c.post( reverse('wiki:root_create'), {'content': 'root article content', 'title': 'Root Article'}, follow=True) self.assertEqual(response.status_code, 200) # sanity check self.root_article = URLPath.root().article self.example_data = { 'content': 'The modified text', 'current_revision': '1', 'preview': '1', # 'save': '1', # probably not too important 'summary': 'why edited', 'title': 'wiki test'}
def test_article_list_update(self): """ Test automatic adding and removing the new article to/from article_list. """ root_data = { 'content': '[article_list depth:2]', 'current_revision': str(URLPath.root().article.current_revision.id), 'preview': '1', 'title': 'Root Article' } response = self.client.post(resolve_url('wiki:edit', path=''), root_data) self.assertRedirects(response, resolve_url('wiki:root')) # verify the new article is added to article_list response = self.client.post( resolve_url('wiki:create', path=''), {'title': 'Sub Article 1', 'slug': 'SubArticle1'} ) self.assertRedirects( response, resolve_url('wiki:get', path='subarticle1/') ) self.assertContains(self.get_by_path(''), 'Sub Article 1') self.assertContains(self.get_by_path(''), 'subarticle1/') # verify the deleted article is removed from article_list response = self.client.post( resolve_url('wiki:delete', path='SubArticle1/'), {'confirm': 'on', 'purge': 'on', 'revision': str(URLPath.objects.get(slug='subarticle1').article.current_revision.id), } ) message = getattr(self.client.cookies['messages'], 'value') self.assertRedirects( response, resolve_url('wiki:get', path='') ) self.assertIn( 'This article together with all ' 'its contents are now completely gone', message) self.assertNotContains(self.get_by_path(''), 'Sub Article 1')
def setUp(self): super(TestAttachmentManagementCommands, self).setUp() self.test_file = tempfile.NamedTemporaryFile('w', delete=False, suffix=".txt") self.test_file.write("test") self.child1 = URLPath.create_urlpath(self.root, 'test-slug', title="Test 1") self.attachment1 = models.Attachment.objects.create( article=self.child1.article ) self.attachment1_revision1 = models.AttachmentRevision.objects.create( attachment=self.attachment1, file=self.test_file.name, )
def test_root_article(self): """ Test redirecting to /create-root/, creating the root article and a simple markup. """ self.get_url('wiki:root') self.assertUrlsEqual(resolve_url('wiki:root_create')) self.fill({ '#id_content': 'test heading h1\n====\n', '#id_title': 'Wiki Test', }) self.submit('input[name="save_changes"]') self.assertUrlsEqual('/') self.assertTextPresent('test heading h1') article = URLPath.root().article self.assertIn('test heading h1', article.current_revision.content)
def test_preview_xframe_options_sameorigin(self): """Ensure that preview response has X-Frame-Options: SAMEORIGIN""" example_data = { 'content': 'The modified text', 'current_revision': str(URLPath.root().article.current_revision.id), 'preview': '1', 'summary': 'why edited', 'title': 'wiki test' } response = self.client.post( resolve_url('wiki:preview', path=''), example_data ) self.assertEquals(response.get('X-Frame-Options'), 'SAMEORIGIN')
def wiki_articles_in_menu(request): wiki_root = URLPath.root() urls = [wiki_root] for subroot in wiki_root.children.all(): urls.append(subroot) items = [] for url in urls: if url.article.can_read(request.user): items.append({ 'url_regex': r'^' + str(url) + ('$' if url.parent is None else ''), 'text': url.article.current_revision.title, 'link': url.article.get_absolute_url(), }) return items
def test_preview_save(self): """Test edit preview, edit save and messages.""" example_data = { 'content': 'The modified text', 'current_revision': str(URLPath.root().article.current_revision.id), 'preview': '1', # 'save': '1', # probably not too important 'summary': 'why edited', 'title': 'wiki test' } # test preview response = self.client.post( resolve_url('wiki:preview', path=''), # url: '/_preview/' example_data ) self.assertContains(response, 'The modified text')
def test_history(self): url = reverse('wiki:globalhistory') response = self.c.get(url) expected = ( '(?s)<title>Global history.*' '>Global history</.*' 'List of all <strong>1 changes</strong>.*' 'Root Article.*no log message.*' '</table>' ) self._assertRegex(response.rendered_content, expected) URLPath.create_article(URLPath.root(), "testhistory1", title="TestHistory1", content="a page", user_message="Comment 1") response = self.c.get(url) expected = ( '(?s)<title>Global history.*' '>Global history</.*' 'List of all <strong>2 changes</strong>.*' 'TestHistory1.*Comment 1.*' 'Root Article.*no log message.*' '</table>' ) self._assertRegex(response.rendered_content, expected) URLPath.create_article(URLPath.root(), "testhistory2", title="TestHistory2", content="a page", user_message="Comment 2") response = self.c.get(url) expected = ( '(?s)<title>Global history.*' '>Global history</.*' 'List of all <strong>3 changes</strong>.*' 'TestHistory2.*Comment 2.*' 'TestHistory1.*Comment 1.*' 'Root Article.*no log message.*' '</table>' ) self._assertRegex(response.rendered_content, expected)
def get(self, request, *args, **kwargs): auth_logout(request) messages.info(request, _(u"You are no longer logged in. Bye bye!")) return redirect("wiki:get", URLPath.root().path)
def test_move(self): # Create a hierarchy of pages self.client.post( resolve_url("wiki:create", path=""), {"title": "Test", "slug": "test0", "content": "Content .0."}, ) self.client.post( resolve_url("wiki:create", path="test0/"), {"title": "Test00", "slug": "test00", "content": "Content .00."}, ) self.client.post( resolve_url("wiki:create", path=""), {"title": "Test1", "slug": "test1", "content": "Content .1."}, ) self.client.post( resolve_url("wiki:create", path="test1/"), {"title": "Tes10", "slug": "test10", "content": "Content .10."}, ) self.client.post( resolve_url("wiki:create", path="test1/test10/"), {"title": "Test100", "slug": "test100", "content": "Content .100."}, ) # Move /test1 => /test0 (an already existing destination slug!) response = self.client.post( resolve_url("wiki:move", path="test1/"), { "destination": str(URLPath.root().article.current_revision.id), "slug": "test0", "redirect": "", }, ) self.assertContains(response, "A slug named") self.assertContains(response, "already exists.") # Move /test1 >= /test2 (valid slug), no redirect test0_id = URLPath.objects.get(slug="test0").article.current_revision.id response = self.client.post( resolve_url("wiki:move", path="test1/"), {"destination": str(test0_id), "slug": "test2", "redirect": ""}, ) self.assertRedirects(response, resolve_url("wiki:get", path="test0/test2/")) # Check that there is no article displayed in this path anymore response = self.get_by_path("test1/") self.assertRedirects(response, "/_create/?slug=test1") # Create /test0/test2/test020 response = self.client.post( resolve_url("wiki:create", path="test0/test2/"), {"title": "Test020", "slug": "test020", "content": "Content .020."}, ) # Move /test0/test2 => /test1new + create redirect response = self.client.post( resolve_url("wiki:move", path="test0/test2/"), { "destination": str(URLPath.root().article.current_revision.id), "slug": "test1new", "redirect": "true", }, ) self.assertRedirects(response, resolve_url("wiki:get", path="test1new/")) # Check that /test1new is a valid path response = self.get_by_path("test1new/") self.assertContains(response, "Content .1.") # Check that the child article test0/test2/test020 was also moved response = self.get_by_path("test1new/test020/") self.assertContains(response, "Content .020.") response = self.get_by_path("test0/test2/") self.assertContains(response, "Moved: Test1") self.assertRegex(response.rendered_content, r"moved to <a[^>]*>wiki:/test1new/") response = self.get_by_path("test0/test2/test020/") self.assertContains(response, "Moved: Test020") self.assertRegex( response.rendered_content, r"moved to <a[^>]*>wiki:/test1new/test020" ) # Check that moved_to was correctly set urlsrc = URLPath.get_by_path("/test0/test2/") urldst = URLPath.get_by_path("/test1new/") self.assertEqual(urlsrc.moved_to, urldst) # Check that moved_to was correctly set on the child's previous path urlsrc = URLPath.get_by_path("/test0/test2/test020/") urldst = URLPath.get_by_path("/test1new/test020/") self.assertEqual(urlsrc.moved_to, urldst)
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 test_history(self): url = reverse('wiki:globalhistory') url0 = reverse('wiki:globalhistory', kwargs={'only_last': '0'}) url1 = reverse('wiki:globalhistory', kwargs={'only_last': '1'}) response = self.client.get(url) expected = ('(?s).*Root Article.*no log message.*') self.assertRegexpMatches(response.rendered_content, expected) URLPath.create_urlpath(URLPath.root(), "testhistory1", title="TestHistory1", content="a page", user_message="Comment 1") response = self.client.get(url) expected = ('(?s).*TestHistory1.*Comment 1.*' 'Root Article.*no log message.*') self.assertRegexpMatches(response.rendered_content, expected) urlpath = URLPath.create_urlpath(URLPath.root(), "testhistory2", title="TestHistory2", content="a page", user_message="Comment 2") expected = ('(?s).*TestHistory2.*Comment 2.*' 'TestHistory1.*Comment 1.*' 'Root Article.*no log message.*') response = self.client.get(url) self.assertRegexpMatches(response.rendered_content, expected) response = self.client.get(url0) self.assertRegexpMatches(response.rendered_content, expected) response = self.client.get(url1) self.assertRegexpMatches(response.rendered_content, expected) response = self.client.post( reverse('wiki:edit', kwargs={'path': 'testhistory2/'}), { 'content': 'a page modified', 'current_revision': str(urlpath.article.current_revision.id), 'preview': '0', 'save': '1', 'summary': 'Testing Revision', 'title': 'TestHistory2Mod' }) expected = ('(?s).*TestHistory2Mod.*Testing Revision.*' 'TestHistory2.*Comment 2.*' 'TestHistory1.*Comment 1.*' 'Root Article.*no log message.*') response = self.client.get(url) self.assertRegexpMatches(response.rendered_content, expected) response = self.client.get(url0) self.assertRegexpMatches(response.rendered_content, expected) expected = ('(?s).*TestHistory2Mod.*Testing Revision.*' 'TestHistory1.*Comment 1.*' 'Root Article.*no log message.*') response = self.client.get(url1) self.assertRegexpMatches(response.rendered_content, expected)
def test_history(self): url = reverse("wiki:globalhistory") url0 = reverse("wiki:globalhistory", kwargs={"only_last": "0"}) url1 = reverse("wiki:globalhistory", kwargs={"only_last": "1"}) response = self.client.get(url) expected = "(?s).*Root Article.*no log message.*" self.assertRegexpMatches(response.rendered_content, expected) URLPath.create_urlpath( URLPath.root(), "testhistory1", title="TestHistory1", content="a page", user_message="Comment 1", ) response = self.client.get(url) expected = "(?s).*TestHistory1.*Comment 1.*" "Root Article.*no log message.*" self.assertRegexpMatches(response.rendered_content, expected) urlpath = URLPath.create_urlpath( URLPath.root(), "testhistory2", title="TestHistory2", content="a page", user_message="Comment 2", ) expected = ("(?s).*TestHistory2.*Comment 2.*" "TestHistory1.*Comment 1.*" "Root Article.*no log message.*") response = self.client.get(url) self.assertRegexpMatches(response.rendered_content, expected) response = self.client.get(url0) self.assertRegexpMatches(response.rendered_content, expected) response = self.client.get(url1) self.assertRegexpMatches(response.rendered_content, expected) response = self.client.post( reverse("wiki:edit", kwargs={"path": "testhistory2/"}), { "content": "a page modified", "current_revision": str(urlpath.article.current_revision.id), "preview": "0", "save": "1", "summary": "Testing Revision", "title": "TestHistory2Mod", }, ) expected = ("(?s).*TestHistory2Mod.*Testing Revision.*" "TestHistory2.*Comment 2.*" "TestHistory1.*Comment 1.*" "Root Article.*no log message.*") response = self.client.get(url) self.assertRegexpMatches(response.rendered_content, expected) response = self.client.get(url0) self.assertRegexpMatches(response.rendered_content, expected) expected = ("(?s).*TestHistory2Mod.*Testing Revision.*" "TestHistory1.*Comment 1.*" "Root Article.*no log message.*") response = self.client.get(url1) self.assertRegexpMatches(response.rendered_content, expected)
def course_wiki_redirect(request, course_id): """ This redirects to whatever page on the wiki that the course designates as it's home page. A course's wiki must be an article on the root (for example, "/6.002x") to keep things simple. """ course = get_course_by_id(course_id) course_slug = course.wiki_slug # cdodge: fix for cases where self.location.course can be interpreted as an number rather than # a string. We're seeing in Studio created courses that people often will enter in a stright number # for 'course' (e.g. 201). This Wiki library expects a string to "do the right thing". We haven't noticed this before # because - to now - 'course' has always had non-numeric characters in them try: float(course_slug) # if the float() doesn't throw an exception, that means it's a number course_slug = course_slug + "_" except: pass valid_slug = True if not course_slug: log.exception("This course is improperly configured. The slug cannot be empty.") valid_slug = False if re.match("^[-\w\.]+$", course_slug) is None: log.exception( "This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens." ) valid_slug = False if not valid_slug: return redirect("wiki:get", path="") # The wiki needs a Site object created. We make sure it exists here try: site = Site.objects.get_current() except Site.DoesNotExist: new_site = Site() new_site.domain = settings.SITE_NAME new_site.name = "edX" new_site.save() if str(new_site.id) != str(settings.SITE_ID): raise ImproperlyConfigured( "No site object was created and the SITE_ID doesn't match the newly created one. " + str(new_site.id) + "!=" + str(settings.SITE_ID) ) try: urlpath = URLPath.get_by_path(course_slug, select_related=True) results = list(Article.objects.filter(id=urlpath.article.id)) if results: article = results[0] else: article = None except (NoRootURL, URLPath.DoesNotExist): # We will create it in the next block urlpath = None article = None if not article: # create it root = get_or_create_root() if urlpath: # Somehow we got a urlpath without an article. Just delete it and # recerate it. urlpath.delete() urlpath = URLPath.create_article( root, course_slug, title=course_slug, content="This is the wiki for **{0}**'s _{1}_.".format(course.org, course.display_name_with_default), user_message="Course page automatically created.", user=None, ip_address=None, article_kwargs={ "owner": None, "group": None, "group_read": True, "group_write": True, "other_read": True, "other_write": True, }, ) return redirect("wiki:get", path=urlpath.path)
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 view_redirect(u: URLPath) -> HttpResponseRedirect: return HttpResponseRedirect(u.get_absolute_url())
def course_wiki_redirect(request, course_id): # pylint: disable=unused-argument """ This redirects to whatever page on the wiki that the course designates as it's home page. A course's wiki must be an article on the root (for example, "/6.002x") to keep things simple. """ course = get_course_by_id( SlashSeparatedCourseKey.from_deprecated_string(course_id)) course_slug = course_wiki_slug(course) valid_slug = True if not course_slug: log.exception( "This course is improperly configured. The slug cannot be empty.") valid_slug = False if re.match(r'^[-\w\.]+$', course_slug) is None: log.exception( "This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens." ) valid_slug = False if not valid_slug: return redirect("wiki:get", path="") # The wiki needs a Site object created. We make sure it exists here try: Site.objects.get_current() except Site.DoesNotExist: new_site = Site() new_site.domain = settings.SITE_NAME new_site.name = "edX" new_site.save() site_id = str(new_site.id) if site_id != str(settings.SITE_ID): raise ImproperlyConfigured( "No site object was created and the SITE_ID doesn't match the newly created one. {} != {}" .format(site_id, settings.SITE_ID)) try: urlpath = URLPath.get_by_path(course_slug, select_related=True) results = list(Article.objects.filter(id=urlpath.article.id)) if results: article = results[0] else: article = None except (NoRootURL, URLPath.DoesNotExist): # We will create it in the next block urlpath = None article = None if not article: # create it root = get_or_create_root() if urlpath: # Somehow we got a urlpath without an article. Just delete it and # recerate it. urlpath.delete() content = cgi.escape( # Translators: this string includes wiki markup. Leave the ** and the _ alone. _("This is the wiki for **{organization}**'s _{course_name}_." ).format( organization=course.display_org_with_default, course_name=course.display_name_with_default_escaped, )) urlpath = URLPath.create_article( root, course_slug, title=course_slug, content=content, user_message=_("Course page automatically created."), user=None, ip_address=None, article_kwargs={ 'owner': None, 'group': None, 'group_read': True, 'group_write': True, 'other_read': True, 'other_write': True, }) return redirect("wiki:get", path=urlpath.path)
def test_editsection(self): # Test creating links to allow editing all sections individually urlpath = URLPath.create_urlpath(URLPath.root(), "testedit", title="TestEdit", content=TEST_CONTENT) output = urlpath.article.render() expected = ( r"(?s)" r'Title 1<a class="article-edit-title-link" href="/testedit/_plugin/editsection/1-0-0/header/T1/">\[edit\]</a>.*' r'Title 2<a class="article-edit-title-link" href="/testedit/_plugin/editsection/1-1-0/header/T2/">\[edit\]</a>.*' r'Title 3<a class="article-edit-title-link" href="/testedit/_plugin/editsection/1-2-0/header/T3/">\[edit\]</a>.*' r'Title 4<a class="article-edit-title-link" href="/testedit/_plugin/editsection/1-2-1/header/T4/">\[edit\]</a>.*' r'Title 5<a class="article-edit-title-link" href="/testedit/_plugin/editsection/1-3-0/header/T5/">\[edit\]</a>.*' r'Title 6<a class="article-edit-title-link" href="/testedit/_plugin/editsection/2-0-0/header/T6/">\[edit\]</a>.*' ) self.assertRegex(output, expected) # Test wrong header text. Editing should fail with a redirect. url = reverse( "wiki:editsection", kwargs={ "path": "testedit/", "location": "1-2-1", "header": "Test" }, ) response = self.client.get(url) self.assertRedirects(response, reverse("wiki:get", kwargs={"path": "testedit/"})) # Test extracting sections for editing url = reverse( "wiki:editsection", kwargs={ "path": "testedit/", "location": "1-2-1", "header": "T4" }, ) response = self.client.get(url) expected = ">### Title 4[\r\n]*" "<" self.assertRegex(response.rendered_content, expected) url = reverse( "wiki:editsection", kwargs={ "path": "testedit/", "location": "1-2-0", "header": "T3" }, ) response = self.client.get(url) expected = (">Title 3[\r\n]*" "-------[\r\n]*" "a[\r\n]*" "Paragraph[\r\n]*" "-------[\r\n]*" "### Title 4[\r\n]*" "<") self.assertRegex(response.rendered_content, expected)
def get(self, request, *args, **kwargs): s = '' start_page = Article.objects.get(urlpath=URLPath.root()) # supersenses try: ss = models.SimpleMetadata.objects.get(article=Article.objects.get( urlpath=URLPath.objects.get(slug='supersenses'))) s += 'Already exists: <a href="' + ss.article.get_absolute_url( ) + '">supersenses</a>. ' except (URLPath.DoesNotExist, Article.DoesNotExist, models.SimpleMetadata.DoesNotExist): s += 'Installing supersenses...' meta = models.SimpleMetadata() article_urlpath = URLPath.create_article( URLPath.root(), slug='supersenses', title='List of Supersenses', content= 'The following are the supersense categories for adpositions and case:', user_message="Metadata install", user=request.user, article_kwargs={ 'owner': request.user, 'group': start_page.group, 'group_read': start_page.group_read, 'group_write': start_page.group_write, 'other_read': start_page.other_read, 'other_write': start_page.other_write, }) newarticle = models.Article.objects.get(urlpath=article_urlpath) meta.article = newarticle meta.save() s += '<a href="' + newarticle.get_absolute_url() + '">done</a>. ' # construals try: c = models.SimpleMetadata.objects.get(article=Article.objects.get( urlpath=URLPath.objects.get(slug='construals'))) s += 'Already exists: <a href="' + c.article.get_absolute_url( ) + '">construals</a>. ' except (URLPath.DoesNotExist, Article.DoesNotExist, models.SimpleMetadata.DoesNotExist): s += 'Installing construals...' meta = models.SimpleMetadata() article_urlpath = URLPath.create_article( URLPath.root(), slug='construals', title='List of Construals', content= 'The following are the construals of the [supersense categories](/supersenses) for adpositions and case:', user_message="Metadata install", user=request.user, article_kwargs={ 'owner': request.user, 'group': start_page.group, 'group_read': start_page.group_read, 'group_write': start_page.group_write, 'other_read': start_page.other_read, 'other_write': start_page.other_write, }) newarticle = models.Article.objects.get(urlpath=article_urlpath) meta.article = newarticle meta.save() s += '<a href="' + newarticle.get_absolute_url() + '">done</a>. ' return HttpResponse(mark_safe(s))
def setUp(self): super().setUp() self.child = URLPath.create_urlpath(self.root, "child")
def wrapper(request, *args, **kwargs): #path = kwargs.pop('path', None) site = Site.objects.get_current() path = 'uga/' parent = URLPath.objects.get(slug='uga') article_id = kwargs.pop('article_id', None) #print('Request: ' + request) #print('Kwargs: ' + kwargs) urlpath = None #print('Path: ' + path) # fetch by urlpath.path if path is not None: try: urlpath = URLPath.get_by_path(path, select_related=True) #urlpath = URLPath.create_urlpath(parent,'/' ) print(urlpath) except NoRootURL: return redirect('root_create') except URLPath.DoesNotExist: try: print('Hello') pathlist = list( filter( lambda x: x != "", path.split("/"), )) path = "/".join(pathlist[:-1]) parent = URLPath.get_by_path(path) return HttpResponseRedirect( reverse( "create", kwargs={'path': parent.path, }) + "?slug=%s" % pathlist[-1].lower()) except URLPath.DoesNotExist: print('Hello 123123132') return HttpResponseNotFound( render_to_string( "wiki/error.html", context={ 'error_type': 'ancestors_missing' }, request=request)) if urlpath.article: # urlpath is already smart about prefetching items on article # (like current_revision), so we don't have to print('test') article = urlpath.article else: # Be robust: Somehow article is gone but urlpath exists... # clean up print('Hello Jonathan and Ferhat') return_url = reverse( 'wiki:get', kwargs={ 'path': urlpath.parent.path}) urlpath.delete() return HttpResponseRedirect(return_url) # fetch by article.id elif article_id: # TODO We should try to grab the article form URLPath so the # caching is good, and fall back to grabbing it from # Article.objects if not articles = Article.objects article = get_object_or_404(articles, id=article_id) try: urlpath = URLPath.objects.get(articles__article=article) except (URLPath.DoesNotExist, URLPath.MultipleObjectsReturned): urlpath = None else: raise TypeError('You should specify either article_id or path') if not deleted_contents: # If the article has been deleted, show a special page. if urlpath: if urlpath.is_deleted(): # This also checks all ancestors return redirect('wiki:deleted', path=urlpath.path) else: if article.current_revision and article.current_revision.deleted: return redirect('wiki:deleted', article_id=article.id) if article.current_revision.locked and not_locked: return response_forbidden(request, article, urlpath) if can_read and not article.can_read(request.user): return response_forbidden(request, article, urlpath) if (can_write or can_create) and not article.can_write(request.user): return response_forbidden(request, article, urlpath) if can_create and not ( request.user.is_authenticated() or settings.ANONYMOUS_CREATE): return response_forbidden(request, article, urlpath) if can_delete and not article.can_delete(request.user): return response_forbidden(request, article, urlpath) if can_moderate and not article.can_moderate(request.user): return response_forbidden(request, article, urlpath) kwargs['urlpath'] = urlpath print('hello1') return func(request, article, *args, **kwargs)
def course_wiki_redirect(request, course_id): """ This redirects to whatever page on the wiki that the course designates as it's home page. A course's wiki must be an article on the root (for example, "/6.002x") to keep things simple. """ course = get_course_by_id(course_id) course_slug = course.wiki_slug # cdodge: fix for cases where self.location.course can be interpreted as an number rather than # a string. We're seeing in Studio created courses that people often will enter in a stright number # for 'course' (e.g. 201). This Wiki library expects a string to "do the right thing". We haven't noticed this before # because - to now - 'course' has always had non-numeric characters in them try: float(course_slug) # if the float() doesn't throw an exception, that means it's a number course_slug = course_slug + "_" except: pass valid_slug = True if not course_slug: log.exception( "This course is improperly configured. The slug cannot be empty.") valid_slug = False if re.match(r'^[-\w\.]+$', course_slug) is None: log.exception( "This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens." ) valid_slug = False if not valid_slug: return redirect("wiki:get", path="") # The wiki needs a Site object created. We make sure it exists here try: site = Site.objects.get_current() except Site.DoesNotExist: new_site = Site() new_site.domain = settings.SITE_NAME new_site.name = "edX" new_site.save() if str(new_site.id) != str(settings.SITE_ID): raise ImproperlyConfigured( "No site object was created and the SITE_ID doesn't match the newly created one. " + str(new_site.id) + "!=" + str(settings.SITE_ID)) try: urlpath = URLPath.get_by_path(course_slug, select_related=True) results = list(Article.objects.filter(id=urlpath.article.id)) if results: article = results[0] else: article = None except (NoRootURL, URLPath.DoesNotExist): # We will create it in the next block urlpath = None article = None if not article: # create it root = get_or_create_root() if urlpath: # Somehow we got a urlpath without an article. Just delete it and # recerate it. urlpath.delete() urlpath = URLPath.create_article( root, course_slug, title=course_slug, content="This is the wiki for **{0}**'s _{1}_.".format( course.org, course.display_name_with_default), user_message="Course page automatically created.", user=None, ip_address=None, article_kwargs={ 'owner': None, 'group': None, 'group_read': True, 'group_write': True, 'other_read': True, 'other_write': True, }) return redirect("wiki:get", path=urlpath.path)
def test_move(self): # Create a hierarchy of pages self.client.post(resolve_url('wiki:create', path=''), { 'title': 'Test', 'slug': 'test0', 'content': 'Content .0.' }) self.client.post(resolve_url('wiki:create', path='test0/'), { 'title': 'Test00', 'slug': 'test00', 'content': 'Content .00.' }) self.client.post(resolve_url('wiki:create', path=''), { 'title': 'Test1', 'slug': 'test1', 'content': 'Content .1.' }) self.client.post(resolve_url('wiki:create', path='test1/'), { 'title': 'Tes10', 'slug': 'test10', 'content': 'Content .10.' }) self.client.post(resolve_url('wiki:create', path='test1/test10/'), { 'title': 'Test100', 'slug': 'test100', 'content': 'Content .100.' }) # Move /test1 => /test0 (an already existing destination slug!) response = self.client.post( resolve_url('wiki:move', path='test1/'), { 'destination': str(URLPath.root().article.current_revision.id), 'slug': 'test0', 'redirect': '' }) self.assertContains(response, 'A slug named') self.assertContains(response, 'already exists.') # Move /test1 >= /test2 (valid slug), no redirect test0_id = URLPath.objects.get( slug='test0').article.current_revision.id response = self.client.post(resolve_url('wiki:move', path='test1/'), { 'destination': str(test0_id), 'slug': 'test2', 'redirect': '' }) self.assertRedirects(response, resolve_url('wiki:get', path='test0/test2/')) # Check that there is no article displayed in this path anymore response = self.get_by_path('test1/') self.assertRedirects(response, '/_create/?slug=test1') # Create /test0/test2/test020 response = self.client.post( resolve_url('wiki:create', path='test0/test2/'), { 'title': 'Test020', 'slug': 'test020', 'content': 'Content .020.' }) # Move /test0/test2 => /test1new + create redirect response = self.client.post( resolve_url('wiki:move', path='test0/test2/'), { 'destination': str(URLPath.root().article.current_revision.id), 'slug': 'test1new', 'redirect': 'true' }) self.assertRedirects(response, resolve_url('wiki:get', path='test1new/')) # Check that /test1new is a valid path response = self.get_by_path('test1new/') self.assertContains(response, 'Content .1.') # Check that the child article test0/test2/test020 was also moved response = self.get_by_path('test1new/test020/') self.assertContains(response, 'Content .020.') response = self.get_by_path('test0/test2/') self.assertContains(response, 'Moved: Test1') self.assertRegex(response.rendered_content, r'moved to <a[^>]*>wiki:/test1new/') response = self.get_by_path('test0/test2/test020/') self.assertContains(response, 'Moved: Test020') self.assertRegex(response.rendered_content, r'moved to <a[^>]*>wiki:/test1new/test020') # Check that moved_to was correctly set urlsrc = URLPath.get_by_path('/test0/test2/') urldst = URLPath.get_by_path('/test1new/') self.assertEqual(urlsrc.moved_to, urldst) # Check that moved_to was correctly set on the child's previous path urlsrc = URLPath.get_by_path('/test0/test2/test020/') urldst = URLPath.get_by_path('/test1new/test020/') self.assertEqual(urlsrc.moved_to, urldst)
def test_history(self): url = reverse('wiki:globalhistory') url0 = reverse('wiki:globalhistory', kwargs={'only_last': '0'}) url1 = reverse('wiki:globalhistory', kwargs={'only_last': '1'}) response = self.client.get(url) expected = ( '(?s).*Root Article.*no log message.*' ) self.assertRegexpMatches(response.rendered_content, expected) URLPath.create_urlpath(URLPath.root(), "testhistory1", title="TestHistory1", content="a page", user_message="Comment 1") response = self.client.get(url) expected = ( '(?s).*TestHistory1.*Comment 1.*' 'Root Article.*no log message.*' ) self.assertRegexpMatches(response.rendered_content, expected) urlpath = URLPath.create_urlpath( URLPath.root(), "testhistory2", title="TestHistory2", content="a page", user_message="Comment 2" ) expected = ( '(?s).*TestHistory2.*Comment 2.*' 'TestHistory1.*Comment 1.*' 'Root Article.*no log message.*' ) response = self.client.get(url) self.assertRegexpMatches(response.rendered_content, expected) response = self.client.get(url0) self.assertRegexpMatches(response.rendered_content, expected) response = self.client.get(url1) self.assertRegexpMatches(response.rendered_content, expected) response = self.client.post( reverse('wiki:edit', kwargs={'path': 'testhistory2/'}), {'content': 'a page modified', 'current_revision': str(urlpath.article.current_revision.id), 'preview': '0', 'save': '1', 'summary': 'Testing Revision', 'title': 'TestHistory2Mod'} ) expected = ( '(?s).*TestHistory2Mod.*Testing Revision.*' 'TestHistory2.*Comment 2.*' 'TestHistory1.*Comment 1.*' 'Root Article.*no log message.*' ) response = self.client.get(url) self.assertRegexpMatches(response.rendered_content, expected) response = self.client.get(url0) self.assertRegexpMatches(response.rendered_content, expected) expected = ( '(?s).*TestHistory2Mod.*Testing Revision.*' 'TestHistory1.*Comment 1.*' 'Root Article.*no log message.*' ) response = self.client.get(url1) self.assertRegexpMatches(response.rendered_content, expected)
def create_urlpath(self, parent, slug): """Creates an article at /parent/slug and returns its URLPath""" return URLPath.create_article(parent, slug, title=slug)
def test_related_manager_works_with_filters(self): root = URLPath.root() self.assertNotIn(root.id, [p.id for p in root.children.active()])
def course_wiki_redirect(request, course_id, wiki_path=""): """ This redirects to whatever page on the wiki that the course designates as it's home page. A course's wiki must be an article on the root (for example, "/6.002x") to keep things simple. """ course = get_course_by_id(CourseKey.from_string(course_id)) course_slug = course_wiki_slug(course) valid_slug = True if not course_slug: log.exception("This course is improperly configured. The slug cannot be empty.") valid_slug = False if re.match(r'^[-\w\.]+$', course_slug) is None: log.exception("This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens.") # lint-amnesty, pylint: disable=line-too-long valid_slug = False if not valid_slug: return redirect("wiki:get", path="") try: urlpath = URLPath.get_by_path(wiki_path or course_slug, select_related=True) results = list(Article.objects.filter(id=urlpath.article.id)) if results: article = results[0] else: article = None except (NoRootURL, URLPath.DoesNotExist): # We will create it in the next block urlpath = None article = None if not article: # create it root = get_or_create_root() if urlpath: # Somehow we got a urlpath without an article. Just delete it and # recerate it. urlpath.delete() content = Text( # Translators: this string includes wiki markup. Leave the ** and the _ alone. _(u"This is the wiki for **{organization}**'s _{course_name}_.") ).format( organization=course.display_org_with_default, course_name=course.display_name_with_default, ) urlpath = URLPath.create_article( root, course_slug, title=course.display_name_with_default, content=content, user_message=_("Course page automatically created."), user=None, ip_address=None, article_kwargs={'owner': None, 'group': None, 'group_read': True, 'group_write': True, 'other_read': True, 'other_write': True, }) return redirect("wiki:get", path=urlpath.path)
def course_wiki_redirect(request, course_id): # pylint: disable=unused-argument """ This redirects to whatever page on the wiki that the course designates as it's home page. A course's wiki must be an article on the root (for example, "/6.002x") to keep things simple. """ course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id)) course_slug = course_wiki_slug(course) valid_slug = True if not course_slug: log.exception("This course is improperly configured. The slug cannot be empty.") valid_slug = False if re.match(r'^[-\w\.]+$', course_slug) is None: log.exception("This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens.") valid_slug = False if not valid_slug: return redirect("wiki:get", path="") # The wiki needs a Site object created. We make sure it exists here try: Site.objects.get_current() except Site.DoesNotExist: new_site = Site() new_site.domain = settings.SITE_NAME new_site.name = "edX" new_site.save() site_id = str(new_site.id) if site_id != str(settings.SITE_ID): msg = "No site object was created and the SITE_ID doesn't match the newly created one. {} != {}".format( site_id, settings.SITE_ID ) raise ImproperlyConfigured(msg) try: urlpath = URLPath.get_by_path(course_slug, select_related=True) results = list(Article.objects.filter(id=urlpath.article.id)) if results: article = results[0] else: article = None except (NoRootURL, URLPath.DoesNotExist): # We will create it in the next block urlpath = None article = None if not article: # create it root = get_or_create_root() if urlpath: # Somehow we got a urlpath without an article. Just delete it and # recerate it. urlpath.delete() content = cgi.escape( # Translators: this string includes wiki markup. Leave the ** and the _ alone. _("This is the wiki for **{organization}**'s _{course_name}_.").format( organization=course.display_org_with_default, course_name=course.display_name_with_default_escaped, ) ) urlpath = URLPath.create_article( root, course_slug, title=course_slug, content=content, user_message=_("Course page automatically created."), user=None, ip_address=None, article_kwargs={'owner': None, 'group': None, 'group_read': True, 'group_write': True, 'other_read': True, 'other_write': True, }) return redirect("wiki:get", path=urlpath.path)
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)