当前位置: 首页>>代码示例>>Python>>正文


Python urlresolvers.reverse函数代码示例

本文整理汇总了Python中sumo.urlresolvers.reverse函数的典型用法代码示例。如果您正苦于以下问题:Python reverse函数的具体用法?Python reverse怎么用?Python reverse使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了reverse函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_profile_edit

    def test_profile_edit(self, unsubscribe, subscribe, lookup_user):
        lookup_user.return_value = mock_lookup_user()
        subscribe.return_value = True
        unsubscribe.return_value = True
        profile = UserProfile.objects.get(user__username='testuser')
        user = profile.user
        url = reverse('users.profile', args=(user.username,))
        r = self.client.get(url, follow=True)
        doc = pq(r.content)
        eq_(0, doc.find('#profile-head .edit .button').length)

        self.client.login(username=user.username,
                          password=TESTUSER_PASSWORD)

        url = reverse('users.profile', args=(user.username,))
        r = self.client.get(url, follow=True)
        doc = pq(r.content)

        edit_button = doc.find('#profile-head .edit #edit-profile')
        eq_(1, edit_button.length)

        url = edit_button.attr('href')
        r = self.client.get(url, follow=True)
        doc = pq(r.content)

        eq_(profile.fullname,
            doc.find('#profile-edit input[name="profile-fullname"]').val())
        eq_(profile.title,
            doc.find('#profile-edit input[name="profile-title"]').val())
        eq_(profile.organization,
            doc.find('#profile-edit input[name="profile-organization"]').val())
        eq_(profile.location,
            doc.find('#profile-edit input[name="profile-location"]').val())
        eq_(profile.irc_nickname,
            doc.find('#profile-edit input[name="profile-irc_nickname"]').val())

        new_attrs = {
            'profile-email': '[email protected]',
            'profile-fullname': "Another Name",
            'profile-title': "Another title",
            'profile-organization': "Another org",
            'profile-country': "us",
            'profile-format': "html"
        }

        r = self.client.post(url, new_attrs, follow=True)
        doc = pq(r.content)

        eq_(1, doc.find('#profile-head').length)
        eq_(new_attrs['profile-fullname'],
            doc.find('#profile-head .main .fn').text())
        eq_(new_attrs['profile-title'],
            doc.find('#profile-head .info .title').text())
        eq_(new_attrs['profile-organization'],
            doc.find('#profile-head .info .org').text())

        profile = UserProfile.objects.get(user__username=user.username)
        eq_(new_attrs['profile-fullname'], profile.fullname)
        eq_(new_attrs['profile-title'], profile.title)
        eq_(new_attrs['profile-organization'], profile.organization)
开发者ID:skins1,项目名称:kuma,代码行数:60,代码来源:test_views.py

示例2: test_user_confirm_email_duplicate

    def test_user_confirm_email_duplicate(self, get_current):
        """If we detect a duplicate email when confirming an email change,
        don't change it and notify the user."""
        get_current.return_value.domain = 'su.mo.com'
        self.client.login(username='rrosario', password='testpass')
        old_email = User.objects.get(username='rrosario').email
        new_email = '[email protected]'
        response = self.client.post(reverse('users.change_email'),
                                    {'email': new_email})
        eq_(200, response.status_code)
        assert mail.outbox[0].subject.find('Please confirm your') == 0
        ec = EmailChange.objects.all()[0]

        # Before new email is confirmed, give the same email to a user
        User.objects.filter(username='pcraciunoiu').update(email=new_email)

        # Visit confirmation link and verify email wasn't changed.
        response = self.client.get(reverse('users.confirm_email',
                                           args=[ec.activation_key]))
        eq_(200, response.status_code)
        doc = pq(response.content)
        eq_('Unable to change email for user rrosario',
            doc('#main h1').text())
        u = User.objects.get(username='rrosario')
        eq_(old_email, u.email)
开发者ID:AutomatedTester,项目名称:kitsune,代码行数:25,代码来源:test_views.py

示例3: add_tag

