def form_valid(self, form): clean_data = form.cleaned_data print(clean_data) slug = clean_data['slug'] title = clean_data['name'] content = clean_data['description'] # creates an article for the category and then associates them by having equaling titles and slugs self.landing_article_urlpath = URLPath.create_article( URLPath.root(), slug, title=title, content=content, user_message=" ", user=self.request.user, article_kwargs={ 'owner': self.request.user, 'group': self.article.group, 'group_read': self.article.group_read, 'group_write': self.article.group_write, 'other_read': self.article.other_read, 'other_write': self.article.other_write, }) landing_article = Article.objects.get( urlpath=self.landing_article_urlpath) form.instance.article = landing_article form.save() category = Category.objects.get(slug=slug) return redirect("wiki:get", path=self.landing_article_urlpath.path, article_id=self.article.id)
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 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(ArticleTestBase, self).setUp() self.root = URLPath.create_root() self.child1 = URLPath.create_article(self.root, 'test-slug', title="Test 1")
def get_article(self, cont, image): urlpath = URLPath.create_article(URLPath.root(), "html_image", title="TestImage", content=cont) if image: self._create_test_image(urlpath.path) return urlpath.article.render()
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 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 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_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 setUp(self): """Test setup.""" super(TestWikiAccessMiddleware, self).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 create(path, title, content, user=None, message=""): """ Create a new wiki page. Args: path (str): the page's new path (must be unusued). title (str): the title of the new page. content (str): the new page's content. user (Account, optional): the new page's owner. message (str, optional): the new revision's message. Returns: article (Artidcle): the new article. Notes: If `user` is unset, use Account #1 (the superuser). If `slug` is unset, use the path. The provided path is an URL. The parent is taken to be the one before the last '/' sign. For example: 'a/b/c/' as a path would mean 'a/b' is taken to mean the parent, and 'c' is taken to be the article's new slug. """ print "Try to create a wiki page..." path = path.strip("/") if "/" in path: parent_path, slug = path.rsplit("/", 1) else: parent_path = "" slug = path parent = URLPath.get_by_path(parent_path) user = user or AccountDB.objects.get(id=1) newpath = URLPath.create_article( parent, slug, title=title, content=content, user_message=message, user=user, ip_address="127.0.0.1", article_kwargs={'owner': user, 'group': None, 'group_read': True, 'group_write': True, 'other_read': False, 'other_write': False, }) return newpath.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 newArticle(self, ex_article=None, name=None, slug=None, parent=None): article_urlpath = URLPath.create_article( parent=parent or URLPath.root(), slug=slug, title=name, content=name, user_message=" ", user=self.user, article_kwargs={'owner': self.user, 'group': ex_article.group, 'group_read': ex_article.group_read, 'group_write': ex_article.group_write, 'other_read': ex_article.other_read, 'other_write': ex_article.other_write, }) newarticle = models.Article.objects.get(urlpath=article_urlpath) return newarticle
def newArticle(self, name=None, slug=None, parent=None): self.article_urlpath = URLPath.create_article( parent=parent or URLPath.root(), slug=slug or self.data['slug'], title=name or self.data['name'], content=name or self.data['name'], user_message=" ", user=self.request.user, article_kwargs={'owner': self.request.user, 'group': self.article.group, 'group_read': self.article.group_read, 'group_write': self.article.group_write, 'other_read': self.article.other_read, 'other_write': self.article.other_write, }) newarticle = models.Article.objects.get(urlpath = self.article_urlpath) return newarticle
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_article(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 setUp(self): """Test setup.""" super(TestComprehensiveTheming, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments 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 create_urlpath(self, parent, slug): """Creates an article at /parent/slug and returns its URLPath""" return URLPath.create_article(parent, slug, title=slug)
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 course_wiki_redirect(request, course_id): # pylint: disable=W0613 """ 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) # pylint: disable=E1101 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, )) 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 setUp(self): super(ArticleTestBase, self).setUp() self.root = URLPath.create_root() self.child1 = URLPath.create_article(self.root, 'test-slug', title="Test 1")
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 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 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 course_wiki_redirect(request, course_id, wiki_path=""): # 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(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.") 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, wiki_path=""): # 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(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." ) 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 = 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.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): #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 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 create_urlpath(self, parent, slug): """Creates an article at /parent/slug and returns its URLPath""" return URLPath.create_article(parent, slug, title=slug)
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 create_urlpath(self, parent, slug): """Creates an article at /parent/slug and returns its URLPath""" from wiki.models import URLPath return URLPath.create_article(parent=parent, slug=slug, title=slug, article_kwargs={'owner': self.user})
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 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 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)