Example #1
1
def redirect_to_default(req, domain=None):
    if not req.user.is_authenticated():
        if domain != None:
            url = reverse("domain_login", args=[domain])
        else:
            # this actually gets hijacked by the static site, but is necessary
            url = reverse("corehq.apps.hqwebapp.views.landing_page")
    else:
        if domain:
            domain = normalize_domain_name(domain)
            domains = [Domain.get_by_name(domain)]
        else:
            domains = Domain.active_for_user(req.user)
        if 0 == len(domains) and not req.user.is_superuser:
            return redirect("registration_domain")
        elif 1 == len(domains):
            if domains[0]:
                domain = domains[0].name
                if req.couch_user.is_commcare_user():
                    url = reverse("cloudcare_main", args=[domain, ""])
                elif req.couch_user.can_view_reports(domain) or req.couch_user.get_viewable_reports(domain):
                    url = reverse("corehq.apps.reports.views.default", args=[domain])
                else:
                    url = reverse("corehq.apps.app_manager.views.default", args=[domain])
            else:
                raise Http404
        else:
            url = settings.DOMAIN_SELECT_URL
    return HttpResponseRedirect(url)
Example #2
1
    def index(self, request, rid):
        repo = get_object_or_404(Repository.reader_queryset(request), id=rid, archive_type=self.archive_type)
        states = [state for state in ArchiveState.objects.filter(repository=repo).order_by("name")]
        tab_infos = [
            (
                reverse("jetbrains:plugin_index", kwargs={"rid": repo.id, "repo_slug": repo.slug}),
                ArchiveState(name=_("All states"), slug="all-states"),
                states,
            )
        ]
        tab_infos += [
            (
                reverse(
                    "jetbrains:plugin_index", kwargs={"rid": repo.id, "repo_slug": repo.slug, "state_slug": state.slug}
                ),
                state,
                [state],
            )
            for state in states
        ]

        template_values = {
            "repo": repo,
            "states": states,
            "upload_allowed": repo.upload_allowed(request),
            "index_url": reverse(moneta_url(repo, "index"), kwargs={"rid": repo.id}),
            "tab_infos": tab_infos,
            "admin_allowed": repo.admin_allowed(request),
        }
        return render_to_response(self.index_html, template_values, RequestContext(request))
Example #3
1
    def test_concurrent_edition_with_conflict(self):
        self.page.raw = "- item1"
        Git().commit(self.page, message="original")
        response1 = self.client.get(self.edit_url)
        response2 = self.client.get(self.edit_url)

        data1 = response1.context[0]["form"].initial
        data1["raw"] = "- item2"
        data1["message"] = "add item2"

        data2 = response2.context[0]["form"].initial
        data2["raw"] = "- item0"
        data1["message"] = "add item0"
        r = self.client.post(self.edit_url, data1)
        self.assertRedirects(r, reverse("waliki_detail", args=(self.page.slug,)))
        r = self.client.post(self.edit_url, data2)
        self.assertRedirects(r, self.edit_url)

        self.assertEqual("", git.status("--porcelain", self.page.path).stdout.decode("utf8"))
        self.assertIn(
            "Merged with conflict",
            git.log("--no-color", "--pretty=format:%s", "-n 1", self.page.path).stdout.decode("utf8"),
        )
        self.assertRegexpMatches(self.page.raw, "<<<<<<< HEAD\n- item2\n=======\n- item0\n>>>>>>> [0-9a-f]{7}\n")

        # can edit in conflict
        response = self.client.get(self.edit_url)
        data1 = response.context[0]["form"].initial
        data1["raw"] = "- item0\n- item2"
        data1["message"] = "fixing :)"
        response = self.client.post(self.edit_url, data1)
        self.assertRedirects(response, reverse("waliki_detail", args=(self.page.slug,)))
        self.assertEqual(self.page.raw, "- item0\n- item2")
