Python django.conf.urls.include() Examples

The following are 30 code examples for showing how to use django.conf.urls.include(). 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.conf.urls , or try the search function .

Example 1
Project: waliki   Author: mgaitan   File: urls.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def waliki_urls():
    base = [url(r'^$', home, name='waliki_home'),
            url(r'^_new$', new, name='waliki_new'),
            url(r'^_get_slug$', get_slug, name='waliki_get_slug'),
            url(r'^_preview$', preview, name='waliki_preview')]

    for pattern in page_urls():
        base.append(url(r'^', include(pattern)))

    base += [url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')/edit$', edit, name='waliki_edit'),
             url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')/delete$',
                 delete, name='waliki_delete'),
             url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')/move$',
                 move, name='waliki_move'),
             url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')/raw$',
                 detail, {'raw': True}, name='waliki_detail_raw'),
             url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')$',
                 detail, name='waliki_detail'),
             ]
    return base 
Example 2
Project: scale   Author: ngageoint   File: rest.py    License: Apache License 2.0 6 votes vote down vote up
def check_update(request, fields):
    """Checks whether the given request includes fields that are not allowed to be updated.

    :param request: The context of an active HTTP request.
    :type request: :class:`rest_framework.request.Request`
    :param fields: A list of field names that are permitted.
    :type fields: [string]
    :returns: True when the request does not include extra fields.
    :rtype: bool

    :raises :class:`util.rest.ReadOnly`: If the request includes unsupported fields to update.
    :raises :class:`exceptions.AssertionError`: If fields in not a list or None.
    """
    fields = fields or []
    assert (isinstance(fields, list))
    extra = filter(lambda x, y=fields: x not in y, request.data.keys())
    if extra:
        raise ReadOnly('Fields do not allow updates: %s' % ', '.join(extra))
    return True 
Example 3
Project: InvenTree   Author: inventree   File: api.py    License: MIT License 6 votes vote down vote up
def get_serializer(self, *args, **kwargs):

        # Do we wish to include extra detail?
        try:
            kwargs['part_detail'] = str2bool(self.request.GET.get('part_detail', None))
        except AttributeError:
            pass

        try:
            kwargs['sub_part_detail'] = str2bool(self.request.GET.get('sub_part_detail', None))
        except AttributeError:
            pass
        
        # Ensure the request context is passed through!
        kwargs['context'] = self.get_serializer_context()
        
        return self.serializer_class(*args, **kwargs) 
Example 4
Project: InvenTree   Author: inventree   File: api.py    License: MIT License 6 votes vote down vote up
def get_serializer(self, *args, **kwargs):

        # Do we wish to include extra detail?
        try:
            kwargs['part_detail'] = str2bool(self.request.query_params.get('part_detail', None))
        except AttributeError:
            pass
        
        try:
            kwargs['supplier_detail'] = str2bool(self.request.query_params.get('supplier_detail', None))
        except AttributeError:
            pass

        try:
            kwargs['manufacturer_detail'] = str2bool(self.request.query_params.get('manufacturer_detail', None))
        except AttributeError:
            pass
        
        kwargs['context'] = self.get_serializer_context()

        return self.serializer_class(*args, **kwargs) 
Example 5
Project: ecommerce   Author: edx   File: apps.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_urls(self):
        urls = [
            url(r'^$', self.index_view.as_view(), name='index'),
            url(r'^catalogue/', include(self.catalogue_app.urls[0])),
            url(r'^reports/', include(self.reports_app.urls[0])),
            url(r'^orders/', include(self.orders_app.urls[0])),
            url(r'^users/', include(self.users_app.urls[0])),
            url(r'^pages/', include(self.pages_app.urls[0])),
            url(r'^partners/', include(self.partners_app.urls[0])),
            url(r'^offers/', include(self.offers_app.urls[0])),
            url(r'^ranges/', include(self.ranges_app.urls[0])),
            url(r'^reviews/', include(self.reviews_app.urls[0])),
            url(r'^vouchers/', include(self.vouchers_app.urls[0])),
            url(r'^comms/', include(self.comms_app.urls[0])),
            url(r'^shipping/', include(self.shipping_app.urls[0])),
            url(r'^refunds/', include(self.refunds_app.urls[0])),
        ]
        urls += self.AUTH_URLS
        return self.post_process_urls(urls) 
Example 6
Project: urljects   Author: Visgean   File: routemap.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def include(self, location, namespace=None, app_name=None):
        """
        Return an object suitable for url_patterns.

        :param location: root URL for all URLs from this router
        :param namespace: passed to url()
        :param app_name: passed to url()
        """
        sorted_entries = sorted(self.routes, key=operator.itemgetter(0),
                                reverse=True)

        arg = [u for _, u in sorted_entries]
        return url(location, urls.include(
            arg=arg,
            namespace=namespace,
            app_name=app_name)) 
