Example #1
0
def access_group_members(request, team, group_id):
    try:
        group = AccessGroup.objects.get(team=team, id=group_id)
    except AccessGroup.DoesNotExist:
        return HttpResponseRedirect(reverse('sentry-manage-access-groups', args=[team.slug]))

    form = NewAccessGroupMemberForm(request.POST or None)
    if form.is_valid():
        user = form.cleaned_data['user']
        group.members.add(user)

        messages.add_message(request, messages.SUCCESS,
            _('%s was added to this access group.') % (user.email,))

        return HttpResponseRedirect(reverse('sentry-access-group-members', args=[team.slug, group.id]))

    context = csrf(request)
    context.update({
        'group': group,
        'form': form,
        'member_list': group.members.all(),
        'group_list': AccessGroup.objects.filter(team=team),
        'page': 'members',
        'SUBSECTION': 'groups',
    })

    return render_with_team_context(team, 'sentry/teams/groups/members.html', context, request)
 def test_charter_url_reverse(self):
     url = reverse("tracking:charter_add")
     self.assertEqual(url, "/tracking/charter/new/")
     url = reverse("tracking:charter_update", args=[9999])
     self.assertEqual(url, "/tracking/charter/update/9999/")
     url = reverse("tracking:multi_charter_add")
     self.assertEqual(url, "/tracking/mc/new/")
Example #3
0
 def test_manga_report_view_post(self):
     ReportManga.open.filter(manga=self.manga, created_by=self.user).delete()
     response = self.client.post(
         reverse("manga.report", args=[self.manga.id, self.manga.slug]),
         {"type": ReportMangaType.COPYRIGHT, "comment": "This is a standard copyright violation.", "check": "on"},
     )
     self.assertRedirects(response, reverse("manga.list"))
Example #4
0
File: api.py Project: heshunwq/hue
def export_result(request):
  response = {'status': -1, 'message': _('Exporting result failed.')}

  # Passed by check_document_access_permission but unused by APIs
  notebook = json.loads(request.POST.get('notebook', '{}'))
  snippet = json.loads(request.POST.get('snippet', '{}'))
  data_format = json.loads(request.POST.get('format', 'hdfs-file'))
  destination = json.loads(request.POST.get('destination', ''))
  overwrite = json.loads(request.POST.get('overwrite', False))

  api = get_api(request, snippet)

  if data_format == 'hdfs-file':
    if overwrite and request.fs.exists(destination):
      if request.fs.isfile(destination):
        request.fs.do_as_user(request.user.username, request.fs.rmtree, destination)
      else:
        raise ValidationError(_("The target path is a directory"))
    response['watch_url'] = api.export_data_as_hdfs_file(snippet, destination, overwrite)
    response['status'] = 0
  elif data_format == 'hive-table':
    notebook_id = notebook['id'] or request.GET.get('editor', request.GET.get('notebook'))
    response['watch_url'] = reverse('notebook:execute_and_watch') + '?action=save_as_table&notebook=' + str(notebook_id) + '&snippet=0&destination=' + destination
    response['status'] = 0
  elif data_format == 'hdfs-directory':
    notebook_id = notebook['id'] or request.GET.get('editor', request.GET.get('notebook'))
    response['watch_url'] = reverse('notebook:execute_and_watch') + '?action=insert_as_query&notebook=' + str(notebook_id) + '&snippet=0&destination=' + destination
    response['status'] = 0

  return JsonResponse(response)
def test_wiki_link_patch(client, data):
    public_url = reverse('wiki-links-detail', kwargs={"pk": data.public_wiki_link.pk})
    private_url1 = reverse('wiki-links-detail', kwargs={"pk": data.private_wiki_link1.pk})
    private_url2 = reverse('wiki-links-detail', kwargs={"pk": data.private_wiki_link2.pk})

    users = [
        None,
        data.registered_user,
        data.project_member_without_perms,
        data.project_member_with_perms,
        data.project_owner
    ]

    with mock.patch.object(OCCResourceMixin, "_validate_and_update_version") as _validate_and_update_version_mock:
            patch_data = json.dumps({"title": "test"})
            results = helper_test_http_method(client, 'patch', public_url, patch_data, users)
            assert results == [401, 200, 200, 200, 200]

            patch_data = json.dumps({"title": "test"})
            results = helper_test_http_method(client, 'patch', private_url1, patch_data, users)
            assert results == [401, 200, 200, 200, 200]

            patch_data = json.dumps({"title": "test"})
            results = helper_test_http_method(client, 'patch', private_url2, patch_data, users)
            assert results == [401, 403, 403, 200, 200]