Example #4
1
    def test_no_double_signup(self):
        "Don't allow new registration with an exiting email"

        res = self.client.post(
            reverse("register"),
            {
                "username": "first_jack",
                "password1": "123",
                "password2": "123",
                "email": "double_jack@example.com",
                "email_notification": "D",
            },
            follow=True,
        )

        self.assertEqual(res.redirect_chain, [("http://testserver/users/edit-profile/", 302)])

        res = self.client.post(
            reverse("register"),
            {
                "username": "double_jack",
                "password1": "123",
                "password2": "123",
                "email": "double_jack@example.com",
                "email_notification": "D",
            },
            follow=True,
        )
        # Now try to create another user with some email
        self.assertContains(res, "errorlist")
Example #5
1
 def __init__(self, *args, **kwargs):
     super(AdministrativeContactForm, self).__init__(*args, **kwargs)
     self.helper.layout = Layout(
         Div(
             Column("function", "default_phone", "default_mail", css_class="col-md-6"),
             Column(
                 FieldWithButtons(
                     "company",
                     StrictButton(
                         "<a href='%s' target='_blank'><span class='glyphicon glyphicon-plus'></span></a>"
                         % reverse("crm.views.company")
                     ),
                 ),
                 "default_fax",
                 FieldWithButtons(
                     "contact",
                     StrictButton(
                         "<a href='%s' target='_blank'><span class='glyphicon glyphicon-plus'></span></a>"
                         % reverse("contact_add")
                     ),
                 ),
                 css_class="col-md-6",
             ),
             css_class="row",
         ),
         self.submit,
     )
Example #6
1
def login(request, form_class=LoginForm, template_name="account/login.html"):
    if request.method == "POST":
        default_redirect_to = getattr(settings, "LOGIN_REDIRECT_URLNAME", None)
        if default_redirect_to:
            default_redirect_to = reverse(default_redirect_to)
        else:
            default_redirect_to = settings.LOGIN_REDIRECT_URL
        next = request.REQUEST.get("next")
        redirect_to = next
        # light security check -- make sure redirect_to isn't garabage.
        if not redirect_to or "://" in redirect_to or " " in redirect_to:
            next = None
            redirect_to = default_redirect_to
        form = form_class(request.POST)
        user = form.login(request)
        if user:
            user_parties = user.parties.all()
            if user_parties:
                if user_parties.count() > 1:
                    redirect_to = reverse("party_chooser")
                else:
                    party = user_parties[0].party
                    # todo: dashboards maybe shd be in models?
                    if party.is_customer():
                        redirect_to = reverse("customer_dashboard")
                    elif party.is_producer():
                        redirect_to = reverse("producer_dashboard")
            elif user.is_staff:
                if not next:
                    redirect_to = reverse("dashboard")
            return HttpResponseRedirect(redirect_to)
    else:
        form = form_class()
    return render_to_response(template_name, {"form": form}, context_instance=RequestContext(request))
Example #7
0
    def form_valid(self, form):
        name = form.cleaned_data["name"]
        attending = form.cleaned_data["attending"] == 1
        song_requests = form.cleaned_data["song_requests"]
        dietary_reqs = form.cleaned_data["dietary_reqs"]
        message = form.cleaned_data["message"]
        postcode = form.cleaned_data["postcode"]
        lat = form.cleaned_data["lat"]
        lng = form.cleaned_data["lng"]

        self.success_url = reverse("rsvp-attending") if attending else reverse("rsvp-declined")

        model = RSVPModel(
            name=name,
            attending=attending,
            song_requests=song_requests,
            dietary_reqs=dietary_reqs,
            message=message,
            postcode=postcode,
            lat=lat,
            lng=lng,
        )

        model.put()

        mail.send_mail(
            sender="neale.dj@gmail.com",
            to="neale.dj@gmail.com",
            subject="Wedding Registration - %s is %sattending" % (name, "not " if not attending else ""),
            body=message,
        )

        return super(RSVPView, self).form_valid(form)