Example 7
Project: builder   Author: Polychart   File: urls.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _buildPatternList():
  urls = [
    # Main website
    url(r'^', include(SITE_URLS)) if SITE_URLS else None,

    # Main app
    url(r'^', include(MAIN_URLS)),

    # Polychart.js website
    url(r'^js/', include(JS_SITE_URLS)) if JS_SITE_URLS else None,

    # Analytics
    url('^', include(ANALYTICS_URLS)) if ANALYTICS_URLS else None,

    # Deprecated URLs
    url(r'^beta$', permanentRedirect('/signup')),
    url(r'^devkit.*$', permanentRedirect('/')),
    url(r'^embed/.*$', permanentRedirect('/')),
  ]

  # Filter out None
  urls = [x for x in urls if x]

  return patterns('polychart.main.views', *urls) 
Example 8
Project: builder   Author: Polychart   File: urls.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def _buildPatternList():
  urls = [
    # Main website
    url(r'^', include(SITE_URLS)) if SITE_URLS else None,

    # Main app
    url(r'^', include(MAIN_URLS)),

    # Polychart.js website
    url(r'^js/', include(JS_SITE_URLS)) if JS_SITE_URLS else None,

    # Analytics
    url('^', include(ANALYTICS_URLS)) if ANALYTICS_URLS else None,

    # Deprecated URLs
    url(r'^beta$', permanentRedirect('/signup')),
    url(r'^devkit.*$', permanentRedirect('/')),
    url(r'^embed/.*$', permanentRedirect('/')),
  ]

  # Filter out None
  urls = [x for x in urls if x]

  return patterns('polychart.main.views', *urls) 
Example 9
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_namespace_pattern_with_variable_prefix(self):
        """
        Using include() with namespaces when there is a regex variable in front
        of it.
        """
        test_urls = [
            ('inc-outer:inc-normal-view', [], {'outer': 42}, '/ns-outer/42/normal/'),
            ('inc-outer:inc-normal-view', [42], {}, '/ns-outer/42/normal/'),
            ('inc-outer:inc-normal-view', [], {'arg1': 37, 'arg2': 4, 'outer': 42}, '/ns-outer/42/normal/37/4/'),
            ('inc-outer:inc-normal-view', [42, 37, 4], {}, '/ns-outer/42/normal/37/4/'),
            ('inc-outer:inc-special-view', [], {'outer': 42}, '/ns-outer/42/+%5C$*/'),
            ('inc-outer:inc-special-view', [42], {}, '/ns-outer/42/+%5C$*/'),
        ]
        for name, args, kwargs, expected in test_urls:
            with self.subTest(name=name, args=args, kwargs=kwargs):
                self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) 
Example 10
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    License: MIT License 5 votes vote down vote up
def test_format_api_patterns_url_import(self):
        urls = patterns('', url(r'api/base/path/', include(self.url_patterns)))
        apis = self.urlparser.get_apis(urls)

        self.assertEqual(len(self.url_patterns), len(apis)) 
Example 11
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    License: MIT License 5 votes vote down vote up
def test_format_api_patterns_excluded_namesapce(self):
        urls = patterns(
            '',
            url(r'api/base/path/',
                include(self.url_patterns, namespace='exclude'))
        )
        apis = self.urlparser.format_api_patterns(
            url_patterns=urls, exclude_namespaces='exclude')

        self.assertEqual([], apis) 
Example 12
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    License: MIT License 5 votes vote down vote up
def test_format_api_patterns_url_import_with_routers(self):

        class MockApiViewSet(ModelViewSet):
            serializer_class = CommentSerializer
            model = User
            queryset = User.objects.all()

        class AnotherMockApiViewSet(ModelViewSet):
            serializer_class = CommentSerializer
            model = User
            queryset = User.objects.all()

        router = DefaultRouter()
        router.register(r'other_views', MockApiViewSet, base_name='test_base_name')
        router.register(r'more_views', AnotherMockApiViewSet, base_name='test_base_name')

        urls_app = patterns('', url(r'^', include(router.urls)))
        urls = patterns(
            '',
            url(r'api/', include(urls_app)),
            url(r'test/', include(urls_app))
        )
        apis = self.urlparser.get_apis(urls)

        self.assertEqual(
            4, sum(api['path'].find('api') != -1 for api in apis))
        self.assertEqual(
            4, sum(api['path'].find('test') != -1 for api in apis)) 