def add_tag(request, question_id):
    """Add a (case-insensitive) tag to question.

    If the question already has the tag, do nothing.

    """
    # If somebody hits Return in the address bar after provoking an error from
    # the add form, nicely send them back to the question:
    if request.method == 'GET':
        return HttpResponseRedirect(
            reverse('questions.answers', args=[question_id]))

    try:
        question, canonical_name = _add_tag(request, question_id)
    except Tag.DoesNotExist:
        template_data = _answers_data(request, question_id)
        template_data['tag_adding_error'] = UNAPPROVED_TAG
        template_data['tag_adding_value'] = request.POST.get('tag-name', '')
        return jingo.render(request, 'questions/answers.html', template_data)

    if canonical_name:  # success
        question.clear_cached_tags()
        return HttpResponseRedirect(
            reverse('questions.answers', args=[question_id]))

    # No tag provided
    template_data = _answers_data(request, question_id)
    template_data['tag_adding_error'] = NO_TAG
    return jingo.render(request, 'questions/answers.html', template_data)
开发者ID:victorneo,项目名称:kitsune,代码行数:29,代码来源:views.py

示例4: test_user_change_email_updates_mindtouch

    def test_user_change_email_updates_mindtouch(self, get_current):
        """Send email to change user's email and then change it."""
        get_current.return_value.domain = 'su.mo.com'

        self.client.login(username='testuser01', password='testpass')
        # Attempt to change email.
        response = self.client.post(reverse('users.change_email'),
                                    {'email': '[email protected]'},
                                    follow=True)
        eq_(200, response.status_code)

        # Be notified to click a confirmation link.
        eq_(1, len(mail.outbox))
        assert mail.outbox[0].subject.find('Please confirm your') == 0
        ec = EmailChange.objects.all()[0]
        assert ec.activation_key in mail.outbox[0].body
        eq_('[email protected]', ec.email)

        # Visit confirmation link to change email.
        response = self.client.get(reverse('users.confirm_email',
                                           args=[ec.activation_key]))
        eq_(200, response.status_code)
        u = User.objects.get(username='testuser01')
        eq_('[email protected]', u.email)

        if not settings.DEKIWIKI_MOCK:
            deki_id = u.get_profile().deki_user_id
            doc = get_deki_user_doc(u)
            eq_(str(deki_id), doc('user').attr('id'))
            eq_('[email protected]',
                doc('user').find('email').text())
开发者ID:HarshaJagadish,项目名称:kuma,代码行数:31,代码来源:test_views.py

示例5: context_dict

def context_dict(revision):
    """Return a dict that fills in the blanks in notification templates."""
    document = revision.document
    from_revision = revision.get_previous()
    to_revision = revision
    diff = revisions_unified_diff(from_revision, to_revision)

    compare_url = ""
    if from_revision:
        compare_url = reverse(
            "wiki.compare_revisions", args=[document.full_path], locale=document.locale
        ) + "?from=%s&to=%s" % (from_revision.id, to_revision.id)

    link_urls = {
        "compare_url": compare_url,
        "view_url": reverse("wiki.document", locale=document.locale, args=[document.slug]),
        "edit_url": reverse("wiki.edit_document", locale=document.locale, args=[document.slug]),
        "history_url": reverse("wiki.document_revisions", locale=document.locale, args=[document.slug]),
    }

    for name, url in link_urls.iteritems():
        url = add_utm(url, "Wiki Doc Edits")
        link_urls[name] = url

    context = {
        "document_title": document.title,
        "creator": revision.creator,
        "host": Site.objects.get_current().domain,
        "diff": diff,
    }
    context.update(link_urls)

    return context
开发者ID:pombredanne,项目名称:kuma,代码行数:33,代码来源:events.py

