Python django.urls.resolve() Examples

The following are 30 code examples of django.urls.resolve(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.urls , or try the search function .
Example #1
Source File: suit_menu.py    From django-ra-erp with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_admin_site(current_app):
    """
    Method tries to get actual admin.site class, if any custom admin sites
    were used. Couldn't find any other references to actual class other than
    in func_closer dict in index() func returned by resolver.
    """
    try:
        resolver_match = resolve(reverse('%s:index' % current_app))
        # Django 1.9 exposes AdminSite instance directly on view function
        if hasattr(resolver_match.func, 'admin_site'):
            return resolver_match.func.admin_site

        for func_closure in resolver_match.func.__closure__:
            if isinstance(func_closure.cell_contents, AdminSite):
                return func_closure.cell_contents
    except:
        pass
    return admin.site 
Example #2
Source File: middleware.py    From django-modeladmin-reorder with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def process_template_response(self, request, response):
        try:
            url = resolve(request.path_info)
        except Resolver404:
            return response
        if not url.app_name == 'admin' and \
                url.url_name not in ['index', 'app_list']:
            # current view is not a django admin index
            # or app_list view, bail out!
            return response

        try:
            app_list = response.context_data['app_list']
        except KeyError:
            # there is no app_list! nothing to reorder
            return response

        self.init_config(request, app_list)
        ordered_app_list = self.get_app_list()
        response.context_data['app_list'] = ordered_app_list
        return response 
Example #3
Source File: transform.py    From ontask_b with MIT License 6 votes vote down vote up
def transform_model(
    request: http.HttpRequest,
    workflow: Optional[models.Workflow] = None,
) -> http.HttpResponse:
    """Show the table of models.

    :param request: HTTP Request
    :param workflow: Object to apply the models.
    :return:
    """
    url_name = resolve(request.path).url_name
    is_model = url_name == 'model'

    table_err = None
    if request.user.is_superuser:
        table_err = models.Plugin.objects.filter(is_model=None)

    return render(
        request,
        'dataops/transform_model.html',
        {
            'table': services.create_model_table(request, workflow, is_model),
            'is_model': is_model,
            'table_err': table_err}) 
Example #4
Source File: test_django.py    From openapi-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_simple(self, request_factory):
        from django.urls import resolve
        request = request_factory.get('/admin/')
        request.resolver_match = resolve('/admin/')

        openapi_request = DjangoOpenAPIRequest(request)

        path = {}
        query = {}
        headers = {
            'Cookie': '',
        }
        cookies = {}
        assert openapi_request.parameters == RequestParameters(
            path=path,
            query=query,
            header=headers,
            cookie=cookies,
        )
        assert openapi_request.method == request.method.lower()
        assert openapi_request.full_url_pattern == \
            request._current_scheme_host + request.path
        assert openapi_request.body == request.body
        assert openapi_request.mimetype == request.content_type 
Example #5
Source File: middleware.py    From Spirit with MIT License 6 votes vote down vote up
def process_request(self, request):
        if not settings.ST_PRIVATE_FORUM:
            return

        if request.user.is_authenticated:
            return

        resolver_match = resolve(request.path)

        if not resolver_match.namespaces:
            return

        if resolver_match.namespaces[0] != 'spirit':
            return

        full_namespace = ':'.join(resolver_match.namespaces)

        if full_namespace == 'spirit:user:auth':
            return

        return redirect_to_login(
            next=request.get_full_path(),
            login_url=settings.LOGIN_URL) 
Example #6
Source File: test_user_management.py    From desec-stack with MIT License 6 votes vote down vote up
def test_action_code_confusion(self):
        # Obtain change password code
        self.assertResetPasswordSuccessResponse(self.reset_password(self.email))
        reset_password_link = self.assertResetPasswordEmail(self.email)
        path = urlparse(reset_password_link).path
        reset_password_code = resolve(path).kwargs.get('code')

        # Obtain deletion code
        self.assertDeleteAccountSuccessResponse(self.delete_account(self.email, self.password))
        delete_link = self.assertDeleteAccountEmail(self.email)
        path = urlparse(delete_link).path
        deletion_code = resolve(path).kwargs.get('code')

        # Swap codes
        self.assertNotEqual(reset_password_code, deletion_code)
        delete_link = delete_link.replace(deletion_code, reset_password_code)
        reset_password_link = reset_password_link.replace(reset_password_code, deletion_code)

        # Make sure links don't work
        self.assertVerificationFailureInvalidCodeResponse(self.client.verify(delete_link))
        self.assertVerificationFailureInvalidCodeResponse(self.client.verify(reset_password_link,
                                                                             data={'new_password': 'dummy'})) 
Example #7
Source File: middleware.py    From mrs with GNU Affero General Public License v3.0 6 votes vote down vote up
def authorize(self, request):
        if not settings.MAINTENANCE_ENABLE:
            # Not to use this env
            return True

        current_url = resolve(request.path_info).url_name

        if current_url in [
            'home', 'login', 'logout', 'maintenance', 'list',
            'detail', 'bill_download', 'pmt_download'
        ]:
            if request.user.is_authenticated:
                if request.user.is_superuser:
                    return True
                else:
                    #  Logout all non superusers (local admins)
                    logout(request)
                    return True
            else:
                return True
        else:
            return False 
Example #8
Source File: atom.py    From oh-my-rss with MIT License 6 votes vote down vote up
def parse_self_atom(feed_url):
    """
    解析本站提供的 RSS 源
    :param feed_url:
    :return: 解析结果,成功字典;失败 None
    """

    feed_path = urllib.parse.urlparse(feed_url).path

    try:
        name = resolve(feed_path).kwargs.get('name')
    except:
        name = None

    if name:
        try:
            Site.objects.get(name=name, status='active')
            return {"name": name}
        except:
            logger.warning(f'订阅源不存在:`{feed_url}')

    return None 
Example #9
Source File: adminlte_menu.py    From django-adminlte-ui with MIT License 6 votes vote down vote up
def get_admin_site(current_app):
    """
    Method tries to get actual admin.site class, if any custom admin sites
    were used. Couldn't find any other references to actual class other than
    in func_closer dict in index() func returned by resolver.
    """
    try:
        resolver_match = resolve(reverse('%s:index' % current_app))
        # Django 1.9 exposes AdminSite instance directly on view function
        if hasattr(resolver_match.func, 'admin_site'):
            return resolver_match.func.admin_site

        for func_closure in resolver_match.func.__closure__:
            if isinstance(func_closure.cell_contents, AdminSite):
                return func_closure.cell_contents
    except:
        pass
    from django.contrib import admin
    return admin.site 
Example #10
Source File: suit_menu.py    From django-ra-erp with GNU Affero General Public License v3.0 6 votes vote down vote up
def process_url(self, url, app=None):
        """
        Try to guess if it is absolute url or named
        """
        if url is None:
            return ''

        if not url or '/' in url:
            return url

        # Model link, ex: 'auth.user'
        if '.' in url:
            url_parts = url.split('.')
            model = self.make_model_from_native(url_parts[1], url_parts[0])
            if model:
                if app:
                    app['model'] = model
                return model['url']

        # Try to resolve as named url, ex: 'admin:index'
        try:
            return reverse(url)
        except:
            return url 
Example #11
Source File: test_urls.py    From django-saml2-pro-auth with MIT License 5 votes vote down vote up
def test_url_resolving_with_start_forward_slash(self):
        self.assertEqual(resolve('/sso/saml/').view_name, 'saml2_auth')
        self.assertEqual(resolve('/sso/saml/metadata/').view_name, 'metadata') 
Example #12
Source File: test_urls.py    From eventoL with GNU General Public License v3.0 5 votes vote down vote up
def test_relationship_url_name_with_view_name(url_name, view_name, required_params, event_data1):
    params = get_reverse_params(required_params, **event_data1)
    path = reverse(url_name, kwargs=params)
    response = resolve(path)
    assert full_view_name(response) == view_name 
Example #13
Source File: mixins.py    From adhocracy4 with GNU Affero General Public License v3.0 5 votes vote down vote up
def url_name(self):
        return resolve(self.request.path_info).url_name 
Example #14
Source File: test_urls.py    From arxiv-vanity with Apache License 2.0 5 votes vote down vote up
def test_urls(self):
        resolver = resolve("/papers/1703.07815/")
        self.assertEqual(resolver.view_name, "paper_detail")

        resolver = resolve("/pdf/1703.07815/")
        self.assertEqual(resolver.view_name, "django.views.generic.base.RedirectView")

        resolver = resolve("/papers/1703.07815/render-state/")
        self.assertEqual(resolver.view_name, "paper_render_state")

        resolver = resolve("/papers/astro-ph/0601001/")
        self.assertEqual(resolver.view_name, "paper_detail")

        resolver = resolve("/papers/astro-ph/0601001/render-state/")
        self.assertEqual(resolver.view_name, "paper_render_state") 
Example #15
Source File: test_urls.py    From django-saml2-pro-auth with MIT License 5 votes vote down vote up
def test_url_resolving_with_end_forward_slash(self):
        self.assertEqual(resolve('/sso/saml/').view_name, 'saml2_auth')
        self.assertEqual(resolve('/sso/saml/metadata/').view_name, 'metadata') 
Example #16
Source File: test_urls.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_detail_resolve(self):
        """/users/testuser/ should resolve to users:detail."""
        self.assertEqual(resolve('/users/testuser/').view_name, 'users:detail') 
Example #17
Source File: test_urls.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_redirect_resolve(self):
        """/users/~redirect/ should resolve to users:redirect."""
        self.assertEqual(
            resolve('/users/~redirect/').view_name,
            'users:redirect'
        ) 
Example #18
Source File: test_urls.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_list_resolve(self):
        """/users/ should resolve to users:list."""
        self.assertEqual(resolve('/users/').view_name, 'users:list') 
Example #19
Source File: forms.py    From zing with GNU General Public License v3.0 5 votes vote down vote up
def clean(self):
        if "checks" in self.errors:
            del self.errors["checks"]
            self.cleaned_data["checks"] = None
        if "user" in self.errors:
            del self.errors["user"]
            self.cleaned_data["user"] = self.request_user
        if self.errors:
            return
        pootle_path = self.cleaned_data.get("path")
        path_keys = ["project_code", "language_code", "dir_path", "filename"]
        try:
            path_kwargs = {
                k: v for k, v in resolve(pootle_path).kwargs.items() if k in path_keys
            }
        except Resolver404:
            raise forms.ValidationError("Unrecognised path")
        self.cleaned_data.update(path_kwargs)
        sort_on = "units"
        if "filter" in self.cleaned_data:
            unit_filter = self.cleaned_data["filter"]
            if unit_filter in ("suggestions", "user-suggestions"):
                sort_on = "suggestions"
            elif unit_filter in ("user-submissions",):
                sort_on = "submissions"
        sort_by_param = self.cleaned_data["sort"]
        self.cleaned_data["sort_by"] = ALLOWED_SORTS[sort_on].get(sort_by_param)
        self.cleaned_data["sort_on"] = sort_on 
Example #20
Source File: middleware.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def __call__(self, request):
        try:
            callback, args, kwargs = resolve(request.path_info, getattr(request, 'urlconf', None))
        except Resolver404:
            callback, args, kwargs = None, None, None

        if getattr(callback, 'short_circuit_middleware', False):
            return callback(request, *args, **kwargs)
        return self.get_response(request) 
Example #21
Source File: views.py    From djangocms-spa with MIT License 5 votes vote down vote up
def get_translated_urls(self):
        request_language = self.request.LANGUAGE_CODE
        if self.url_name:
            url_name = self.url_name
        else:
            url_name = resolve(self.request.path).url_name

        language_links = {}
        for language_code, language in settings.LANGUAGES:
            if language_code != request_language:
                activate(language_code)
                with suppress(NoReverseMatch):
                    language_links[language_code] = reverse(url_name, args=self.args, kwargs=self.kwargs)
        activate(request_language)
        return language_links 
Example #22
Source File: context_processors.py    From byro with Apache License 2.0 5 votes vote down vote up
def byro_information(request):
    ctx = {
        "config": Configuration.get_solo(),
        "pending_mails": EMail.objects.filter(sent__isnull=True).count(),
        "pending_transactions": Transaction.objects.unbalanced_transactions().count(),
        "log_end": LogEntry.objects.get_chain_end(),
        "effective_date_format": formats.get_format(
            "SHORT_DATE_FORMAT", lang=translation.get_language()
        ),
    }

    ctx["effective_date_format_js"] = (
        ctx["effective_date_format"]
        .replace("d", "dd")
        .replace("m", "mm")
        .replace("Y", "yyyy")
    )

    try:
        ctx["url_name"] = resolve(request.path_info).url_name
    except Http404:
        ctx["url_name"] = ""

    if settings.DEBUG:
        ctx["development_warning"] = True

    ctx["byro_version"] = get_version()

    return ctx 
Example #23
Source File: middleware.py    From byro with Apache License 2.0 5 votes vote down vote up
def __call__(self, request):
        url = resolve(request.path_info)

        allow = True

        if request.user.is_anonymous and url.url_name not in self.UNAUTHENTICATED_URLS:
            allow = False

        if not allow:
            unauthenticated_urls_matchers = []
            for receiver, response in unauthenticated_urls.send(self):
                unauthenticated_urls_matchers.extend(response)

            for url_matcher in unauthenticated_urls_matchers:
                if callable(url_matcher):
                    if url_matcher(request, url):
                        allow = True
                        break
                else:
                    if url.view_name == url_matcher:
                        allow = True
                        break

        if not allow:
            return redirect(
                reverse("common:login") + "?next={request.path}".format(request=request)
            )
        else:
            return self.get_response(request) 
Example #24
Source File: middleware.py    From byro with Apache License 2.0 5 votes vote down vote up
def __call__(self, request):
        url = resolve(request.path_info)
        if not request.user.is_anonymous and url.url_name not in self.ALLOWED_URLS:
            config = Configuration.get_solo()
            values = ("name", "backoffice_mail", "mail_from")
            if not all(getattr(config, value, None) for value in values):
                return redirect("office:settings.initial")
        return self.get_response(request) 
Example #25
Source File: general_templatetags.py    From freesound-datasets with GNU Affero General Public License v3.0 5 votes vote down vote up
def current_url_equals(context, url_name, **kwargs):
    resolved = False
    try:
        resolved = resolve(context.get('request').path)
    except:
        pass
    matches = resolved and (resolved.url_name == url_name or url_name in resolved.url_name)
    if matches and kwargs:
        for key in kwargs:
            kwarg = kwargs.get(key)
            resolved_kwarg = resolved.kwargs.get(key)
            if not resolved_kwarg or kwarg != resolved_kwarg:
                return False
    return matches 
Example #26
Source File: test_urls.py    From wagtail-cookiecutter-foundation with MIT License 5 votes vote down vote up
def test_update_resolve(self):
        """/users/update/ should resolve to users:update."""
        self.assertEqual(
            resolve('/users/update/').view_name,
            'users:update'
        ) 
Example #27
Source File: test_urls.py    From wagtail-cookiecutter-foundation with MIT License 5 votes vote down vote up
def test_detail_resolve(self):
        """/users/testuser/ should resolve to users:detail."""
        self.assertEqual(resolve('/users/dashboard/').view_name,
                         'users:detail') 
Example #28
Source File: test_urls.py    From wagtail-cookiecutter-foundation with MIT License 5 votes vote down vote up
def test_redirect_resolve(self):
        """/users/redirect/ should resolve to users:redirect."""
        self.assertEqual(
            resolve('/users/redirect/').view_name,
            'users:redirect'
        ) 
Example #29
Source File: test_urls.py    From opentaps_seas with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_detail(user: settings.AUTH_USER_MODEL):
    assert (
        reverse("users:detail", kwargs={"username": user.username})
        == f"/users/{user.username}/"
    )
    assert resolve(f"/users/{user.username}/").view_name == "users:detail" 
Example #30
Source File: test_urls.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_update_resolve(self):
        """/users/~update/ should resolve to users:update."""
        self.assertEqual(
            resolve('/users/~update/').view_name,
            'users:update'
        )