Example #1
0
def view_page(request, slug):
    try:
        page = Page.objects.order_by('-version').filter('slug =', slug)[0]
    except IndexError:
        page = Page(slug=slug) # Temporarily construct Page object so we can call edit_url()
        return HttpResponseRedirect(page.edit_url())
    return render_to_response('wiki/view_page.html', {'page': page})
Example #2
0
    def test_recent_pages(self):
        """Tests getting the recent pages."""
        recent_five = Page.recent_pages()
        recent_ten = Page.recent_pages(10)

        self.assertEqual(recent_five.count(), 5)
        self.assertEqual(recent_ten.count(), 7)
Example #3
0
File: views.py Project: Sir2B/Uni
def save_page(request, page_name):
    content = request.POST["content"]
    try:
        page = Page.objects.get(pk=page_name)
        page.content = content
    except Page.DoesNotExist:
	page = Page(name=page_name, content=content)
    page.save()
    return HttpResponseRedirect("/wikicamp/"+ page_name + "/")
Example #4
0
def save_page(request, page_name):
  content = request.POST['content']
  try:
    page = Page.objects.get(pk=page_name)
    page.content = content
  except Page.DoesNotExist:
    page = Page(name=page_name, content=content)
  page.save()
  page = RequestContext(request, {'page': page})
  return HttpResponseRedirect("/wiki/" + page_name + "/")
Example #5
0
def save_page(request, page_name):
  """A form from EDIT redirects to save_page with a content and a page_name"""
  content = request.POST['content']
  try:
    page = Page.objects.get(pk=page_name) # takes this from model
    page.content = content
  except Page.DoesNotExist:
    page = Page(name=page_name, content=content)
  page.save()
  return HttpResponseRedirect("/wikicamp/" + page_name + "/" )
Example #6
0
def save_page(request,page_name):
	content = request.POST.get("content","")
	cate = request.POST.get("cate","")
	try:
		page = Page.objects.get(pk=page_name.replace("?","__").replace("/","^^"))
		page.content = content
		page.cate = cate
	except Page.DoesNotExist:
		page = Page(name=page_name.replace("?","__").replace("/","^^"), content= content, cate = cate)
	page.save()
	return HttpResponseRedirect("/wiki/"+page_name+"/")
Example #7
0
def save_page(request, page_name):
    content = request.POST["content"]
    try:
        page = Page.objects.get(pk=page_name)
        page.contents = content
    except Page.DoesNotExist:
        page = Page(name=page_name, contents=content)

    page.save()

    return HttpResponseRedirect(reverse("view_page", args=(page_name,)))
Example #8
0
def save_page(request, page_name):
		content = request.POST['content']
		try:
			page = Page.objects.get(pk=page_name)
			page.content = content
		except:
			page = Page(
				name = page_name,
				content = content
			)
		page.save()
		return HttpResponseRedirect('/wiki/' + page_name + '/')
Example #9
0
def save_add(request):
	content = request.POST.get("content","")
	page_name = request.POST.get("page_name","")
	cate = request.POST.get("cate","")
	date = request.POST.get("date","")
	try:
		page = Page.objects.get(pk=page_name.replace("?","__").replace("/","^^"))
		return render_to_response("add.html",{"error":"Name already exist"})
	except Page.DoesNotExist:
		page = Page(name=page_name.replace("?","__").replace("/","^^"), content= content, cate = cate, date = date)
		page.save()
		return HttpResponseRedirect("/browse")
def save_page(request, page_name):
    # request the content from the form
    content = request.POST["content"]
    try:
        page = Page.objects.get(pk=page_name)
        # if the page exists we write the new content into the database
        page.content = content
    # if Page does not exist we save the page in the database
    except Page.DoesNotExist:
        page = Page(name=page_name, content=content)
    page.save()
    return HttpResponseRedirect("/wikicamp/" + page_name + "/")
Example #11
0
def save_edit(name):
    title = request.form.get("title", "")
    if not title:
        return redirect("/edit/" + name)
    markdown = request.form.get("markdown", "")
    page = Page.query.options(eagerload("versions")).filter_by(name=name).first()
    if not page:
        page = Page(name)
        session.add(page)
    version = Version(title, markdown)
    page.versions.append(version)
    page.tag_string = request.form.get("tags", "")
    #db.commit()
    return redirect(url_for("view", name=name))