示例6: test_xss_file_attachment_title

    def test_xss_file_attachment_title(self):
        title = '"><img src=x onerror=prompt(navigator.userAgent);>'
        # use view to create new attachment
        file_for_upload = make_test_file()
        post_data = {
            'title': title,
            'description': 'xss',
            'comment': 'xss',
            'file': file_for_upload,
        }
        self.client.login(username='admin', password='testpass')
        resp = self.client.post(reverse('attachments.new_attachment'),
                                data=post_data)
        eq_(302, resp.status_code)

        # now stick it in/on a document
        attachment = Attachment.objects.get(title=title)
        rev = revision(content='<img src="%s" />' % attachment.get_file_url(),
                      save=True)

        # view it and verify markup is escaped
        response = self.client.get(reverse('wiki.edit_document', args=(rev.slug,),
                                    locale=settings.WIKI_DEFAULT_LANGUAGE))
        eq_(200, response.status_code)
        doc = pq(response.content)
        eq_('%s xss' % title,
            doc('#page-attachments-table .attachment-name-cell').text())
        ok_('&gt;&lt;img src=x onerror=prompt(navigator.userAgent);&gt;' in
            doc('#page-attachments-table .attachment-name-cell').html())
开发者ID:Faldrian,项目名称:kuma,代码行数:29,代码来源:test_templates.py

示例7: item_description

    def item_description(self, item):
        previous = item.get_previous()
        if previous is None:
            return '<p>Created by: %s</p>' % item.creator.username
        # TODO: put this in a jinja template if django syndication will let us
        by = '<p>Edited by: %s</p>' % item.creator.username
        comment = '<p>Comment: %s</p>' % item.comment
        diff = ("Diff:<blockquote>%s</blockquote>" % (
            diff_inline(previous.content, item.content)))

        diff = (diff.replace('<ins', '<ins style="background-color: #AAFFAA;"')
                .replace('<del', '<del style="background-color: #FFAAAA;"'))

        link_cell = '<td><a href="%s">%s</a></td>'
        view_cell = link_cell % (reverse('wiki.document',
                                         args=[item.document.full_path]),
                                 _('View Page'))
        edit_cell = link_cell % (reverse('wiki.edit_document',
                                         args=[item.document.full_path]),
                                 _('Edit Page'))
        compare_cell = link_cell % (reverse('wiki.compare_revisions',
                                         args=[item.document.full_path])
                                    + '?' +
                                    urllib.urlencode({'from': previous.id,
                                                      'to': item.id}),
                                 _('Show comparison'))
        history_cell = link_cell % (reverse('wiki.document_revisions',
                                         args=[item.document.full_path]),
                                 _('History'))
        links_table = '<table border="0" width="80%">'
        links_table = links_table + '<tr>%s%s%s%s</tr>' % (view_cell, edit_cell, compare_cell, history_cell)
        links_table = links_table + '</table>'
        description = "%s%s%s%s" % (by, comment, diff, links_table)
        return description
开发者ID:adherang,项目名称:kuma,代码行数:34,代码来源:feeds.py

示例8: test_advanced_search_questions_num_votes

    def test_advanced_search_questions_num_votes(self):
        """Tests advanced search for questions num_votes filter"""
        q = question(title=u"tags tags tags", save=True)

        # Add two question votes
        questionvote(question=q, save=True)
        questionvote(question=q, save=True)

        self.refresh()

        # Advanced search for questions with num_votes > 5. The above
        # question should be not in this set.
        response = self.client.get(
            reverse("search"),
            {"q": "", "tags": "desktop", "w": "2", "a": "1", "num_voted": 2, "num_votes": 5, "format": "json"},
        )

        eq_(200, response.status_code)

        content = json.loads(response.content)
        eq_(content["total"], 0)

        # Advanced search for questions with num_votes < 1. The above
        # question should be not in this set.
        response = self.client.get(
            reverse("search"),
            {"q": "", "tags": "desktop", "w": "2", "a": "1", "num_voted": 1, "num_votes": 1, "format": "json"},
        )

        eq_(200, response.status_code)

        content = json.loads(response.content)
        eq_(content["total"], 0)
开发者ID:atopal,项目名称:kitsune,代码行数:33,代码来源:test_es.py

