Python django.urls() Examples

The following are 15 code examples for showing how to use django.urls(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django , or try the search function .

Example 1
Project: openapi-core   Author: p1c2u   File: test_django.py    License: 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 2
Project: django-generic-scaffold   Author: spapas   File: views.py    License: MIT License 6 votes vote down vote up
def get_url_patterns(self, ):
        prefix = hasattr(self, 'prefix') and self.prefix or ''

        url_patterns = [
            url(r'^'+prefix+'$', self.perms['list'](self.get_list_class_view().as_view()), name=self.list_url_name, ),
            url(r'^'+prefix+'create/$', self.perms['create'](self.get_create_class_view().as_view()), name=self.create_url_name ),
            url(r'^'+prefix+'detail/(?P<pk>\d+)$', self.perms['detail'](self.get_detail_class_view().as_view()), name=self.detail_url_name ),
            url(r'^'+prefix+'update/(?P<pk>\d+)$', self.perms['update'](self.get_update_class_view().as_view()), name=self.update_url_name ),
            url(r'^'+prefix+'delete/(?P<pk>\d+)$', self.perms['delete'](self.get_delete_class_view().as_view()), name=self.delete_url_name ),
        ]

        if django.VERSION >= (1, 8, 0):
            return url_patterns
        else:
            from django.conf.urls import patterns
            return patterns('', *url_patterns) 
Example 3
Project: sentry-python   Author: getsentry   File: test_transactions.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_legacy_resolver_newstyle_django20_urlconf():
    from django.urls import path

    url_conf = (path("api/v2/<int:project_id>/store/", lambda x: ""),)
    resolver = RavenResolver()
    result = resolver.resolve("/api/v2/1234/store/", url_conf)
    assert result == "/api/v2/{project_id}/store/" 
Example 4
Project: django-seo   Author: whyflyru   File: tests.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_useful_error_messages(self):
        """ Tests that the system gracefully handles a developer error
            (eg exception in get_absolute_url).
        """
        if django.VERSION < (2, 0):
            from django.core.urlresolvers import NoReverseMatch
        else:
            from django.urls import NoReverseMatch
        with self.assertRaises(NoReverseMatch):
            self.page.type = "a type with spaces!"  # this causes get_absolute_url() to fail
            self.page.save()
            self.fail("No exception raised on developer error.") 
Example 5
Project: openapi-core   Author: p1c2u   File: test_django.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def django_settings(self):
        import django
        from django.conf import settings
        from django.contrib import admin
        from django.urls import path

        if settings.configured:
            return

        settings.configure(
            ALLOWED_HOSTS=[
                'testserver',
            ],
            INSTALLED_APPS=[
                'django.contrib.admin',
                'django.contrib.auth',
                'django.contrib.contenttypes',
                'django.contrib.messages',
                'django.contrib.sessions',
            ],
            MIDDLEWARE=[
                'django.contrib.sessions.middleware.SessionMiddleware',
                'django.contrib.auth.middleware.AuthenticationMiddleware',
                'django.contrib.messages.middleware.MessageMiddleware',
            ]
        )
        django.setup()
        settings.ROOT_URLCONF = (
            path('admin/', admin.site.urls),
        ) 
Example 6
Project: openapi-core   Author: p1c2u   File: test_django.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_url_rule(self, request_factory):
        from django.urls import resolve
        request = request_factory.get('/admin/auth/group/1/')
        request.resolver_match = resolve('/admin/auth/group/1/')

        openapi_request = DjangoOpenAPIRequest(request)

        path = {
            'object_id': '1',
        }
        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 + "/admin/auth/group/{object_id}/"
        assert openapi_request.body == request.body
        assert openapi_request.mimetype == request.content_type 
Example 7
Project: openapi-core   Author: p1c2u   File: test_django.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_response_validator_path_pattern(
            self, django_spec, request_factory, response_factory):
        from django.urls import resolve
        validator = ResponseValidator(django_spec)
        request = request_factory.get('/admin/auth/group/1/')
        request.resolver_match = resolve('/admin/auth/group/1/')
        openapi_request = DjangoOpenAPIRequest(request)
        response = response_factory(b('Some item'))
        openapi_response = DjangoOpenAPIResponse(response)
        result = validator.validate(openapi_request, openapi_response)
        assert not result.errors 
Example 8
Project: openapi-core   Author: p1c2u   File: test_django.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_request_validator_path_pattern(
            self, django_spec, request_factory):
        from django.urls import resolve
        validator = RequestValidator(django_spec)
        request = request_factory.get('/admin/auth/group/1/')
        request.resolver_match = resolve('/admin/auth/group/1/')
        openapi_request = DjangoOpenAPIRequest(request)
        result = validator.validate(openapi_request)
        assert not result.errors 
Example 9
Project: django-admin-interface   Author: fabiocaccamo   File: admin_interface_tags.py    License: MIT License 5 votes vote down vote up
def get_admin_interface_languages(context):
    if not settings.USE_I18N:
        # i18n disabled
        return None
    if len(settings.LANGUAGES) < 2:
        # less than 2 languages
        return None
    try:
        set_language_url = reverse('set_language')
    except NoReverseMatch:
        # ImproperlyConfigured - must include i18n urls:
        # urlpatterns += [url(r'^i18n/', include('django.conf.urls.i18n')),]
        return None
    request = context.get('request', None)
    if not request:
        return None
    full_path = request.get_full_path()
    admin_nolang_url = re.sub(r'^\/([\w]{2})([\-\_]{1}[\w]{2})?\/', '/', full_path)
    if admin_nolang_url == full_path:
        # ImproperlyConfigured - must include admin urls using i18n_patterns:
        # from django.conf.urls.i18n import i18n_patterns
        # urlpatterns += i18n_patterns(url(r'^admin/', admin.site.urls))
        return None
    langs_data = []
    default_lang_code = settings.LANGUAGE_CODE
    current_lang_code = translation.get_language() or default_lang_code
    for language in settings.LANGUAGES:
        lang_code = language[0].lower()
        lang_name = language[1].title()
        lang_data = {
            'code': lang_code,
            'name': lang_name,
            'default': lang_code == default_lang_code,
            'active': lang_code == current_lang_code,
            'activation_url': '{}?next=/{}{}'.format(
                set_language_url, lang_code, admin_nolang_url)
        }
        langs_data.append(lang_data)
    return langs_data 
Example 10
Project: Dailyfresh-B2C   Author: BeanWei   File: compat.py    License: Apache License 2.0 5 votes vote down vote up
def is_route_pattern(urlpattern):
    if hasattr(urlpattern, 'pattern'):
        # Django 2.0
        from django.urls.resolvers import RoutePattern
        return isinstance(urlpattern.pattern, RoutePattern)
    else:
        # Django < 2.0
        return False 
Example 11
Project: Dailyfresh-B2C   Author: BeanWei   File: compat.py    License: Apache License 2.0 5 votes vote down vote up
def make_url_resolver(regex, urlpatterns):
    try:
        # Django 2.0
        from django.urls.resolvers import RegexPattern
        return URLResolver(RegexPattern(regex), urlpatterns)

    except ImportError:
        # Django < 2.0
        return URLResolver(regex, urlpatterns) 
Example 12
def test_bad_re_catastrophic_usage_django(self):
        python_node = self.get_ast_node(
            """
            import django

            django.core.validators.RegexValidator('(a+)+b')
            django.urls.re_path('(a+)+b')
            """
        )

        linter = dlint.linters.BadReCatastrophicUseLinter()
        linter.visit(python_node)

        result = linter.get_results()
        expected = [
            dlint.linters.base.Flake8Result(
                lineno=4,
                col_offset=0,
                message=dlint.linters.BadReCatastrophicUseLinter._error_tmpl
            ),
            dlint.linters.base.Flake8Result(
                lineno=5,
                col_offset=0,
                message=dlint.linters.BadReCatastrophicUseLinter._error_tmpl
            ),
        ]

        assert result == expected 
Example 13
def test_bad_re_catastrophic_usage_from_import_django(self):
        python_node = self.get_ast_node(
            """
            from django.core.validators import RegexValidator
            from django.urls import re_path

            RegexValidator('(a+)+b')
            re_path('(a+)+b')
            """
        )

        linter = dlint.linters.BadReCatastrophicUseLinter()
        linter.visit(python_node)

        result = linter.get_results()
        expected = [
            dlint.linters.base.Flake8Result(
                lineno=5,
                col_offset=0,
                message=dlint.linters.BadReCatastrophicUseLinter._error_tmpl
            ),
            dlint.linters.base.Flake8Result(
                lineno=6,
                col_offset=0,
                message=dlint.linters.BadReCatastrophicUseLinter._error_tmpl
            ),
        ]

        assert result == expected 
Example 14
Project: django-bananas   Author: 5monkeys   File: __init__.py    License: MIT License 5 votes vote down vote up
def urlpatterns(*urls):
    if django.VERSION < (1, 10):
        from django.conf.urls import patterns

        return patterns("", *urls)

    return list(urls) 
Example 15
Project: scout_apm_python   Author: scoutapp   File: django_app.py    License: MIT License 4 votes vote down vote up
def urlpatterns():
    """
    URL's as a lazy object because they touch admin.site.urls and that isn't
    ready until django.setup() has been called
    """
    if django.VERSION >= (2, 0):
        from django.urls import include, path

        patterns = [
            path("", home),
            path("hello/", hello),
            path("crash/", crash),
            path("return-error/", return_error),
            path("cbv/", CbvView.as_view()),
            path("sql/", sql),
            path("sql-kwargs/", sql_kwargs),
            path("sql-type-errors/", sql_type_errors),
            path("template/", template),
            path("template-response/", template_response),
            path("admin/", admin.site.urls),
            path("drf-router/", include(drf_router.urls)),
        ]
        if tastypie_api:
            patterns.append(path("tastypie-api/", include(tastypie_api.urls)))
        return patterns

    else:
        from django.conf.urls import include, url

        patterns = [
            url(r"^$", home),
            url(r"^hello/$", hello),
            url(r"^crash/$", crash),
            url(r"^return-error/$", return_error),
            url(r"^cbv/$", CbvView.as_view()),
            url(r"^sql/$", sql),
            url(r"^sql-kwargs/$", sql_kwargs),
            url(r"^sql-type-errors/$", sql_type_errors),
            url(r"^template/$", template),
            url(r"^template-response/$", template_response),
            url(r"^admin/", admin.site.urls),
            url(r"^drf-router/", include(drf_router.urls)),
        ]
        if tastypie_api:
            patterns.append(url(r"^tastypie-api/", include(tastypie_api.urls)))
        return patterns