Example #12
0
    def setUp(self):
        #Settings are kept in between tests, so we need to reset this:
        settings.IS_TESTING_WIKI = False
        #Make sure we create a user and sign up for a wiki first.
        User.objects.create_user('test', '*****@*****.**', 'test')
        self.assertTrue(self.client.login(username='******', password='******'))
        #Now create a wiki:
        r = self.client.post(
            '/signup/',
            {
                'subdomain': 'mywiki',
                #'submit': 'Claim',
                'title': 'My Excellent Wiki',
            })
        self.failUnlessEqual(r.status_code, 302)  #redirect

        #Now we force the middleware to pretend that we're in a subdomain.
        settings.IS_TESTING_WIKI = True

        #Create a HomePage so that settings can be set.
        w = Wiki.objects.get(tag='mywiki')
        p = Page()
        p.wiki = w
        p.tag = 'HomePage'
        p.content = 'Welcome to your new wiki!'
        p.ip_address = '127.0.0.1'
        p.save()
Example #13
0
def save_page(request, page_name):
    content = request.POST.get("content", "")
    cate = request.POST.get("cate", "")
    try:
        page = Page.objects.get(
            pk=page_name.replace("?", "__").replace("/", "^^"))
        page.content = content
        page.cate = cate
    except Page.DoesNotExist:
        page = Page(name=page_name.replace("?", "__").replace("/", "^^"),
                    content=content,
                    cate=cate)
    page.save()
    return HttpResponseRedirect("/wiki/" + page_name + "/")
Example #14
0
    def test_page_slugify_on_save(self):
        """ Tests the slug generated when saving a Page. """
        # Author is a required field in our model.
        # Create a user for this test and save it to the test database.
        user = User()
        user.save()

        # Create and save a new page to the test database.
        page = Page(title="My Test Page", content="test", author=user)
        page.save()

        # Make sure the slug that was generated in Page.save()
        # matches what we think it should be.
        self.assertEqual(page.slug, "my-test-page")
Example #15
0
def save_page(request, slug):
    if request.method == 'POST':
        content = request.POST.get('content', '')
        title = request.POST.get('title', slug.replace('-', '').title())
        if content == '':
            return redirect('/edit/{slug}.html'.format(slug=slug))
        try:
            page = Page.objects.get(slug=slug)
            setattr(page, 'content', content)
            page.save()
        except Page.DoesNotExist:
            page = Page(slug=slug, content=content, title=title)
            page.save()
        update_index.Command().handle(using=['default'], remove=True)
        return redirect('/view/{slug}.html'.format(slug=page.get_url()))
Example #16
0
def page_edit(request, slug):
    page = get_or_none(Page, slug=slug)
    if not page:
        title = slug.replace('-', ' ')
    else:
        title = page.name
    if request.method == "POST":
        new_content = request.POST.get('edit')
        if page:
            page.content = new_content
            page.save()
        else:
            page = Page(name=title, content=new_content, slug=slug)
            page.save()
    return direct_to_template(request, 'wiki/page_edit.html', locals())
Example #17
0
    def post(self, request, slug, *args, **kwargs):
        form = PageForm(request.POST)

        if form.is_valid:
            Page = self.get_queryset().get(slug__iexact=slug)
            Page.title = request.POST['title']
            Page.content = request.POST['content']
            Page.modified = datetime.now()
            Page.slug = slugify(Page.title, allow_unicode=True)
            # Page = form.save(commit=False)
            Page.author = request.user
            Page.save()
            return HttpResponseRedirect(
                reverse('wiki-details-page', args=[Page.slug]))
        return render(request, 'page.html', {'form': form})
Example #18
0
def edit(req, pagename):
    if req.user.get_profile().banned:
        return HttpResponseRedirect(
            "/wiki/%s?error=%s" %
            (pagename, "Sorry banned users can't edit the wiki"))

    try:
        page = Page.objects.get(title__iexact=pagename)
    except:
        page = None

    if page and page.op_only and not req.user.is_staff:
        return HttpResponseRedirect(
            "/wiki/%s?error=%s" %
            (pagename, "Sorry only operators edit this page."))

    if req.POST.has_key('body'):  # We should save something
        #if req.POST.has_key( 'base_rev' ):
        # ^ TODO: Add super merging fun time.
        # ^ TODO: Add op-only check.

        if not page:
            page = Page(title=pagename, op_only=False)
            page.save()

        rev = Revision(author=req.user,
                       pub_date=datetime.datetime.now(),
                       body=req.POST['body'],
                       page=page)
        rev.save()
        return HttpResponseRedirect("/wiki/%s" % pagename)

    if page:
        # try to fetch the last our last revision.
        revision = page.get_last_revision()
        wiki_title = page.title.replace('_', ' ')

    else:
        revision = None
        wiki_title = pagename.replace('_', ' ')

    c = RequestContext(req, {
        'wiki_title': wiki_title,
        'pagename': pagename,
        'revision': revision
    })

    return render_to_response("wiki/edit.html", c)