Example #6
0
 def __init__(self):
     self.current_site = Site.objects.get_current()
     self.site_url = '%s://%s' % (PROTOCOL, self.current_site.domain)
     self.blog_url = '%s%s' % (self.site_url,
                               reverse('objectapp_gbobject_archive_index'))
     self.blog_feed = '%s%s' % (self.site_url,
                                reverse('objectapp_gbobject_latest_feed'))
Example #7
0
    def test_votes(self):
        self.client.login(username='testuser', password='testPass')
        #User.objects.create(user=self.user, mailman_id=str(uuid.uuid1()))
        ## use a temp variable below because self.client.session is actually a
        ## property which returns a new instance en each call :-/
        #session = self.client.session
        #session["user_id"] = uuid.uuid1()
        #session.save()
        msg_hash = self._send_message()
        email = Email.objects.get(message_id="msg")
        email.vote(user=self.user, value=1)

        try:
            response = self.client.get(reverse("hk_user_votes"))
        except AttributeError:
            self.fail("Getting the votes should not fail if "
                      "the user has never voted yet\n%s" % format_exc())
        self.assertEqual(response.status_code, 200)
        self.assertContains(response,
            '<a href="{}">Dummy message</a>'.format(
                reverse("hk_message_index", args=("list@example.com", msg_hash)
             )), count=2, html=True)
        self.assertContains(response, 'action="{}">'.format(
                reverse("hk_message_vote", args=("list@example.com", msg_hash)
             )), count=2, html=False)
        self.assertContains(response, "Dummy Sender", count=2, html=False)
Example #8
0
    def test_reg_code_with_multiple_courses_and_checkout_scenario(self):
        self.add_reg_code(self.course_key)

        # Two courses in user shopping cart
        self.login_user()
        PaidCourseRegistration.add_to_order(self.cart, self.course_key)
        PaidCourseRegistration.add_to_order(self.cart, self.testing_course.id)
        self.assertEquals(self.cart.orderitem_set.count(), 2)

        resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': self.reg_code})
        self.assertEqual(resp.status_code, 200)

        resp = self.client.get(reverse('shoppingcart.views.show_cart', args=[]))
        self.assertIn('Check Out', resp.content)
        self.cart.purchase(first='FirstNameTesting123', street1='StreetTesting123')

        resp = self.client.get(reverse('shoppingcart.views.show_receipt', args=[self.cart.id]))
        self.assertEqual(resp.status_code, 200)

        ((template, context), _) = render_mock.call_args  # pylint: disable=W0621
        self.assertEqual(template, 'shoppingcart/receipt.html')
        self.assertEqual(context['order'], self.cart)
        self.assertEqual(context['order'].total_cost, self.testing_cost)

        course_enrollment = CourseEnrollment.objects.filter(user=self.user)
        self.assertEqual(course_enrollment.count(), 2)
Example #9
0
def edit_snippet(request, snippet_id=None):
    "Edits an existing code snippet"

    if snippet_id is None:
        raise Http404()

    template_name = "snippets/edit.html"

    if request.method == "POST":
        form = CodeSnippetForm(request.POST)
        if form.is_valid():
            snippet = get_snippet_or_404(snippet_id)
            snippet = copy_snippet_from_form(form, snippet=snippet)
            snippet.put()
            index_snippet_with_search(snippet)

            return HttpResponseRedirect(reverse("snippets:snippet-detail", kwargs={"snippet_id": snippet.key().id()}))
    else:
        initial_data = {}
        snippet = get_snippet_or_404(snippet_id)
        initial_data.update(db.to_dict(snippet))
        form = CodeSnippetForm(initial=initial_data, auto_id=False)

    ctx = {}
    ctx["form"] = form
    ctx["form_action"] = reverse("snippets:edit-snippet", kwargs={"snippet_id": snippet_id})

    return render_to_response(template_name, context_instance=RequestContext(request, ctx))