示例9: test_created

    def test_created(self):
        """Basic functionality of created filter."""
        created_ds = datetime(2010, 6, 19, 12, 00)

        # on 6/19/2010
        q1 = question(title=u"q1 audio", created=created_ds, save=True)
        q1.tags.add(u"desktop")
        ans = answer(question=q1, save=True)
        answervote(answer=ans, helpful=True, save=True)

        # on 6/21/2010
        q2 = question(title=u"q2 audio", created=(created_ds + timedelta(days=2)), save=True)
        q2.tags.add(u"desktop")
        ans = answer(question=q2, save=True)
        answervote(answer=ans, helpful=True, save=True)

        self.refresh()

        qs = {"a": 1, "w": 2, "format": "json", "sortby": 2, "created_date": "06/20/2010"}

        qs["created"] = constants.INTERVAL_BEFORE
        response = self.client.get(reverse("search"), qs)
        results = json.loads(response.content)["results"]
        eq_([q1.get_absolute_url()], [r["url"] for r in results])

        qs["created"] = constants.INTERVAL_AFTER
        response = self.client.get(reverse("search"), qs)
        results = json.loads(response.content)["results"]
        eq_([q2.get_absolute_url()], [r["url"] for r in results])
开发者ID:atopal,项目名称:kitsune,代码行数:29,代码来源:test_es.py

示例10: test_document_listing

    def test_document_listing(self, flag_is_active):
        """Verify /products/<product slug>/<topic slug> renders articles."""
        flag_is_active.return_value = True

        # Create a topic and product.
        t1 = topic(save=True)
        t2 = topic(save=True)
        p = product(save=True)

        # Create 3 documents with the topic and product and one without.
        for i in range(3):
            doc = revision(is_approved=True, save=True).document
            doc.topics.add(t1)
            doc.products.add(p)
            if i == 1:  # Only one document with t2
                doc.topics.add(t2)

        doc = revision(is_approved=True, save=True).document

        self.refresh()

        # GET the page and verify the content.
        url = reverse('products.documents', args=[p.slug, t1.slug])
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
        doc = pq(r.content)
        eq_(3, len(doc('#document-list > ul > li')))

        # GET the page with refine topic and verify the content.
        url = reverse('products.documents', args=[p.slug, t1.slug])
        url = urlparams(url, refine=t2.slug)
        r = self.client.get(url, follow=True)
        eq_(200, r.status_code)
        doc = pq(r.content)
        eq_(1, len(doc('#document-list > ul > li')))
开发者ID:Uwanja,项目名称:kitsune,代码行数:35,代码来源:test_templates.py

示例11: test_invalid_slugs

    def test_invalid_slugs(self, get_current):
        """Slugs cannot contain /."""
        get_current.return_value.domain = 'testserver'
        client = LocalizingClient()
        client.login(username='admin', password='testpass')
        data = new_document_data()
        error = 'The slug provided is not valid.'

        data['slug'] = 'inva/lid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertContains(response, error)

        data['slug'] = 'no-question-marks?'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertContains(response, error)

        data['slug'] = 'no+plus'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertContains(response, error)

        data['slug'] = 'valid'
        response = client.post(reverse('wiki.new_document'), data)
        self.assertRedirects(response, reverse('wiki.document_revisions',
                                               args=[data['slug']],
                                               locale='en-US'))
开发者ID:fox2mike,项目名称:kitsune,代码行数:25,代码来源:test_views.py

示例12: devmo_url