Example #19
0
def save_add(request):
    content = request.POST.get("content", "")
    page_name = request.POST.get("page_name", "")
    cate = request.POST.get("cate", "")
    date = request.POST.get("date", "")
    try:
        page = Page.objects.get(
            pk=page_name.replace("?", "__").replace("/", "^^"))
        return render_to_response("add.html", {"error": "Name already exist"})
    except Page.DoesNotExist:
        page = Page(name=page_name.replace("?", "__").replace("/", "^^"),
                    content=content,
                    cate=cate,
                    date=date)
        page.save()
        return HttpResponseRedirect("/browse")
Example #20
0
class PageModelTests(TestCase):
    fixtures = ['pages.json']

    def setUp(self):
        self.page = Page(title="Test", markdown="FDSFD")

    def test_render_markdown(self):
        """Tests the html method to ensure it renders HTML from markdown."""
        page = Page(title="Test", markdown="# Testing this\n**test**")

        self.assertEqual(page.html, "<h1>Testing this</h1>\n\n<p><strong>test</strong></p>\n")

    def test_was_modified_when_modified(self):
        """Tests to make sure modified articles are marked as modified"""
        self.page.date_created = datetime.now() - timedelta(hours=1)
        self.page.date_modified = datetime.now()

        self.assertTrue(self.page.was_modified)

    def test_was_modified_when_not_modified(self):
        """Tests to make sure non-modified articles are marked as unmodified"""
        self.page.date_created = datetime.now()
        self.page.date_modified = datetime.now()

        self.assertFalse(self.page.was_modified)

    def test_was_modified_boundaries_not_modified(self):
        """Tests to make sure unmodified articles are marked as unmodified at boundary"""
        now = datetime.now()
        self.page.date_created = now - timedelta(minutes=4, seconds=59)
        self.page.date_modified = now

        self.assertFalse(self.page.was_modified)

    def test_was_modified_boundaries_modified(self):
        """Tests to make sure modified articles are marked as modified at boundary"""
        now = datetime.now()
        self.page.date_created = now - timedelta(minutes=5)
        self.page.date_modified = now

        self.assertTrue(self.page.was_modified)

    def test_get_absolute_url(self):
        """Tests to see if the absolute url is correct"""
        self.assertEqual(self.page.get_absolute_url(), '/wiki/{0}'.format(self.page.title.lower()))

    def test_get_absolute_url_spaces(self):
        """Tests to see if the absolute url (with spaces) is correct"""
        page = Page(title="Test Title", markdown="# Testing this\n**test**")

        self.assertEqual(page.get_absolute_url(), '/wiki/{0}'.format(page.title.lower().replace(" ", "%20")))

    def test_recent_pages(self):
        """Tests getting the recent pages."""
        recent_five = Page.recent_pages()
        recent_ten = Page.recent_pages(10)

        self.assertEqual(recent_five.count(), 5)
        self.assertEqual(recent_ten.count(), 7)
Example #21
0
def add_details(request,page_name):
	msg={}
	if request.method == 'POST':
		content = request.POST.get("content","")
		cate = request.POST.get("cate","")
		date = request.POST.get("date","")
		try:
			page = Page.objects.get(pk=page_name)
			page.content = content
			page.cate = cate
			page.date = date
			msg["status"]="200 OK"
		except Page.DoesNotExist:
			page = Page(name=page_name, content= content , cate = cate ,date = date)
			msg["status"]="201 Empty"
		page.save()
	else:
		msg["status"] = "202 Invalid"
	return JsonResponse(msg)