Example #10
0
    def test_reg_code_free_discount_with_multiple_courses_in_cart(self, info_log):

        reg_item = self.add_course_to_user_cart()
        self.add_reg_code(self.course_key)
        cert_item = CertificateItem.add_to_order(self.cart, self.verified_course_key, self.cost, 'honor')
        self.assertEquals(self.cart.orderitem_set.count(), 2)

        resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': self.reg_code})
        self.assertEqual(resp.status_code, 200)

        # unit_cost should be 0 for that particular course for which registration code is registered
        items = self.cart.orderitem_set.all().select_subclasses()
        for item in items:
            if item.id == reg_item.id:
                self.assertEquals(item.unit_cost, 0)
            elif item.id == cert_item.id:
                self.assertEquals(item.list_price, None)

        # Delete the discounted item, corresponding reg code redemption should be removed for that particular item
        resp = self.client.post(reverse('shoppingcart.views.remove_item', args=[]),
                                {'id': reg_item.id})

        self.assertEqual(resp.status_code, 200)
        self.assertEquals(self.cart.orderitem_set.count(), 1)
        info_log.assert_called_with(
            'Registration code "{0}" redemption entry removed for user "{1}" for order item "{2}"'.format(self.reg_code, self.user, reg_item.id))
Example #11
0
 def test_postpay_callback_success(self):
     postpay_mock.return_value = {'success': True, 'order': self.cart}
     self.login_user()
     resp = self.client.post(reverse('shoppingcart.views.postpay_callback', args=[]))
     self.assertEqual(resp.status_code, 302)
     self.assertEqual(urlparse(resp.__getitem__('location')).path,
                      reverse('shoppingcart.views.show_receipt', args=[self.cart.id]))
Example #12
0
    def dispatch(self, request, organization_slug):
        from sentry.auth.helper import AuthHelper
        helper = AuthHelper.get_for_request(request)

        # SP initiated authentication, request helper is provided
        if helper:
            from sentry.web.frontend.auth_provider_login import AuthProviderLoginView
            sso_login = AuthProviderLoginView()
            return sso_login.handle(request)

        # IdP initiated authentication. The organizatio_slug must be valid and
        # an auth provider must exist for this organization to proceed with
        # IdP initiated SAML auth.
        try:
            organization = Organization.objects.get(slug=organization_slug)
        except Organization.DoesNotExist:
            messages.add_message(request, messages.ERROR, ERR_NO_SAML_SSO)
            return self.redirect(reverse('sentry-login'))

        try:
            auth_provider = AuthProvider.objects.get(organization=organization)
        except AuthProvider.DoesNotExist:
            messages.add_message(request, messages.ERROR, ERR_NO_SAML_SSO)
            return self.redirect(reverse('sentry-login'))

        helper = AuthHelper(
            request=request,
            organization=organization,
            auth_provider=auth_provider,
            flow=AuthHelper.FLOW_LOGIN,
        )

        helper.init_pipeline()
        return helper.current_step()
Example #13
0
    def get_context_data(self, **kwargs):
        context = super(ProjectDetailView, self).get_context_data(**kwargs)

        project = self.get_object()
        context['versions'] = Version.objects.public(
            user=self.request.user, project=project)
        context['filter'] = VersionSlugFilter(self.request.GET,
                                              queryset=context['versions'])

        protocol = 'http'
        if self.request.is_secure():
            protocol = 'https'

        context['badge_url'] = "%s://%s%s?version=%s" % (
            protocol,
            settings.PRODUCTION_DOMAIN,
            reverse('project_badge', args=[project.slug]),
            project.get_default_version(),
        )
        context['site_url'] = "%s://%s%s?badge=%s" % (
            protocol,
            settings.PRODUCTION_DOMAIN,
            reverse('projects_detail', args=[project.slug]),
            project.get_default_version(),
        )

        return context