Example #8
0
    def get_redirect_url(self, *args, **kwargs):
        """
        Do ContentNegotiation for some resource and
        redirect to the appropriate place
        """
        label = self.kwargs.get("label")
        type_ = self.kwargs.get("type_")
        url_kwargs = {"label": label}
        extension_ = self.kwargs.get("extension")
        mimetype = get_lod_mime_type(extension_, self.request)

        if mimetype and mimetype in RDF_SUPPORTED_MIME_TYPES:
            path = "lod_data_detail"
            url_kwargs["extension"] = mime_to_extension(mimetype)
        elif USE_EDM_BINDINGS and type_ in ["aggregation"]:
            path = "edm_lod_page_detail"
            return reverse(path, kwargs=url_kwargs)
        else:
            path = "lod_page_detail"

        if type_:
            path = "typed_{}".format(path)
            url_kwargs["type_"] = type_

        return reverse(path, kwargs=url_kwargs)
def external_start(request, login_associate, provider):
    if "googlebot(at)googlebot.com" in request.META.get("HTTP_FROM", ""):
        return HttpResponseNotFound()

    if not provider in providers.providers:
        return HttpResponseNotFound()

    if login_associate == "associate" and not request.user.is_authenticated():
        login_associate = "login"

    if "next" in request.GET:
        validate_next(request, request.GET["next"])  # raises exception on error
        request.session["oauth_finish_next"] = request.GET["next"]

    if providers.providers[provider]["method"] == "openid2" or True:
        # the callback must match the realm, which is always SITE_ROOT_URL
        callback = SITE_ROOT_URL + reverse(external_return, args=[login_associate, provider])
    else:
        # be nicer and build the callback URL from the HttpRequest, in case we are not
        # hosting SITE_ROOT_URL (i.e. debugging).
        callback = request.build_absolute_uri(reverse(external_return, args=[login_associate, provider]))
    request.session["oauth_finish_url"] = callback

    scope = request.GET.get("scope", None)
    mode = request.GET.get("mode", None)

    response = HttpResponseRedirect(
        providers.methods[providers.providers[provider]["method"]]["get_redirect"](
            request, provider, callback, scope, mode
        )
    )
    response["Cache-Control"] = "no-store"
    return response
Example #10
0
    def test_login_and_registration_form_signin_preserves_params(self, is_edx_domain, url_name):
        params = [("course_id", "edX/DemoX/Demo_Course"), ("enrollment_action", "enroll")]

        # The response should have a "Sign In" button with the URL
        # that preserves the querystring params
        with mock.patch.dict(settings.FEATURES, {"IS_EDX_DOMAIN": is_edx_domain}):
            response = self.client.get(reverse(url_name), params)

        expected_url = "/login?{}".format(self._finish_auth_url_param(params + [("next", "/dashboard")]))
        self.assertContains(response, expected_url)

        # Add additional parameters:
        params = [
            ("course_id", "edX/DemoX/Demo_Course"),
            ("enrollment_action", "enroll"),
            ("course_mode", "honor"),
            ("email_opt_in", "true"),
            ("next", "/custom/final/destination"),
        ]

        # Verify that this parameter is also preserved
        with mock.patch.dict(settings.FEATURES, {"IS_EDX_DOMAIN": is_edx_domain}):
            response = self.client.get(reverse(url_name), params)

        expected_url = "/login?{}".format(self._finish_auth_url_param(params))
        self.assertContains(response, expected_url)