Example #22
0
def add_details(request, page_name):
    msg = {}
    if request.method == 'POST':
        content = request.POST.get("content", "")
        cate = request.POST.get("cate", "")
        date = request.POST.get("date", "")
        try:
            page = Page.objects.get(pk=page_name)
            page.content = content
            page.cate = cate
            page.date = date
            msg["status"] = "200 OK"
        except Page.DoesNotExist:
            page = Page(name=page_name, content=content, cate=cate, date=date)
            msg["status"] = "201 Empty"
        page.save()
    else:
        msg["status"] = "202 Invalid"
    return JsonResponse(msg)
Example #23
0
 def __init__(self, user, page_tag):
     self.user = user
     self.page_tag = page_tag
     #Get page object
     try:
         self.page = Page.objects.filter(wiki = settings.WIKI, tag = page_tag).order_by('-id')[0]
     except IndexError:
         #If page doesn't exist, we pass a dummy Page object in so that we
         #use global perm. We need to set the Wiki object.
         self.page = Page(wiki = settings.WIKI)
Example #24
0
def edit_master_tag_discussion(request,bus_id,page_id):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/accounts/login/?next=%s'%request.path)
        
    b = get_object_or_404(Business, pk=bus_id)
    page = get_object_or_404(Page, pk=page_id)

    try:
        b.photourl = get_photo_web_url(b)
    except:
        b.photourl= "" #NONE


    if request.method == 'POST':
        form = PageForm(request.POST)
        if form.is_valid():
            if not page:
                page = Page()
            page.content = form.cleaned_data['content']

            page.save()
            return redirect(bus_details, bus_id=bus_id)
    else:
        if page:
            wiki_edit_form = PageForm(initial=page.__dict__)
        else:
            wiki_edit_form = PageForm(initial={'name': page.name})

    
    try:
        pgr = PageRelationship.objects.get(page=page)
    except:
        pgr = PageRelationship.objects.filter(page=page)[0]
    t = pgr.businesstag
    context = get_default_bus_context(b, request.user)
    context['form']=wiki_edit_form
    context['page']=page
    context['tag'] =t 
    

    
    return render_to_response('ratings/busdetail.html', context_instance=RequestContext(request,context))
Example #25
0
def edit( req, pagename ):
    if req.user.get_profile().banned:
        return HttpResponseRedirect( "/wiki/%s?error=%s" %(
                pagename, "Sorry banned users can't edit the wiki" ) )

    try:
        page = Page.objects.get( title__iexact=pagename )
    except:
        page = None

    if page and page.op_only and not req.user.is_staff:
        return HttpResponseRedirect( "/wiki/%s?error=%s" %(
                pagename, "Sorry only operators edit this page." ) )

    if req.POST.has_key( 'body' ): # We should save something
        #if req.POST.has_key( 'base_rev' ):
        # ^ TODO: Add super merging fun time.
        # ^ TODO: Add op-only check.
        
        if not page:
            page = Page( title=pagename, op_only=False )
            page.save()
        
        rev = Revision( author=req.user, pub_date=datetime.datetime.now(),
                        body = req.POST['body'], page=page )
        rev.save()
        return HttpResponseRedirect( "/wiki/%s" % pagename )
    
    if page:
        # try to fetch the last our last revision.
        revision = page.get_last_revision()
        wiki_title = page.title.replace( '_', ' ' )
        
    else:
        revision = None
        wiki_title = pagename.replace( '_', ' ' )

    c = RequestContext( req, { 'wiki_title': wiki_title,
                               'pagename': pagename,
                               'revision': revision } )
    
    return render_to_response( "wiki/edit.html", c )
Example #26
0
	def test_get_absolute_url_for_page(self):
		page = Page()
		page.title = "Page title";
		page.content = "Page content";
		page.owner_id = 1

		page.save()

		self.assertEquals(page.get_absolute_url(), "/wiki/" + str(page.id))
Example #27
0
def addPage(request):
    """
    A view to create a new wiki page, or save an addition in progress
    """
    name = request.matchdict['pagename']
    if 'form.submitted' in request.params:
        session = DBSession()
        body = request.params['body']
        page = Page(name, body)
        session.add(page)
        result = HTTPFound(
            location=route_url('viewPage', request, pagename=name))
    else:
        result = {
            'page': Page('', ''),
            'save_url': route_url('addPage', request, pagename=name),
            'logged_in': authenticated_userid(request)
        }

    return result