Example #14
0
def access_group_projects(request, team, group_id):
    try:
        group = AccessGroup.objects.get(team=team, id=group_id)
    except AccessGroup.DoesNotExist:
        return HttpResponseRedirect(reverse('sentry-manage-access-groups', args=[team.slug]))

    form = NewAccessGroupProjectForm(group, request.POST or None)
    if form.is_valid():
        project = form.cleaned_data['project']
        group.projects.add(project)

        messages.add_message(request, messages.SUCCESS,
            _('%s was added to this access group.') % (project.name,))

        return HttpResponseRedirect(reverse('sentry-access-group-projects', args=[team.slug, group.id]))

    group_list = list(AccessGroup.objects.filter(team=team))
    for g_ in group_list:
        g_.team = team

    context = csrf(request)
    context.update({
        'group': group,
        'form': form,
        'project_list': group.projects.all(),
        'group_list': group_list,
        'page': 'projects',
        'SUBSECTION': 'groups',
    })

    return render_with_team_context(team, 'sentry/teams/groups/projects.html', context, request)
    def get_absolute_url(self, language=None, fallback=True):
        try:
            if self.is_home():
                return reverse('pages-root')
        except NoHomeFound:
            pass
        if settings.CMS_FLAT_URLS:
            path = self.get_slug(language, fallback)
        else:
            path = self.get_path(language, fallback)
            if hasattr(self, "home_cut_cache") and self.home_cut_cache:
                if not self.get_title_obj_attribute("has_url_overwrite", language, fallback) and path:
                    path = "/".join(path.split("/")[1:])
            else:    
                home_pk = None
                try:
                    home_pk = self.home_pk_cache
                except NoHomeFound:
                    pass
                ancestors = self.get_cached_ancestors(ascending=True)
                if self.parent_id and ancestors[-1].pk == home_pk and not self.get_title_obj_attribute("has_url_overwrite", language, fallback) and path:
                    path = "/".join(path.split("/")[1:])
            
        if settings.CMS_DBGETTEXT and settings.CMS_DBGETTEXT_SLUGS:
            path = '/'.join([ugettext(p) for p in path.split('/')])

        return urljoin(reverse('pages-root'), path)
Example #16
0
    def test_task_history(self):
        self.test_add_task()

        url = reverse("task:add_tasklist", kwargs={
            "username": TEST_DATA['user']['username'],
        })
        response = self.client.post(url, TEST_DATA['tasklist_2'], follow=True)

        url = reverse("task:edit_task", kwargs={
            "username": TEST_DATA['user']['username'],
            "task_id": 1,
        })
        response = self.client.post(url, TEST_DATA['task_edit_for_history'], follow=True)

        url = reverse("task:view_task", kwargs={
            "username": TEST_DATA['user']['username'],
            "task_id": 1,
        })
        response = self.client.get(url)

        self.assertContains(response, TEST_DATA['task']['name'])
        self.assertContains(response, TEST_DATA['task']['description'])
        self.assertContains(response, TEST_DATA['task_edit_for_history']['name'])
        self.assertContains(response, TEST_DATA['task_edit_for_history']['description'])
        self.assertContains(response, TEST_DATA['tasklist']['name'])
        self.assertContains(response, TEST_DATA['tasklist_2']['name'])
Example #17
0
File: forms.py Project: gisce/AMON
    def __init__(self, *args, **kwargs):
        self.form_data = kwargs.pop('provider_data', None)

        super(AmazonForm, self).__init__(*args, **kwargs)

        try:
            self.fields['name'].initial = self.form_data.get('name')
            self.fields['access_key'].initial = self.form_data.get('access_key')
            self.fields['secret_key'].initial = self.form_data.get('secret_key')
            self.fields['regions'].initial = self.form_data.get('regions')

            self.fields['regions'].widget.attrs.update({
                'tags-dropdown': '', 
                'data-size': 480,
                'read-only': True,
                'data-tags-url': reverse('api_cloudservers_get_amazon_regions'),
                'data-url': reverse('api_cloudservers_get_amazon_regions'),
            })

        except:
            self.fields['regions'].widget.attrs.update({
                'tags-dropdown': '', 
                'data-size': 480,
                'data-tags-url': reverse('api_cloudservers_get_amazon_regions'),
            })