Example #11
0
    def setUp(self):
        self.register_url = reverse("accounts-registration")

        self.data = {"password": "vjq1gfhjkm"}

        response = self.client.post(self.register_url, self.data)
        self.number = response.data["number"]
        self.token = response.data["token"]
        self.user_owner = get_user_model().objects.get(pk=self.number)
        self.client.credentials(HTTP_AUTHORIZATION="Token {}".format(self.token))

        response = self.client.post(self.register_url, self.data)
        self.number = response.data["number"]
        self.user_foreign = get_user_model().objects.get(pk=self.number)

        self.expected_response_keys = {
            "number",
            "brains",
            "is_guest",
            "last_name",
            "first_name",
            "middle_name",
            "phone",
            "email",
        }
        self.profile_url = reverse("accounts-detail", kwargs={"pk": self.number})
    def test_registration(self):
        """
        Registration creates a new inactive account and a new profile
        with activation key, populates the correct account data and
        sends an activation email.

        """
        resp = self.client.post(
            reverse("registration_register"),
            data={"username": "bob", "email": "bob@example.com", "password1": "secret", "password2": "secret"},
        )
        self.assertRedirects(resp, reverse("registration_complete"))

        new_user = User.objects.get(username="bob")

        self.failUnless(new_user.check_password("secret"))
        self.assertEqual(new_user.email, "bob@example.com")

        # New user must not be active.
        self.failIf(new_user.is_active)

        # A registration profile was created, and an activation email
        # was sent.
        self.assertEqual(RegistrationProfile.objects.count(), 1)
        self.assertEqual(len(mail.outbox), 1)
    def test_allow(self):
        """
        The setting ``REGISTRATION_OPEN`` appropriately controls
        whether registration is permitted.

        """
        old_allowed = getattr(settings, "REGISTRATION_OPEN", True)
        settings.REGISTRATION_OPEN = True

        resp = self.client.get(reverse("registration_register"))
        self.assertEqual(200, resp.status_code)

        settings.REGISTRATION_OPEN = False

        # Now all attempts to hit the register view should redirect to
        # the 'registration is closed' message.
        resp = self.client.get(reverse("registration_register"))
        self.assertRedirects(resp, reverse("registration_disallowed"))

        resp = self.client.post(
            reverse("registration_register"),
            data={"username": "bob", "email": "bob@example.com", "password1": "secret", "password2": "secret"},
        )
        self.assertRedirects(resp, reverse("registration_disallowed"))

        settings.REGISTRATION_OPEN = old_allowed
Example #14
0
def create(api, request):
    top_id = api.top_create()
    if request.REQUEST.has_key("json"):
        import simplejson as json

        top = json.loads(request.REQUEST["json"])
        mods = []
        mods.append(
            {
                "type": "topology-rename",
                "element": None,
                "subelement": None,
                "properties": {"name": top["attrs"]["name"]},
            }
        )
        for devname, dev in top["devices"].iteritems():
            mods.append({"type": "device-create", "element": None, "subelement": None, "properties": dev["attrs"]})
            for iface in dev["interfaces"].values():
                mods.append(
                    {"type": "interface-create", "element": devname, "subelement": None, "properties": iface["attrs"]}
                )
        for conname, con in top["connectors"].iteritems():
            mods.append({"type": "connector-create", "element": None, "subelement": None, "properties": con["attrs"]})
            for c in con["connections"].values():
                mods.append(
                    {"type": "connection-create", "element": conname, "subelement": None, "properties": c["attrs"]}
                )
        api.top_modify(top_id, mods, True)
        return HttpResponseRedirect(reverse("tomato.top.show", kwargs={"top_id": top_id}))
    else:
        return HttpResponseRedirect(reverse("tomato.top.edit", kwargs={"top_id": top_id}))