Example #28
0
def test_detail_page(self):
    """ Test to see if slug generated when saving a Page."""

    # Create a user and save to the database
    user = User.objects.create()
    user.save()

    # Create a page and save to the database
    page = Page(title="My Detail Test Page",
                content="details_test",
                author=user)
    page.save()

    # Slug is generated matches with what we expect
    slug = page.slug
    response = self.client.get(f'/{slug}/')

    self.assertEqual(response.status_code, 200)

    info = self.client.get('/')
    self.assertContains(info, 'makewiki', html=True)
Example #29
0
    def test_detail_page(self):
        """ Tests the slug generated when saving a Page. """
        # Author is a required field in our model.
        # Create a user for this test and save it to the test database.
        user = User.objects.create()
        user.save()

        # Create and save a new page to the test database.
        page = Page(title="My Detail Test Page",
                    content="details_test",
                    author=user)
        page.save()

        # Make sure the slug that was generated in Page.save()
        # matches what we think it should be.
        slug = page.slug
        response = self.client.get(f'/{slug}/')

        self.assertEqual(response.status_code, 200)

        info = self.client.get('/')
        self.assertContains(info, 'makewiki', html=True)
Example #30
0
def get_page_or_temp(title):
    """
    Attempts to retrieve a page from the provided id, otherwise returns
    a new page with using the provided id as its title.

    :param title: id of the page.
    :return: page matching provided id or temporary blank page.
    """
    page = get_page(title)

    if page is None:
        page = Page(page_title=title)

    return page
Example #31
0
    def test_wiki_details_page_loads_for_a_specific_page(self):
        # # Make some test data to be displayed on the page.
        # user = User.objects.create()

        # Page.objects.create(title="My Test Page", content="test", author=user)

        # # Issue a GET request to the detail page
        # # When we make a request, we get a response back.
        # response = self.client.get('/my-test-page', follow= True)

        # # Check that the response is 200 OK.
        # self.assertEqual(response.status_code, 200)

        # # Check that the number of pages passed to the template
        # # matches the number of pages we have in the database.
        # response = response.context['page']

        # self.assertQuerysetEqual(
        #     response,
        #     ['<Page: My Test Page>'],
        #     ordered=False
        # )

        # ==========My Own Version================
        # Author is a required field in our model.
        # Create a user for this test and save it to the test database.
        user = User()
        user.save()

        # Create and save a new page to the test database.
        page = Page(title="My Test Page", content="test", author=user)
        page.save()

        # Make a response call
        response = self.client.get("/my-test-page", follow=True)
        # Assert response code is a 200
        self.assertEqual(response.status_code, 200)
Example #32
0
 def post(self, request, slug):
     form = PageForm(request.POST)
     if form.is_valid():
         obj = Page()
         obj.title = form.cleaned_data['title']
         obj.author = form.cleaned_data['author']
         obj.slug = form.cleaned_data['slug']
         obj.email = form.cleaned_data['email']
         obj.content = form.cleaned_data['content']
         obj.save()
         messages.add_message(request, messages.INFO,
                              obj.title + ' has been successfully updated')
         return HttpResponseRedirect(reverse('wiki-list-page'))
     else:
         form = PageForm()
         page = Page.objects.get(slug=slug)
         return render(request, 'wiki/page.html', {
             'page': page,
             'form': form
         })
Example #33
0
def EditPage(request, title):
    try:
        page = Page.objects.get(title=title)
    except Page.DoesNotExist:
        page = Page(title=title, content="")

    if request.method == 'GET':
        form = PageForm(instance=page)
        return render(request, 'wiki/edit.html', {'page': page, 'form': form})

    if request.method == 'POST':
        form = PageForm(request.POST, instance=page)
        form.save()
        #page.content = request.POST['content']
        #page.save()
        return HttpResponseRedirect(reverse('wiki:wikipage', args=(title, )))
Example #34
0
	def test_cant_access_someone_elses_page(self):
		new_user = User.objects.create(username = '******')
		new_user.set_password('parola')
		new_user.save()
		page = Page()
		page.title = "Page title";
		page.content = "Page content";
		page.owner = new_user

		page.save()

		res = self.client.get('/wiki/' + str(page.id))
		self.assertEquals(404, res.status_code)
Example #35
0
	def test_cant_delete_someone_elses_page(self):
		new_user = User.objects.create(username = '******')
		new_user.set_password('parola')
		new_user.save()
		page = Page()
		page.title = "Page title";
		page.content = "Page content";
		page.owner = new_user

		page.save()

		count_before = Page.objects.all().count()
		self.client.get('/wiki/delete/' + str(page.id))
		count_after = Page.objects.all().count()

		self.assertEqual(count_before, count_after)