Example #18
0
    def test_courseware_page_unfulfilled_prereqs(self):
        """
        Test courseware access when a course has pre-requisite course yet to be completed
        """
        seed_milestone_relationship_types()
        pre_requisite_course = CourseFactory.create(org="edX", course="900", run="test_run")

        pre_requisite_courses = [unicode(pre_requisite_course.id)]
        course = CourseFactory.create(
            org="edX", course="1000", run="test_run", pre_requisite_courses=pre_requisite_courses
        )
        set_prerequisite_courses(course.id, pre_requisite_courses)

        test_password = "t3stp4ss.!"
        user = UserFactory.create()
        user.set_password(test_password)
        user.save()
        self.login(user.email, test_password)
        CourseEnrollmentFactory(user=user, course_id=course.id)

        url = reverse("courseware", args=[unicode(course.id)])
        response = self.client.get(url)
        self.assertRedirects(response, reverse("dashboard"))
        self.assertEqual(response.status_code, 302)

        fulfill_course_milestone(pre_requisite_course.id, user)
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
 def make_request(self, request):
     """
     We need this to be a method and not a function, since we need to have
     a reference to the shop interface
     """
     order = self.shop.get_order(request)
     base_url = '%s://%s' % ('https' if request.is_secure() else 'http', request.get_host())
     signed_order = signing.dumps({'order_id': order.pk})
     xml_request = render_to_string('shop_sofortpayment/xml/new_transaction.xml', {
         'project_id': settings.SHOP_SOFORT_PROJECT_ID,
         'language_code': get_language(),
         'interface_version': 'django-shop-sofortpayment-' + __version__,
         'amount': order.order_total,
         'currency': settings.SHOP_SOFORT_CURRENCY,
         'order_number': order.pk,
         'user_name': order.billing_address_text,
         'success_url': '%s%s?s=%s' % (base_url, reverse('sofort_success'), signed_order),
         'notification_url': '%s%s?s=%s' % (base_url, reverse('sofort_notify'), signed_order),
         'abort_url': base_url + reverse('cart'),
         'customer_protection': '1' if settings.SHOP_SOFORT_ENABLE_CUSTOMER_PROTECTION else '0',
     })
     response = requests.post(
         settings.SHOP_SOFORT_API_ENDPOINT,
         data=xml_request.encode('utf-8'),
         headers={'Content-Type': 'application/xml; charset=UTF-8'},
         auth=(settings.SHOP_SOFORT_CUSTOMER_NUMBER, settings.SHOP_SOFORT_API_KEY),
     )
     if response.status_code == 200:
         doc = xmltodict.parse(response.content)
         transaction = SofortTransaction.objects.create(
             order=order,
             transaction_number=doc['new_transaction']['transaction'],
         )
         return HttpResponseRedirect(doc['new_transaction']['payment_url'])
     return render_to_response("shop_sofortpayment/payment.html", context)
Example #20
0
    def test_delete_member(self):
        " Delete member from group "
        self.client.login(username='john', password='doo')

        response = self.client.get(reverse('project-member-delete', kwargs = {'model_slug': 'busy-lizzy', 'member_slug': 'jane'}))

        self.assertRedirects(response, reverse('project-detail', kwargs = {'slug': 'busy-lizzy'}), target_status_code=200)
Example #21
0
 def _wrapped_view(request, *args, **kwargs):
     mv = MessageVerification.objects.get(user=request.user)
     if not mv.verified:
         return redirect(reverse("accounts.views.sms_verify"))
     if not request.user.profile.activated:
         return redirect(reverse("accounts.views.not_activated"))
     return view_func(request, *args, **kwargs)
Example #22
0
    def test_private_pages_auth(self):
        """Make sure pages that do require login work."""
        auth_pages = (
            reverse('index'),
        )

        # These are pages that should just load when the user is logged in
        # (no data needed)
        simple_auth_pages = (
            reverse('index'),
        )

        # need an activated user
        self.test_create_account()

        # Create a new session
        self.client = Client()

        # Not logged in.  Should redirect to login.
        print('Not logged in')
        for page in auth_pages:
            print("Checking '{0}'".format(page))
            self.check_page_get(page, expected=302)

        # Logged in should work.
        self.login(self.email, self.pw)

        print('Logged in')
        for page in simple_auth_pages:
            print("Checking '{0}'".format(page))
            self.check_page_get(page, expected=200)