Example #15
0
def list_details(request, list_id):
    if not request.user.is_staff:
        return HttpResponse("Unauthorized")

    list = QuestionList.objects.get(pk=list_id)
    questions_list = QuestionListOrder.objects.filter(question_list=list).order_by("order")

    edit_form = QuestionListForm(instance=list)
    add_question_form = QuestionListAddForm(list)
    invalid_count = False
    if request.method == "POST":

        if request.POST.has_key("edit_list"):
            edit_form = QuestionListForm(request.POST, instance=list)
            if edit_form.is_valid():
                list = edit_form.save()
                return HttpResponseRedirect(reverse("quanda_list_details", args=[list.id]))

        elif request.POST.has_key("reorder"):
            for value in request.POST.values():
                if value != "0" and request.POST.values().count(value) > 1:
                    invalid_count = True
                    break
            if not invalid_count:
                for k, v in request.POST.items():
                    if k != "reorder":
                        list_item = questions_list.get(question__id=k)
                        if v == "0":
                            list_item.delete()
                        else:
                            list_item.order = v
                            list_item.save()
                return HttpResponseRedirect(reverse("quanda_list_details", args=[list.id]))

        elif request.POST.has_key("add_question"):
            add_question_form = QuestionListAddForm(list, request.POST)
            if add_question_form.is_valid():
                question = get_object_or_404(Question, pk=add_question_form.cleaned_data["question"])
                list_questions = QuestionListOrder.objects.filter(question_list=list)
                if not list_questions:
                    new_item = QuestionListOrder(question_list=list, question=question, order=1)
                    new_item.save()
                    return HttpResponseRedirect(reverse("quanda_list_details", args=[list.id]))
                else:
                    order_number = list_questions.order_by("-order")[0].order + 1
                    new_item = QuestionListOrder(question_list=list, question=question, order=order_number)
                    new_item.save()
                    return HttpResponseRedirect(reverse("quanda_list_details", args=[list.id]))

    return render_to_response(
        "quanda/list_details.html",
        {
            "list": list,
            "edit_form": edit_form,
            "add_question_form": add_question_form,
            "questions_list": questions_list,
            "invalid_count": invalid_count,
        },
        context_instance=RequestContext(request),
    )
Example #16
0
def import_action(request, workflow, parent_action_id):
    available_actions = OozieDesign.objects.all()

    if request.method == "POST":
        form = ImportJobsubDesignForm(
            data=request.POST, choices=[(action.id, action.name) for action in available_actions]
        )
        if form.is_valid():
            try:
                design = OozieDesign.objects.get(id=form.cleaned_data["action_id"])
                action = convert_jobsub_design(design)
                action.workflow = workflow
                action.save()

                workflow.add_action(action, parent_action_id)
            except OozieDesign.DoesNotExist:
                request.error(_("Jobsub design doesn't exist."))
            except (Mapreduce.DoesNotExist, Streaming.DoesNotExist, Java.DoesNotExist):
                request.error(_("Could not convert jobsub design"))
            except:
                request.error(_("Could not convert jobsub design or add action to workflow"))

        return redirect(reverse("oozie:edit_workflow", kwargs={"workflow": action.workflow.id}))

    return render(
        "editor/import_workflow_action.mako",
        request,
        {
            "workflow": workflow,
            "available_actions": available_actions,
            "form_url": reverse(
                "oozie:import_action", kwargs={"workflow": workflow.id, "parent_action_id": parent_action_id}
            ),
        },
    )
Example #17
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)
Example #18
0
def submit_coordinator(request, coordinator):
    ParametersFormSet = formset_factory(ParameterForm, extra=0)

    if request.method == "POST":
        params_form = ParametersFormSet(request.POST)

        if params_form.is_valid():
            mapping = dict([(param["name"], param["value"]) for param in params_form.cleaned_data])
            job_id = _submit_coordinator(request, coordinator, mapping)

            request.info(_("Coordinator submitted."))
            return redirect(reverse("oozie:list_oozie_coordinator", kwargs={"job_id": job_id}))
        else:
            request.error(_("Invalid submission form: %s" % params_form.errors))
    else:
        parameters = coordinator.find_all_parameters()
        initial_params = ParameterForm.get_initial_params(
            dict([(param["name"], param["value"]) for param in parameters])
        )
        params_form = ParametersFormSet(initial=initial_params)

    popup = render(
        "editor/submit_job_popup.mako",
        request,
        {
            "params_form": params_form,
            "action": reverse("oozie:submit_coordinator", kwargs={"coordinator": coordinator.id}),
        },
        force_template=True,
    ).content
    return HttpResponse(json.dumps(popup), mimetype="application/json")