Example #36
0
	def test_delete_page(self):
		page = Page()
		page.title = "Page title";
		page.content = "Page content";
		page.owner = self.user

		page.save()

		res = self.client.get('/wiki/all')
		self.assertTrue("Page title" in res.content)

		res = self.client.get('/wiki/delete/' + str(page.id))
		self.assertEquals(200, res.status_code)

		res = self.client.get('/wiki/all')
		self.assertFalse("Page title" in res.content)
Example #37
0
	def test_update_page_via_request(self):
		page = Page()
		page.title = "Page title";
		page.content = "Page content";
		page.owner = self.user

		page.save()

		title = "New title"
		content = "New content"
		res = self.client.post('/wiki/update/' + str(page.id), {'title': title, 'content': content})

		self.assertEquals(302, res.status_code)

		res = self.client.get('/wiki/' + str(page.id))
		self.assertTrue(title in res.content)
		self.assertTrue(content in res.content)
Example #38
0
	def test_creating_a_new_model_page_and_saving_it_to_the_database(self):
		page = Page()
		page.title = "Page title";
		page.content = "Page content";
		page.owner = self.user

		page.save()

		all_pages = Page.objects.all()
		self.assertEquals(len(all_pages), 1)

		only_page_in_database = all_pages[0]
		self.assertEquals(only_page_in_database, page)

		self.assertEquals(only_page_in_database.title, "Page title")
		self.assertEquals(only_page_in_database.content, "Page content")
		self.assertEquals(only_page_in_database.owner_id, self.user.id)
Example #39
0
    def test_get_absolute_url_spaces(self):
        """Tests to see if the absolute url (with spaces) is correct"""
        page = Page(title="Test Title", markdown="# Testing this\n**test**")

        self.assertEqual(page.get_absolute_url(), '/wiki/{0}'.format(page.title.lower().replace(" ", "%20")))