def test_wiki_link_update(client, data):
    public_url = reverse('wiki-links-detail', kwargs={"pk": data.public_wiki_link.pk})
    private_url1 = reverse('wiki-links-detail', kwargs={"pk": data.private_wiki_link1.pk})
    private_url2 = reverse('wiki-links-detail', kwargs={"pk": data.private_wiki_link2.pk})

    users = [
        None,
        data.registered_user,
        data.project_member_without_perms,
        data.project_member_with_perms,
        data.project_owner
    ]

    with mock.patch.object(OCCResourceMixin, "_validate_and_update_version") as _validate_and_update_version_mock:
            wiki_link_data = WikiLinkSerializer(data.public_wiki_link).data
            wiki_link_data["title"] = "test"
            wiki_link_data = json.dumps(wiki_link_data)
            results = helper_test_http_method(client, 'put', public_url, wiki_link_data, users)
            assert results == [401, 200, 200, 200, 200]

            wiki_link_data = WikiLinkSerializer(data.private_wiki_link1).data
            wiki_link_data["title"] = "test"
            wiki_link_data = json.dumps(wiki_link_data)
            results = helper_test_http_method(client, 'put', private_url1, wiki_link_data, users)
            assert results == [401, 200, 200, 200, 200]

            wiki_link_data = WikiLinkSerializer(data.private_wiki_link2).data
            wiki_link_data["title"] = "test"
            wiki_link_data = json.dumps(wiki_link_data)
            results = helper_test_http_method(client, 'put', private_url2, wiki_link_data, users)
            assert results == [401, 403, 403, 200, 200]
Example #24
0
    def test_channel_edit_child(self):
        channel = Channel.objects.get(slug='testing')
        response = self.client.get(
            reverse('manage:channel_edit', args=(channel.pk,)),
        )
        eq_(response.status_code, 200)
        choices = (
            response.content
            .split('name="parent"')[1]
            .split('</select>')[0]
        )
        ok_('Main' in choices)
        # you should not be able to self-reference
        ok_('Testing' not in choices)

        main = Channel.objects.get(slug='main')
        response = self.client.post(
            reverse('manage:channel_edit', args=(channel.pk,)),
            {
                'name': 'Different',
                'slug': 'different',
                'description': '<p>Other things</p>',
                'parent': main.pk,
                'feed_size': 10,
            }
        )
        eq_(response.status_code, 302)
        channel = Channel.objects.get(slug='different')
        eq_(channel.parent, main)

        # now expect two links to "Main" on the channels page
        response = self.client.get(reverse('manage:channels'))
        eq_(response.status_code, 200)
        view_url = reverse('main:home_channels', args=(main.slug,))
        eq_(response.content.count(view_url), 2)
Example #25
0
def profile_page(request, view_user):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('forum.views.main_index',))
    else:
        if request.user.username == view_user:
            if request.method == 'POST':
                #print request.FILES
                form_profile = ProfileUpdate(request.POST, request.FILES)
                if form_profile.is_valid():
                    # process data
                    cd = form_profile.cleaned_data
                    user_update = ForumUser.objects.get(user=request.user)
                    
                    success_reply = []
                    
                    if request.FILES:
                        f = request.FILES['avatar_img']
                        
                        destination = open('%s/avatars/%s' % (settings.MEDIA_ROOT, f.name), 'wb+')
                        for chunk in f.chunks():
                            destination.write(chunk)
                        destination.close()
                        
                        user_update.avatar_img = "avatars/%s" % f.name
                        user_update.save()
                        
                        # uploadedImage = cd['avatar_img']
                        # user_update = (request.FILES)
                    
                    if(cd['password1']):
                        user_update.user.set_password(cd['password1'])
                        user_update.user.save()
                        success_reply.append('Password')
                        
                    if(cd['email1'] != user_update.user.email and cd['email1'] != ''):
                        user_update.user.email = cd['email1']
                        user_update.user.save()
                        success_reply.append('Email')
                    
                    return render_to_response('profile_page.html', {'form_profile' : form_profile, 'success_reply': success_reply,
                                'forum_user': user_update, 'site_root': reverse('forum.views.main_index'), },
                                context_instance=RequestContext(request))
            else:
                default_data = {
                    'email1': request.user.email,
                    'email2': request.user.email,
                }
        
                form_profile = ProfileUpdate(default_data)
                try:
                    forum_user = ForumUser.objects.get(user=request.user)
                except:
                    forum_user = ForumUser(user=request.user)
                    forum_user.save()
        
            return render_to_response('profile_page.html', {'form_profile' : form_profile, 'forum_user' : forum_user,
                                'site_root': reverse('forum.views.main_index',),},
                                context_instance=RequestContext(request))
        else:
            return HttpResponseRedirect(reverse('forum.views.main_index',))