Example 13
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        class FuzzyApiView(APIView):
            def get(self, request):
                pass

        class ShinyApiView(APIView):
            def get(self, request):
                pass

        api_fuzzy_url_patterns = patterns(
            '', url(r'^item/$', FuzzyApiView.as_view(), name='find_me'))
        api_shiny_url_patterns = patterns(
            '', url(r'^item/$', ShinyApiView.as_view(), name='hide_me'))

        fuzzy_app_urls = patterns(
            '', url(r'^api/', include(api_fuzzy_url_patterns,
                                      namespace='api_fuzzy_app')))
        shiny_app_urls = patterns(
            '', url(r'^api/', include(api_shiny_url_patterns,
                                      namespace='api_shiny_app')))

        self.project_urls = patterns(
            '',
            url('my_fuzzy_app/', include(fuzzy_app_urls)),
            url('my_shiny_app/', include(shiny_app_urls)),
        ) 
Example 14
Project: wagtailinvoices   Author: SableWalnut   File: wagtail_hooks.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^invoices/', include(urls)),
    ] 
Example 15
Project: django-nyt   Author: django-wiki   File: urls.py    License: Apache License 2.0 5 votes vote down vote up
def get_pattern(app_name=app_name, namespace="nyt"):
    """Every url resolution takes place as "nyt:view_name".
       https://docs.djangoproject.com/en/dev/topics/http/urls/#topics-http-reversing-url-namespaces
    """
    import warnings
    warnings.warn(
        'django_nyt.urls.get_pattern is deprecated and will be removed in next version,'
        ' just use include(\'django_nyt.urls\')', DeprecationWarning
    )
    return include('django_nyt.urls') 
Example 16
Project: django-nyt   Author: django-wiki   File: urls.py    License: Apache License 2.0 5 votes vote down vote up
def get_pattern(app_name=app_name, namespace="nyt"):
    """Every url resolution takes place as "nyt:view_name".
       https://docs.djangoproject.com/en/dev/topics/http/urls/#topics-http-reversing-url-namespaces
    """
    import warnings
    warnings.warn(
        'django_nyt.urls.get_pattern is deprecated and will be removed in next version,'
        ' just use include(\'django_nyt.urls\')', DeprecationWarning
    )
    return include('django_nyt.urls') 
Example 17
Project: wagtail-personalisation   Author: wagtail   File: wagtail_hooks.py    License: MIT License 5 votes vote down vote up
def register_admin_urls():
    """Adds the administration urls for the personalisation apps."""
    return [
        url(r'^personalisation/', include(
            admin_urls, namespace='wagtail_personalisation')),
    ] 