Example #40
0
def edit(request, page_tag, rev = None):
    if request.method == 'POST':
        form = EditForm(request.POST)
        #Also check to see if we are 're-editing' the page:
        if form.is_valid() and request.POST.get('action') != 'Edit':
            data = form.cleaned_data
            #print data

            #Check for preview or save. In both cases, we'll create a new page
            #(since we always want to save a new record.
            p = Page()
            p.wiki = settings.WIKI 
            p.tag = page_tag
            p.content = data['content']
            p.note = data['note']
            #If user is anonymous, then leave the p.author field blank.
            if request.user.is_authenticated() and request.user.is_active:
                p.author = request.user
            p.ip_address = request.META['REMOTE_ADDR']
            if request.POST.get('action') == 'Save' or request.POST.get('action') == 'Force Save':
                #TODO: Check if there has been a change in content. If no change, then
                #don't save.

                #We also save the previous (most current) page permission.
                try:
                    latest = Page.objects.filter(wiki = settings.WIKI, tag = page_tag).order_by('-id')[0]
                    p.can_view = latest.can_view
                    p.can_edit = latest.can_edit
                    p.can_special = latest.can_special

                    #We also check for edit conflict. That is, if the previous edit
                    #creation datetime is >= the current edit datetime. We only check
                    #for conflict when the action is "Save" and NOT "Force Save".
                    if latest.created >= data['time'] and latest.content != p.content:
                        #We also need to check if the 'latest' timestamp sent by
                        #the form is >= the current 'latest' timestamp at the time
                        #of this submission. If so, that means someone edited the
                        #article while we were resolving conflicts. In that case,
                        #show the conflicts again.
                        if request.POST.get('action') == 'Save' or data['latest_time'] < latest.created:
                            #Display conflict diff
                            diffs = unified_diff(latest.content, p.content)

                            return render_to_response('wiki/conflict.html', {
                                                        'page_tag': page_tag,
                                                        'page': p, #Can be None
                                                        'form': form,
                                                        'rev': rev, #Used to check if using rev
                                                        'latest': latest,
                                                        'diffs': diffs,
                                                      }, 
                                                      context_instance = RequestContext(request))

                except IndexError:
                    #Means that this page doesn't exist yet. That's fine. Global
                    #perm will be used for the page.
                    pass

                p.save()

                #Return to show page
                return HttpResponseRedirect(reverse('show', args=[page_tag]))
            else: #Anything else will be considered 'Preview'
                content_html = text2html(p.content, environ = {
                                            'settings': settings,
                                            'wiki.page': p,
                                            'wiki.macros': wiki.utils.wikiparser_macros.macros,
                                            'wiki.parser': text2html,
                                        })

                #Check if a page title has been set (with a macro). If not, then we check to see
                #if there is a first header that we can use as the title.
                if not hasattr(p, 'title'):
                    #If there is no first header, then we set the page_title to be the page_tag:
                    if not settings.SEARCH_HEADER.match(p.content):
                        p.title = p.tag

                #Change the content field to hidden
                form.fields['content'].widget = widgets.HiddenInput()
                return render_to_response('wiki/preview.html', {
                                            'page_tag': page_tag,
                                            'page': p, #Can be None
                                            'content_html': content_html,
                                            'form': form,
                                            #'from' allows us to determine if we will
                                            #do specific stuff for conflict case.
                                            'from': request.GET.get('from'),
                                          }, 
                                          context_instance = RequestContext(request))
        else:
            #We are re-editing the page from preview or form was invalid.
            #Either way, we only have data from the form submission and so we
            #display that.
            p = None
    else: 
        #Otherwise, form was not submitted. We prepopulate the form:
        try:
            #If we have a rev specified, then get only that revision
            if rev != None:
                rev = short_to_int(rev)
                p = Page.objects.get(wiki = settings.WIKI, tag = page_tag, id = rev)
            else:
                #Select the most recent version
                p = Page.objects.filter(wiki = settings.WIKI, tag = page_tag).order_by('-id')[0]
            #Since our EditForm is a ModelForm, we can set it up with
            #instance.
            form = EditForm(initial = {
                'content': p.content, 
                'note': '',
                #Get rid of microseconds for time since forms.DateTimeField doesn't
                #parse microseconds. Well, it does in python 2.6 using: 
                #%Y-%m-%d %H:%M:%S.%f as input_formats.
                'time': str(datetime.datetime.now()).split('.')[0],
            })
        except Page.DoesNotExist:
            #This means that the rev specified does not exist. So we'll just
            #redirect to the most recent version.
            #TODO: Show error message with redirect.
            return HttpResponseRedirect(reverse('edit', args=[page_tag]))
        except IndexError:
            #Check to see if this is one of our global pages
            try:
                p = Page.objects.filter(wiki = settings.GLOBAL_WIKI_ID, 
                                        tag = page_tag) \
                                .order_by('-id')[0]
                form = EditForm(initial = {
                    'content': p.content, 
                    'note': '',
                    'time': str(datetime.datetime.now()).split('.')[0],
                })
            except IndexError:
                #Okay, we don't have a global page. Display a blank form.
                form = EditForm(initial = {
                    'time': str(datetime.datetime.now()).split('.')[0],
                })
                p = None

    #Set up and prepopulate the form for page permissions (if page exists).
    if p == None: #Either this is a new page, or we got here from preview.
        #See if we can grab existing page.
        try:
            p = Page.objects.filter(wiki = settings.WIKI, tag = page_tag).order_by('-id')[0]
        except IndexError:
            #Do nothing, this is a new page.
            pass

    page_permissions_form = None
    if request.user.has_perm('page.can_special', p):
        try:
            page_permissions_form = PagePermissionsForm(initial = {
                                        'view': p.can_view,
                                        'edit': p.can_edit,
                                        })
        except AttributeError:
            #Means that this page totally doesn't exist at all so we can't access
            #p.can_view and p.can_edit.
            pass

    return render_to_response('wiki/edit.html', {
                                'page_tag': page_tag,
                                'page': p, #Can be None
                                'form': form,
                                'page_permissions_form': page_permissions_form,
                                'rev': rev, #Used to check if using rev
                              }, 
                              context_instance = RequestContext(request))
Example #41
0
 def _get_page(self, page_name):
     return Page.get_pages(self.db, key = page_name).rows