Example #19
0
    def test_user_info(self):
        user = User(username="admin", email="admin@example.com")
        user.set_password("admin")
        user.save()

        self.assertRaises(Exception, self.client.get, reverse("sentry-raise-exc"))

        self.assertEquals(len(self.raven.events), 1)
        event = self.raven.events.pop(0)
        self.assertTrue("user" in event["data"]["__sentry__"])
        user_info = event["data"]["__sentry__"]["user"]
        self.assertTrue("is_authenticated" in user_info)
        self.assertFalse(user_info["is_authenticated"])
        self.assertFalse("username" in user_info)
        self.assertFalse("email" in user_info)

        self.assertTrue(self.client.login(username="admin", password="admin"))

        self.assertRaises(Exception, self.client.get, reverse("sentry-raise-exc"))

        self.assertEquals(len(self.raven.events), 1)
        event = self.raven.events.pop(0)
        self.assertTrue("user" in event["data"]["__sentry__"])
        user_info = event["data"]["__sentry__"]["user"]
        self.assertTrue("is_authenticated" in user_info)
        self.assertTrue(user_info["is_authenticated"])
        self.assertTrue("username" in user_info)
        self.assertEquals(user_info["username"], "admin")
        self.assertTrue("email" in user_info)
        self.assertEquals(user_info["email"], "admin@example.com")
Example #20
0
    def test_get_page_for_apphook(self):

        with SettingsOverride(ROOT_URLCONF="cms.test_utils.project.second_urls_for_apphook_tests"):
            en_title, de_title = self.create_base_structure(APP_NAME, ["en", "de"])
            with force_language("en"):
                path = reverse("sample-settings")
            request = self.get_request(path)
            request.LANGUAGE_CODE = "en"

            attached_to_page = applications_page_check(request, path=path[1:])  # strip leading slash
            self.assertEqual(attached_to_page.pk, en_title.page.pk)

            response = self.client.get(path)
            self.assertEqual(response.status_code, 200)

            self.assertTemplateUsed(response, "sampleapp/home.html")
            self.assertContains(response, en_title.title)
            with force_language("de"):
                path = reverse("sample-settings")
            request = self.get_request(path)
            request.LANGUAGE_CODE = "de"
            attached_to_page = applications_page_check(
                request, path=path[1:]
            )  # strip leading slash and language prefix
            self.assertEqual(attached_to_page.pk, de_title.page.pk)

            response = self.client.get(path)
            self.assertEqual(response.status_code, 200)
            self.assertTemplateUsed(response, "sampleapp/home.html")
            self.assertContains(response, de_title.title)

            apphook_pool.clear()
Example #21
0
 def test_following_members(self):
     """Test the following and unfollowing members using the
        generic follow method.
     """
     p = self.jacob.get_profile()
     loggedin = self.client.login(username="jacob", password="JKM")
     self.assertTrue(loggedin)
     response = self.client.post(
         reverse("user-follow-unfollow"), {"id": self.david.id, "what": "member", "verb": "follow"}
     )
     self.assertEquals(response.status_code, 200)
     self.assertEquals(p.members[0], self.david)
     response = self.client.post(
         reverse("user-follow-unfollow"), {"id": self.yosef.id, "what": "member", "verb": "follow"}
     )
     self.assertEquals(len(p.members), 2)
     response = self.client.post(
         reverse("user-follow-unfollow"), {"id": self.david.id, "what": "member", "verb": "unfollow"}
     )
     self.assertEquals(len(p.members), 1)
     self.assertEquals(p.members[0], self.yosef)
     response = self.client.post(
         reverse("user-follow-unfollow"), {"id": self.yosef.id, "what": "member", "verb": "unfollow"}
     )
     self.assertEquals(len(p.members), 0)
     self.client.logout()