Example 18
Project: django-admino   Author: erdem   File: sites.py    License: MIT License 5 votes vote down vote up
def get_urls(self):
        urlpatterns = super(AdminoSite, self).get_urls()
        valid_app_labels = []
        for model, model_admin in self._registry.items():
            api_urlpatterns = [
                url(r'^api/%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.api_urls)),
            ]
            urlpatterns = urlpatterns + api_urlpatterns
            if model._meta.app_label not in valid_app_labels:
                valid_app_labels.append(model._meta.app_label)
        return urlpatterns 
Example 19
Project: scale   Author: ngageoint   File: rest.py    License: Apache License 2.0 5 votes vote down vote up
def get_versioned_urls(apps):
    """Generates a list of URLs for applications with REST APIs

    :param apps: A list of application names to register.
    :type apps: [string]
    :returns: A list of URLs for REST APIs with version prefixes.
    :rtype: [:class:`django.core.urlresolvers.RegexURLPattern`]
    """
    urls = []

    # Check whether the application is configured to use versions
    rest_settings = getattr(settings, 'REST_FRAMEWORK', None)
    if not rest_settings:
        return urls
    allowed_versions = rest_settings.get('ALLOWED_VERSIONS', None)
    if not allowed_versions:
        return urls

    # Generate a URL for each endpoint with a version prefix
    for version in allowed_versions:
        app_urls = []
        for app in apps:
            app_urls.append(url('', include(app + '.urls')))

        urls.append(url(r'^' + version + '/', include(app_urls, namespace=version)))
    return urls 
Example 20
Project: scale   Author: ngageoint   File: rest.py    License: Apache License 2.0 5 votes vote down vote up
def parse_datetime(request, name, default_value=None, required=True):
    """Parses a datetime parameter from the given request.

    :param request: The context of an active HTTP request.
    :type request: :class:`rest_framework.request.Request`
    :param name: The name of the parameter to parse.
    :type name: string
    :param default_value: The name of the parameter to parse.
    :type default_value: datetime.datetime
    :param required: Indicates whether or not the parameter is required. An exception will be raised if the parameter
        does not exist, there is no default value, and required is True.
    :type required: bool
    :returns: The value of the named parameter or the default value if provided.
    :rtype: datetime.datetime

    :raises :class:`util.rest.BadParameter`: If the value cannot be parsed.
    """
    value = _get_param(request, name, default_value, required)
    if not isinstance(value, basestring):
        return value

    try:
        result = parse_util.parse_datetime(value)
        if result:
            return result
        raise BadParameter('Did not parse a result for parameter: %s' % name)
    except:
        raise BadParameter('Datetime values must follow ISO-8601 and include a timezone: %s' % name) 
Example 21
Project: gro-api   Author: OpenAgricultureFoundation   File: urls.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_current_urls():
    urls = BaseRouter.get_instance().urls + [
        url(r'^auth/', include(auth_patterns)),
        url(r'^auth/registration/', include(auth_registration_patterns)),
        url(r'^docs/', include('rest_framework_swagger.urls')),
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    if settings.DEBUG:
        import debug_toolbar
        urls.append(url(r'^__debug__/', include(debug_toolbar.urls)))
    return urls 
Example 22
Project: django-ra-erp   Author: ra-systems   File: base.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_urls(self):
        # from ra.utils.views import access_denied
        def wrap(view, cacheable=False):
            def wrapper(*args, **kwargs):
                return self.admin_view(view, cacheable)(*args, **kwargs)

            return update_wrapper(wrapper, view)

        urls = super(RaAdminSiteBase, self).get_urls()
        help_center = [
            url(r'^i18n/', include('django.conf.urls.i18n')),
        ]

        settings_update = [
            url(r'^manifest/$', self.manifest_view, name='manifest'),
            url(r'^sw.js$', self.service_worker_view, name='service-worker'),
        ]

        urlpatterns = [
            url(r'^reports/(?P<base_model>[\w-]+)/$', get_report_list_class, name='report_list'),
            url(r'^reports/(?P<base_model>[\w-]+)/(?P<report_slug>[\w-]+)/$', get_report_view, name='report'),
            # new from sites
            path('top-search/', TopSearchView.as_view(), name='top-search'),
            # path('access-denied/', access_denied, name='access-denied'),
        ]

        return urls + help_center + settings_update + urlpatterns 
Example 23
Project: InvenTree   Author: inventree   File: api.py    License: MIT License 5 votes vote down vote up
def filter_queryset(self, queryset):
        """
        Filter the test list queryset.

        If filtering by 'part', we include results for any parts "above" the specified part.
        """

        queryset = super().filter_queryset(queryset)

        params = self.request.query_params

        part = params.get('part', None)

        # Filter by part
        if part:
            try:
                part = Part.objects.get(pk=part)
                queryset = queryset.filter(part__in=part.get_ancestors(include_self=True))
            except (ValueError, Part.DoesNotExist):
                pass

        # Filter by 'required' status
        required = params.get('required', None)

        if required is not None:
            queryset = queryset.filter(required=required)

        return queryset 
Example 24
Project: online-judge   Author: DMOJ   File: urls.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def paged_list_view(view, name):
    return include([
        url(r'^$', view.as_view(), name=name),
        url(r'^(?P<page>\d+)$', view.as_view(), name=name),
    ]) 
Example 25
Project: django-oscar-wagtail   Author: labd   File: app.py    License: MIT License 5 votes vote down vote up
def get_urls(self):
        urlpatterns = [
            url(r'', include(wagtail_urls)),
        ]

        return self.post_process_urls(urlpatterns) 
Example 26
Project: wagtail   Author: wagtail   File: router.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_urlpatterns(self):
        urlpatterns = []

        for name, class_ in self._endpoints.items():
            pattern = url(
                r'^{}/'.format(name),
                include((class_.get_urlpatterns(), name), namespace=name)
            )
            urlpatterns.append(pattern)

        decorate_urlpatterns(urlpatterns, self.wrap_view)

        return urlpatterns 
Example 27
Project: wagtail   Author: wagtail   File: router.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def urls(self):
        """
        A shortcut to allow quick registration of the API in a URLconf.

        Use with Django's include() function:

            url(r'api/', include(myapi.urls)),
        """
        return self.get_urlpatterns(), self.url_namespace, self.url_namespace 
Example 28
Project: wagtail   Author: wagtail   File: wagtail_hooks.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^images/', include(admin_urls, namespace='wagtailimages')),
    ] 
Example 29
Project: wagtail   Author: wagtail   File: wagtail_hooks.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^search/', include(admin_urls, namespace='wagtailsearch_admin')),
    ] 
Example 30
Project: wagtail   Author: wagtail   File: wagtail_hooks.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^users/', include(users, namespace='wagtailusers_users')),
    ]