Example #42
0
	def import_wiki(self):
		models.signals.pre_save.disconnect(dispatch_uid='setup_index_signals')
		models.signals.post_save.disconnect(dispatch_uid='setup_index_signals')
		users = set(User.objects.values_list('id', flat = True))
		all_slugs = set()
		categories = {}
		for instance in Deserializer(open('wiki/pages.json')):
			instance.object.created = timezone.now()
			instance.object.save()
			categories[instance.object.title.replace('&amp;', '&')] = instance.object.id
			all_slugs.add(instance.object.slug)

		cols = [
			'id',
			'nadpis',
			'text',
			'time',
			'userid',
			'kategoria',
			'nazov_kategorie',
		]
		select_query = 'SELECT ' + (', '.join(['KnowledgeBase.' + col for col in cols])) + ' FROM KnowledgeBase ORDER BY KnowledgeBase.id DESC'
		self.cursor.execute(select_query)
		wiki_pages = [self.decode_cols_to_dict(cols, r) for r in list(self.cursor)]
		wiki_pages = dict([(p['id'], [p]) for p in wiki_pages])

		select_query = 'SELECT ' + (', '.join(['KnowledgeBase_History.' + col for col in cols])) + ' FROM KnowledgeBase_History ORDER BY KnowledgeBase_History.id'
		self.cursor.execute(select_query)
		wiki_history = [self.decode_cols_to_dict(cols, r) for r in list(self.cursor)]
		for item in wiki_history:
			if item['id'] in wiki_pages:
				wiki_pages[item['id']].insert(0, item)

		count = 0
		for id, page_list in wiki_pages.iteritems():
			count += len(page_list)

		reversion.register(WikiPage)

		self.logger.set_sub_progress(u"Databáza znalostí", count)
		for id, page_list in wiki_pages.iteritems():
			page_object = None
			for page in page_list:
				page['nadpis'] = page['nadpis'].replace('&amp;', '&')
				page['nazov_kategorie'] = page['nazov_kategorie'].replace('&amp;', '&')
				if not page_object:
					page_object = WikiPage()

				user = None
				if page['userid'] in users:
					page_object.last_author_id = page['userid']
					user = User.objects.get(pk = page['userid'])
				page_object.id = page['id'] + 7
				page_object.title = page['nadpis']
				page_object.original_text = ('html', page['text'])
				page_object.filtered_text = page['text']
				page_object.updated = page['time']
				page_object.parent = WikiPage.objects.get(pk = categories[page['nazov_kategorie']])
				page_object.page_type = 'p'
				if not page_object.created:
					page_object.created = page['time']
				if not page_object.slug:
					slug = AutoSlugField.create_unique_slug(slugify(page['nadpis'])[:45], all_slugs, 9999)
					all_slugs.add(slug)
					page_object.slug = slug
				page_object.save(ignore_auto_date = True)
				revision = reversion.revision.save_revision([page_object], user = user)
				revision.date_created = page['time']
				revision.save()

				self.logger.step_sub_progress()
		self.logger.finish_sub_progress()

		connections['default'].cursor().execute('SELECT setval(\'wiki_page_id_seq\', (SELECT MAX(id) FROM wiki_page) + 1);')
Example #43
0
 def setUp(self):
     self.page = Page(title="Test", markdown="FDSFD")
Example #44
0
 def clean_title(self):
     input_title  = self.cleaned_data['title']
     title_exists = Page.get_pages(self.db, key=input_title).rows
     if title_exists and not self.cleaned_data['_id'] == title_exists[0].value['_id']:
         raise forms.ValidationError("Title %s already exists" %title_exists[0].value['title'])
     return input_title
Example #45
0
def revert(request, page_tag, rev):
    #Get revision information
    rev_int = short_to_int(rev)
    r = Page.objects.get(wiki = settings.WIKI, tag = page_tag, id = rev_int)

    #We also get the last current page information (for saving permissions).
    #We know for SURE that at least one page exists for revert to happen so this
    #query must return at least one page.
    latest = Page.objects.filter(wiki = settings.WIKI, tag = page_tag).order_by('-id')[0]

    #Now resave as current page.
    p = Page()
    p.wiki = r.wiki
    p.tag = r.tag
    p.content = r.content
    p.note = 'Reverted to revision '+str(rev)+'.'
    p.author = r.author
    p.ip_address = r.ip_address
    
    #We keep same permissions as the previous page.
    p.can_view = latest.can_view
    p.can_edit = latest.can_edit
    p.can_special = latest.can_special

    p.save()

    messages.success(request, 'You have successfully reverted to revision '+str(rev)+'.')
    return HttpResponseRedirect(reverse('show', args=[page_tag]))