Example #26
0
    def test_api_nodes_delete(self):
        # # Creating the nodetype
        data = {'name': self.nodetype_name}
        url = reverse("api_node_types", args=[self.graph_slug])
        nodetype_slug = check_nodes_get(self, url, data)
        # # Creating the property for the nodetype
        url = reverse("api_node_type_schema_properties",
                      args=[self.graph_slug, nodetype_slug])
        property_name = 'prop_name'
        property_datatype = 'default'
        property_data = {
            'key': property_name,
            'datatype': property_datatype
        }
        create_property(self, url, property_data, property_name)
        # # Creating the nodes
        url = reverse("api_nodes",
                      args=[self.graph_slug, nodetype_slug])
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data['nodes'], [])

        node_name1 = "nodeName1"
        node_data1 = {property_name: node_name1}
        node_name2 = "nodeName2"
        node_data2 = {property_name: node_name2}
        nodes_list = []
        nodes_list.append(node_data1)
        nodes_list.append(node_data2)
        nodes_ids = create_nodes(self, url, nodes_list)
        self.assertEqual(len(nodes_ids), 2)

        # # Deleting the nodes
        delete_nodes(self, url, nodes_ids)
 def test_ajax_url_reverse(self):
     url = reverse("tracking:ajax_charter_events", args=[9999])
     self.assertEqual(url, "/tracking/ajax/charter_events/9999/")
     url = reverse("tracking:ajax_ds_charter_list")
     self.assertEqual(url, "/tracking/ajax/charters/")
     url = reverse("tracking:new_charter_modal")
     self.assertEqual(url, "/tracking/ajax/charter/modal/")
Example #28
0
def check_relationships(test, url, data_source, data_target):
    response = test.client.post(url, data_source)
    # We check that the request is correct
    test.assertEqual(response.status_code, 201)
    source_slug = response.data['slug']
    response = test.client.post(url, data_target)
    # We check that the request is correct
    test.assertEqual(response.status_code, 201)
    target_slug = response.data['slug']
    data = {'name': test.relationshiptype_name,
            'source': source_slug,
            'target': target_slug}
    url = reverse("api_relationship_types", args=[test.graph_slug])
    # Then, we check the post method
    response = test.client.post(url, data)
    data = {'name': test.relationshiptype_name}
    relationshiptype_name = response.data['name']
    test.assertEqual(relationshiptype_name, test.relationshiptype_name)
    response = test.client.get(url)
    relationshiptype_slug = response.data[0]['slug']
    url = reverse("api_relationship_type",
                  args=[test.graph_slug, relationshiptype_slug])
    response = test.client.get(url)
    test.assertEqual(response.status_code, 200)
    test.assertEqual(response.data['name'], test.relationshiptype_name)
    test.assertEqual(response.data['rels_info'], [])
    return (relationshiptype_slug, source_slug, target_slug)
Example #29
0
def login_view(request, message='', username="", password="", template='user/login.html', modal=False):
    modal = request.REQUEST.get("modal", False)
    close = request.REQUEST.get("close", False)
    if modal == "true":
        template = 'user/login_modal.html'

    if not request.user.is_anonymous():
        return HttpResponseRedirect(reverse("home"))

    next = request.REQUEST.get('next', reverse('home'))

    if request.POST:
        username = request.POST['username']
        email_exists = User.objects.filter(email=username)
        if email_exists:
            username = email_exists[0].username

        password = request.POST['password']

        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                login(request, user)
                return SuccessfulSignInRedirect(next, modal, request, close=close)

        message = "Error logging you in, are you sure you're using the right credentials?"

    context ={'message' : message, 'next' : next, 'username': username, 'password': password, 'modal': modal, 'close': close }
    return render_to_response(template, context, context_instance = RequestContext(request))
Example #30
0
def remove_access_group(request, team, group_id):
    try:
        group = AccessGroup.objects.get(team=team, id=group_id)
    except AccessGroup.DoesNotExist:
        return HttpResponseRedirect(reverse('sentry-manage-access-groups', args=[team.slug]))

    if request.method == 'POST':
        form = RemoveAccessGroupForm(request.POST)
    else:
        form = RemoveAccessGroupForm()

    if form.is_valid():
        group.delete()

        messages.add_message(request, messages.SUCCESS,
            _('%s was permanently removed.') % (group.name,))

        return HttpResponseRedirect(reverse('sentry-manage-access-groups', args=[team.slug]))

    context = csrf(request)
    context.update({
        'form': form,
        'group': group,
        'page': 'details',
        'SUBSECTION': 'groups',
    })

    return render_with_team_context(team, 'sentry/teams/groups/remove.html', context, request)