Example #22
0
    def test_get_page_for_apphook_on_preview_or_edit(self):
        with SettingsOverride(ROOT_URLCONF="cms.test_utils.project.urls_3"):
            if get_user_model().USERNAME_FIELD == "email":
                superuser = get_user_model().objects.create_superuser("admin", "admin@admin.com", "admin@admin.com")
            else:
                superuser = get_user_model().objects.create_superuser("admin", "admin@admin.com", "admin")

            page = create_page(
                "home", "nav_playground.html", "en", created_by=superuser, published=True, apphook=APP_NAME
            )
            create_title("de", page.get_title(), page)
            page.publish("en")
            page.publish("de")
            page.save()
            public_page = page.get_public_object()

            with self.login_user_context(superuser):
                with force_language("en"):
                    path = reverse("sample-settings")
                    request = self.get_request(path + "?%s" % get_cms_setting("CMS_TOOLBAR_URL__EDIT_ON"))
                    request.LANGUAGE_CODE = "en"
                    attached_to_page = applications_page_check(request, path=path[1:])  # strip leading slash
                    response = self.client.get(path + "?edit")
                    self.assertContains(response, "?redirect=")
                with force_language("de"):
                    path = reverse("sample-settings")
                    request = self.get_request(path + "?%s" % get_cms_setting("CMS_TOOLBAR_URL__EDIT_ON"))
                    request.LANGUAGE_CODE = "de"
                    attached_to_page = applications_page_check(request, path=path[1:])  # strip leading slash
                    self.assertEqual(attached_to_page.pk, public_page.pk)
    def test_switch_tenants(self):
        NEW_TENANT = "newTenant"
        TOKEN_ID = 1

        self.setActiveUser(self.TEST_TOKEN, self.TEST_USER, self.TEST_TENANT, False, self.TEST_SERVICE_CATALOG)

        form_data = {
            "method": "LoginWithTenant",
            "password": self.PASSWORD,
            "tenant": NEW_TENANT,
            "username": self.TEST_USER,
        }

        self.mox.StubOutWithMock(api, "token_create")
        aToken = self.mox.CreateMock(api.Token)
        aToken.id = TOKEN_ID
        aToken.serviceCatalog = {}
        api.token_create(IsA(http.HttpRequest), NEW_TENANT, self.TEST_USER, self.PASSWORD).AndReturn(aToken)

        self.mox.StubOutWithMock(api, "token_info")
        tokenInfo = {"user": self.TEST_USER, "tenant": NEW_TENANT, "admin": False}
        api.token_info(IsA(http.HttpRequest), aToken).AndReturn(tokenInfo)

        self.mox.ReplayAll()

        res = self.client.post(reverse("auth_switch", args=[NEW_TENANT]), form_data)

        self.assertRedirectsNoFollow(res, reverse("dash_overview"))
        self.assertEqual(self.client.session["tenant"], NEW_TENANT)

        self.mox.VerifyAll()
Example #24
0
    def test_include_urlconf(self):
        with SettingsOverride(ROOT_URLCONF="cms.test_utils.project.second_urls_for_apphook_tests"):
            self.create_base_structure(APP_NAME, "en")

            path = reverse("extra_second")
            response = self.client.get(path)
            self.assertEqual(response.status_code, 200)
            self.assertTemplateUsed(response, "sampleapp/extra.html")
            self.assertContains(response, "test included urlconf")

            path = reverse("extra_first")
            response = self.client.get(path)
            self.assertEqual(response.status_code, 200)
            self.assertTemplateUsed(response, "sampleapp/extra.html")
            self.assertContains(response, "test urlconf")
            with force_language("de"):
                path = reverse("extra_first")
            response = self.client.get(path)
            self.assertEqual(response.status_code, 200)
            self.assertTemplateUsed(response, "sampleapp/extra.html")
            self.assertContains(response, "test urlconf")
            with force_language("de"):
                path = reverse("extra_second")
            response = self.client.get(path)
            self.assertEqual(response.status_code, 200)
            self.assertTemplateUsed(response, "sampleapp/extra.html")
            self.assertContains(response, "test included urlconf")

            apphook_pool.clear()
