Python django.conf.urls.include() Examples

The following are 30 code examples of django.conf.urls.include(). 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.conf.urls , or try the search function .
Example #1
Source File: urls.py    From waliki with BSD 3-Clause "New" or "Revised" License 7 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
Source File: api.py    From InvenTree with 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 #3
Source File: apps.py    From ecommerce with 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 #4
Source File: routemap.py    From urljects with 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 #5
Source File: api.py    From InvenTree with 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 #6
Source File: urls.py    From builder with 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 #7
Source File: urls.py    From builder with 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
Source File: tests.py    From djongo with 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 #9
Source File: rest.py    From scale with 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 #10
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_include_app_name(self):
        self.assertEqual(
            include(self.app_urls),
            (self.app_urls, 'inc-app', 'inc-app')
        ) 
Example #11
Source File: wagtail_hooks.py    From openstax-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^duplicate/', include(admin_urls, namespace='duplicatebooks_admin')),
    ] 
Example #12
Source File: wagtail_hooks.py    From wagtail-review with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_admin_urls():
    admin_urls = [
        url(r'^api/', include(api_urls, namespace='api')),
    ]

    return [
        url(r'^wagtail_review/', include((admin_urls, 'wagtail_review_admin'), namespace='wagtail_review_admin')),
    ] 
Example #13
Source File: wagtail_hooks.py    From wagalytics with MIT License 5 votes vote down vote up
def register_admin_urls():
    return [
        re_path(r'^analytics/', include(urls)),
    ] 
Example #14
Source File: wagtail_hooks.py    From wagtailvideos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^videos/', include(urls)),
    ] 
Example #15
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_include_2_tuple(self):
        self.assertEqual(
            include((self.url_patterns, 'app_name')),
            (self.url_patterns, 'app_name', 'app_name')
        ) 
Example #16
Source File: base.py    From avos with Apache License 2.0 5 votes vote down vote up
def _urls(self):
        """Constructs the URLconf for Horizon from registered Dashboards."""
        urlpatterns = self._get_default_urlpatterns()
        self._autodiscover()

        # Discover each dashboard's panels.
        for dash in self._registry.values():
            dash._autodiscover()

        # Load the plugin-based panel configuration
        self._load_panel_customization()

        # Allow for override modules
        if self._conf.get("customization_module", None):
            customization_module = self._conf["customization_module"]
            bits = customization_module.split('.')
            mod_name = bits.pop()
            package = '.'.join(bits)
            mod = import_module(package)
            try:
                before_import_registry = copy.copy(self._registry)
                import_module('%s.%s' % (package, mod_name))
            except Exception:
                self._registry = before_import_registry
                if module_has_submodule(mod, mod_name):
                    raise

        # Compile the dynamic urlconf.
        for dash in self._registry.values():
            urlpatterns += patterns('',
                                    url(r'^%s/' % dash.slug,
                                        include(dash._decorated_urls)))

        # Return the three arguments to django.conf.urls.include
        return urlpatterns, self.namespace, self.slug 
Example #17
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_include_app_name_namespace(self):
        self.assertEqual(
            include(self.app_urls, 'namespace'),
            (self.app_urls, 'inc-app', 'namespace')
        ) 
Example #18
Source File: sites.py    From ImitationTmall_Django with GNU General Public License v3.0 5 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url, include
        from xadmin.views.base import BaseAdminView

        if settings.DEBUG:
            self.check_dependencies()

        def wrap(view, cacheable=False):
            def wrapper(*args, **kwargs):
                return self.admin_view(view, cacheable)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        # Admin-site-wide views.
        urlpatterns = [
                url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n')
            ]

        # Registed admin views
        # inspect[isclass]: Only checks if the object is a class. With it lets you create an custom view that
        # inherits from multiple views and have more of a metaclass.
        urlpatterns += [
                url(path, wrap(self.create_admin_view(clz_or_func)) if inspect.isclass(clz_or_func) and issubclass(clz_or_func, BaseAdminView) else include(clz_or_func(self)),
                name=name) for path, clz_or_func, name in self._registry_views
            ]

        # Add in each model's views.
        for model, admin_class in self._registry.iteritems():
            view_urls = [url(
                path, wrap(
                    self.create_model_admin_view(clz, model, admin_class)),
                name=name % (model._meta.app_label, model._meta.model_name))
                for path, clz, name in self._registry_modelviews]
            urlpatterns += [
                    url(r'^%s/%s/' % ( model._meta.app_label, model._meta.model_name), include(view_urls))
                ]

        return urlpatterns 