def devmo_url(context, path):
    """ Create a URL pointing to devmo.
        Look for a wiki page in the current locale, or default to given path
    """
    if hasattr(context["request"], "locale"):
        locale = context["request"].locale
    else:
        locale = settings.WIKI_DEFAULT_LANGUAGE
    try:
        url = cache.get("devmo_url:%s_%s" % (locale, path))
    except:
        return path
    if not url:
        url = reverse("wiki.document", locale=settings.WIKI_DEFAULT_LANGUAGE, args=[path])
        if locale != settings.WIKI_DEFAULT_LANGUAGE:
            try:
                parent = Document.objects.get(locale=settings.WIKI_DEFAULT_LANGUAGE, slug=path)
                """ # TODO: redirect_document is coupled to doc view
                follow redirects vs. update devmo_url calls
                
                target = parent.redirect_document()
                if target:
                parent = target
                """
                child = Document.objects.get(locale=locale, parent=parent)
                url = reverse("wiki.document", locale=locale, args=[child.slug])
            except Document.DoesNotExist:
                pass
        cache.set("devmo_url:%s_%s" % (locale, path), url)
    return url
开发者ID:rbellido,项目名称:kuma,代码行数:30,代码来源:helpers.py

示例13: test_needs_change

    def test_needs_change(self):
        """Test setting and unsetting the needs change flag"""
        # Create a new document and edit it, setting needs_change.
        comment = 'Please update for Firefix.next'
        doc = revision(save=True).document
        data = new_document_data()
        data.update({'needs_change': True,
                     'needs_change_comment': comment,
                     'form': 'doc'})

        # Verify that needs_change can't be set if the user doesn't have
        # the permission.
        self.client.post(reverse('wiki.edit_document', args=[doc.slug]), data)
        doc = Document.uncached.get(pk=doc.pk)
        assert not doc.needs_change
        assert not doc.needs_change_comment

        # Give the user permission, now it should work.
        add_permission(self.u, Document, 'edit_needs_change')
        self.client.post(reverse('wiki.edit_document', args=[doc.slug]), data)
        doc = Document.uncached.get(pk=doc.pk)
        assert doc.needs_change
        eq_(comment, doc.needs_change_comment)

        # Clear out needs_change.
        data.update({'needs_change': False,
                     'needs_change_comment': comment})
        self.client.post(reverse('wiki.edit_document', args=[doc.slug]), data)
        doc = Document.uncached.get(pk=doc.pk)
        assert not doc.needs_change
        eq_('', doc.needs_change_comment)
开发者ID:ejean555,项目名称:kitsune,代码行数:31,代码来源:test_views.py

示例14: test_my_profile_edit

 def test_my_profile_edit(self):
     u = User.objects.get(username='testuser')
     self.client.login(username=u.username, password=TESTUSER_PASSWORD)
     resp = self.client.get(reverse('users.my_profile_edit'))
     eq_(302, resp.status_code)
     ok_(reverse('users.profile_edit', args=(u.username,)) in
         resp['Location'])
开发者ID:skins1,项目名称:kuma,代码行数:7,代码来源:test_views.py

示例15: test_created

    def test_created(self):
        """Basic functionality of created filter."""
        created_ds = datetime(2010, 6, 19, 12, 00)

        # on 6/19/2010
        q1 = question(title=u'q1 audio', created=created_ds, save=True)
        q1.tags.add(u'desktop')
        ans = answer(question=q1, save=True)
        answervote(answer=ans, helpful=True, save=True)

        # on 6/21/2010
        q2 = question(title=u'q2 audio',
                      created=(created_ds + timedelta(days=2)),
                      save=True)
        q2.tags.add(u'desktop')
        ans = answer(question=q2, save=True)
        answervote(answer=ans, helpful=True, save=True)

        self.refresh()

        qs = {'a': 1, 'w': 2, 'format': 'json',
              'sortby': 2, 'created_date': '06/20/2010'}

        qs['created'] = constants.INTERVAL_BEFORE
        response = self.client.get(reverse('search'), qs)
        results = json.loads(response.content)['results']
        eq_([q1.get_absolute_url()], [r['url'] for r in results])

        qs['created'] = constants.INTERVAL_AFTER
        response = self.client.get(reverse('search'), qs)
        results = json.loads(response.content)['results']
        eq_([q2.get_absolute_url()], [r['url'] for r in results])
开发者ID:LASarkar,项目名称:kitsune,代码行数:32,代码来源:test_es.py


注:本文中的sumo.urlresolvers.reverse函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。