Example #25
0
 def __init__(self, *args, **kwargs):
     super(SupplierForm, self).__init__(*args, **kwargs)
     self.helper.layout = Layout(
         Div(
             Column(
                 FieldWithButtons(
                     "contact",
                     StrictButton(
                         "<a href='%s' target='_blank'><span class='glyphicon glyphicon-plus'></span></a>"
                         % reverse("contact_add")
                     ),
                 ),
                 css_class="col-md-6",
             ),
             Column(
                 FieldWithButtons(
                     "company",
                     StrictButton(
                         "<a href='%s' target='_blank'><span class='glyphicon glyphicon-plus'></span></a>"
                         % reverse("crm.views.company")
                     ),
                 ),
                 css_class="col-md-6",
             ),
             css_class="row",
         ),
         self.submit,
     )
Example #26
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 #27
0
    def test_whatchanged_pagination(self):
        self.page.raw = "line\n"
        Git().commit(self.page, message=u"one")
        self.page.raw += "line 2\n"
        Git().commit(self.page, message=u"two")
        self.page.raw += "line 3\n"
        Git().commit(self.page, message=u"three")
        with patch("waliki.git.views.settings") as s_mock:
            type(s_mock).WALIKI_PAGINATE_BY = PropertyMock(return_value=2)
            response1 = self.client.get(reverse("waliki_whatchanged"))
            response2 = self.client.get(reverse("waliki_whatchanged", args=("2",)))

        # first page has no previous page
        self.assertIsNone(response1.context[0]["prev"])
        self.assertEqual(response1.context[0]["next"], 2)
        self.assertIsNone(response2.context[0]["next"])
        self.assertEqual(response2.context[0]["prev"], 1)

        changes1 = response1.context[0]["changes"]
        changes2 = response2.context[0]["changes"]
        self.assertEqual(len(changes1), 2)
        self.assertEqual(len(changes2), 1)
        self.assertEqual(changes1[0]["message"], "three")
        self.assertEqual(changes1[1]["message"], "two")
        self.assertEqual(changes2[0]["message"], "one")
    def get_form(self, request):
        """
        Configures a paypal form and returns. Allows this code to be reused
        in other views.
        """
        order = self.shop.get_order(request)
        url_scheme = "https" if request.is_secure() else "http"
        # get_current_site requires Django 1.3 - backward compatibility?
        url_domain = get_current_site(request).domain
        paypal_dict = {
            "business": settings.PAYPAL_RECEIVER_EMAIL,
            "currency_code": settings.PAYPAL_CURRENCY_CODE,
            "amount": self.shop.get_order_total(order),
            "item_name": self.shop.get_order_short_name(order),
            "invoice": self.shop.get_order_unique_id(order),
            "notify_url": "%s://%s%s" % (url_scheme, url_domain, reverse("paypal-ipn")),  # defined by django-paypal
            "return_url": "%s://%s%s"
            % (url_scheme, url_domain, reverse("paypal_success")),  # That's this classe's view
            "cancel_return": "%s://%s%s" % (url_scheme, url_domain, self.shop.get_cancel_url()),  # A generic one
        }
        if hasattr(settings, "PAYPAL_LC"):
            paypal_dict["lc"] = settings.PAYPAL_LC

        # Create the instance.
        form = PayPalPaymentsForm(initial=paypal_dict)
        return form
Example #29
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 #30
0
    def inner(request, *args, **kw):
        user = request.user
        course = request.common_page_data["course"]

        if user.is_authenticated() and not is_member_of_course(course, user):
            messages.add_message(
                request, messages.ERROR, "You must be a member of the course to view the content you chose."
            )
            return HttpResponseRedirect(
                reverse(
                    "courses.views.main",
                    args=(request.common_page_data["course_prefix"], request.common_page_data["course_suffix"]),
                )
            )

        if not user.is_authenticated():
            messages.add_message(request, messages.ERROR, "You must be logged-in to view the content you chose.")

            return HttpResponseRedirect(
                reverse(
                    "courses.views.main",
                    args=(request.common_page_data["course_prefix"], request.common_page_data["course_suffix"]),
                )
            )

        return view(request, *args, **kw)