Example #19
Source File: base.py    From avos with Apache License 2.0 5 votes vote down vote up
def _decorated_urls(self):
        urlpatterns = self._get_default_urlpatterns()

        default_panel = None

        # Add in each panel's views except for the default view.
        for panel in self._registry.values():
            if panel.slug == self.default_panel:
                default_panel = panel
                continue
            url_slug = panel.slug.replace('.', '/')
            urlpatterns += patterns('',
                                    url(r'^%s/' % url_slug,
                                        include(panel._decorated_urls)))
        # Now the default view, which should come last
        if not default_panel:
            raise NotRegistered('The default panel "%s" is not registered.'
                                % self.default_panel)
        urlpatterns += patterns('',
                                url(r'',
                                    include(default_panel._decorated_urls)))

        # Require login if not public.
        if not self.public:
            _decorate_urlconf(urlpatterns, require_auth)
        # Apply access controls to all views in the patterns
        permissions = getattr(self, 'permissions', [])
        _decorate_urlconf(urlpatterns, require_perms, permissions)
        _decorate_urlconf(urlpatterns, _current_component, dashboard=self)

        # Return the three arguments to django.conf.urls.include
        return urlpatterns, self.slug, self.slug 
Example #20
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_app_object(self):
        """
        Dynamic URL objects can return a (pattern, app_name) 2-tuple, and
        include() can set the namespace.
        """
        test_urls = [
            ('new-ns1:urlobject-view', [], {}, '/newapp1/inner/'),
            ('new-ns1:urlobject-view', [37, 42], {}, '/newapp1/inner/37/42/'),
            ('new-ns1:urlobject-view', [], {'arg1': 42, 'arg2': 37}, '/newapp1/inner/42/37/'),
            ('new-ns1:urlobject-special-view', [], {}, '/newapp1/inner/+%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 #21
Source File: documentation.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def include_docs_urls(
        title=None, description=None, schema_url=None, public=True,
        patterns=None, generator_class=SchemaGenerator,
        authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES,
        permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES,
        renderer_classes=None):
    docs_view = get_docs_view(
        title=title,
        description=description,
        schema_url=schema_url,
        public=public,
        patterns=patterns,
        generator_class=generator_class,
        authentication_classes=authentication_classes,
        renderer_classes=renderer_classes,
        permission_classes=permission_classes,
    )
    schema_js_view = get_schemajs_view(
        title=title,
        description=description,
        schema_url=schema_url,
        public=public,
        patterns=patterns,
        generator_class=generator_class,
        authentication_classes=authentication_classes,
        permission_classes=permission_classes,
    )
    urls = [
        url(r'^$', docs_view, name='docs-index'),
        url(r'^schema.js$', schema_js_view, name='schema-js')
    ]
    return include((urls, 'api-docs'), namespace='api-docs') 
Example #22
Source File: urlpatterns.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
    """
    Supplement existing urlpatterns with corresponding patterns that also
    include a '.format' suffix.  Retains urlpattern ordering.

    urlpatterns:
        A list of URL patterns.

    suffix_required:
        If `True`, only suffixed URLs will be generated, and non-suffixed
        URLs will not be used.  Defaults to `False`.

    allowed:
        An optional tuple/list of allowed suffixes.  eg ['json', 'api']
        Defaults to `None`, which allows any suffix.
    """
    suffix_kwarg = api_settings.FORMAT_SUFFIX_KWARG
    if allowed:
        if len(allowed) == 1:
            allowed_pattern = allowed[0]
        else:
            allowed_pattern = '(%s)' % '|'.join(allowed)
        suffix_pattern = r'\.(?P<%s>%s)/?$' % (suffix_kwarg, allowed_pattern)
    else:
        suffix_pattern = r'\.(?P<%s>[a-z0-9]+)/?$' % suffix_kwarg

    if path and register_converter:
        converter_name, suffix_converter = _get_format_path_converter(suffix_kwarg, allowed)
        register_converter(suffix_converter, converter_name)

        suffix_route = '<%s:%s>' % (converter_name, suffix_kwarg)
    else:
        suffix_route = None

    return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required, suffix_route) 
Example #23
Source File: settings.py    From django-sae with Apache License 2.0 5 votes vote down vote up
def patch_root_urlconf():
    from django.conf.urls import include, patterns, url
    from django.core.urlresolvers import clear_url_caches, reverse, NoReverseMatch
    from django.utils.importlib import import_module

    try:
        reverse('tasks:execute')
    except NoReverseMatch:
        root = import_module(settings.ROOT_URLCONF)
        root.urlpatterns = patterns('', url(r'^tasks/', include('django_sae.contrib.tasks.urls', 'tasks',
                                                                'tasks')), ) + root.urlpatterns
        clear_url_caches() 
Example #24
Source File: wagtail_hooks.py    From wagtailnews with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def register_admin_urls():
    return [
        url(r'^news/', include(urls)),
    ] 
Example #25
Source File: urls.py    From cartoview with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def app_url(app_name):
    app = str(app_name)
    return url(
        r'^' + app + '/', include('%s.urls' % app), name=app + '_base_url') 
Example #26
Source File: api.py    From cartoview with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def register_app_urls(self, app_name):
        self.urlpatterns.append(
            url(r"^%s/" % app_name, include(self.apis[app_name].urls))) 
Example #27
Source File: api.py    From cartoview with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def urls(self):
        pattern_list = [
            url(r'^$',
                home,
                name='cartoview_rest_url'),
        ]
        for name in sorted(self.apis.keys()):
            pattern_list.append(
                url(r"^%s/" % name, include(self.apis[name].urls)))
        self.urlpatterns = pattern_list
        return self.urlpatterns 
Example #28
Source File: api.py    From cartoview with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def urls(self):
        """
        Provides URLconf details for the ``Api`` and all registered
        ``Resources`` beneath it.
        """
        if self.api_name:
            api_pattern = '(?P<api_name>%s)'
            top_level = r"^%s%s$" % (api_pattern, trailing_slash())
        else:
            api_pattern = '(?P<api_name>)'
            top_level = r"^$"

        pattern_list = [
            url(top_level,
                self.wrap_view('top_level'),
                name="%s_rest_url" % self.app_name),
        ]

        for name in sorted(self._registry.keys()):
            resource = self._registry[name]
            resource.api_name = self.api_name
            pattern_list.append(
                url(r"^%s" % api_pattern, include(resource.urls)))

        urlpatterns = self.prepend_urls()
        overridden_urls = self.override_urls()
        if overridden_urls:
            warnings.warn(
                "'override_urls' is a deprecated method & \
                will be removed by v1.0.0.\
                 Please rename your method to ``prepend_urls``."
            )

            urlpatterns += overridden_urls

        urlpatterns += pattern_list
        return urlpatterns 
Example #29
Source File: urljects.py    From urljects with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def view_include(view_module, namespace=None, app_name=None):
    """
    Includes view in the url, works similar to django include function.
    Auto imports all class based views that are subclass of ``URLView`` and
    all functional views that have been decorated with ``url_view``.

    :param view_module: object of the module or string with importable path
    :param namespace: name of the namespaces, it will be guessed otherwise
    :param app_name: application name
    :return: result of urls.include
    """

    # since Django 1.8 patterns() are deprecated, list should be used instead
    # {priority:[views,]}
    view_dict = defaultdict(list)

    if isinstance(view_module, six.string_types):
        view_module = importlib.import_module(view_module)

    # pylint:disable=unused-variable
    for member_name, member in inspect.getmembers(view_module):
        is_class_view = inspect.isclass(member) and issubclass(member, URLView)
        is_func_view = (inspect.isfunction(member) and
                        hasattr(member, 'urljects_view') and
                        member.urljects_view)

        if (is_class_view and member is not URLView) or is_func_view:
            view_dict[member.url_priority].append(
                url(member.url, member, name=member.url_name))

    view_patterns = list(*[
        view_dict[priority] for priority in sorted(view_dict)
        ])

    return urls.include(
        arg=view_patterns,
        namespace=namespace,
        app_name=app_name) 
Example #30
Source File: sites.py    From devops with MIT License 5 votes vote down vote up
def get_urls(self):
        from django.conf.urls import patterns, url, include
        from xadmin.views.base import BaseAdminView

        if settings.DEBUG:
            self.check_dependencies()

        def wrap(view, cacheable=False):
            def wrapper(*args, **kwargs):
                return self.admin_view(view, cacheable)(*args, **kwargs)
            return update_wrapper(wrapper, view)

        # Admin-site-wide views.
        urlpatterns = patterns('',
                               url(r'^jsi18n/$', wrap(self.i18n_javascript,
                                                      cacheable=True), name='jsi18n')
                               )

        # Registed admin views
        urlpatterns += patterns('',
                                *[url(
                                  path, wrap(self.create_admin_view(clz_or_func)) if type(clz_or_func) == type and issubclass(clz_or_func, BaseAdminView) else include(clz_or_func(self)),
                                  name=name) for path, clz_or_func, name in self._registry_views]
                                )

        # Add in each model's views.
        for model, admin_class in self._registry.iteritems():
            view_urls = [url(
                path, wrap(
                    self.create_model_admin_view(clz, model, admin_class)),
                name=name % (model._meta.app_label, model._meta.model_name))
                for path, clz, name in self._registry_modelviews]
            urlpatterns += patterns('',
                                    url(
                                    r'^%s/%s/' % (
                                        model._meta.app_label, model._meta.model_name),
                                    include(patterns('', *view_urls)))
                                    )

        return urlpatterns