Python django.urls.path() Examples

The following are 30 code examples of django.urls.path(). 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: admin.py    From django-admin-actions with MIT License 6 votes vote down vote up
def changelist_view(self, request, extra_context=None):
        if extra_context is None:
            extra_context = {}

        actions = []
        for method_name in self.actions_list:
            method = getattr(self, method_name)

            actions.append({
                'title': getattr(method, 'short_description', method_name),
                'path': reverse('admin:' + method_name)
            })

        extra_context.update({
            'actions_list': actions,
        })

        return super(ActionsModelAdmin, self).changelist_view(request, extra_context) 
Example #2
Source File: options.py    From bioforum with MIT License 6 votes vote down vote up
def get_urls(self):
        from django.urls import path

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

        info = self.model._meta.app_label, self.model._meta.model_name

        urlpatterns = [
            path('', wrap(self.changelist_view), name='%s_%s_changelist' % info),
            path('add/', wrap(self.add_view), name='%s_%s_add' % info),
            path('autocomplete/', wrap(self.autocomplete_view), name='%s_%s_autocomplete' % info),
            path('<path:object_id>/history/', wrap(self.history_view), name='%s_%s_history' % info),
            path('<path:object_id>/delete/', wrap(self.delete_view), name='%s_%s_delete' % info),
            path('<path:object_id>/change/', wrap(self.change_view), name='%s_%s_change' % info),
            # For backwards compatibility (was the change url before 1.9)
            path('<path:object_id>/', wrap(RedirectView.as_view(
                pattern_name='%s:%s_%s_change' % ((self.admin_site.name,) + info)
            ))),
        ]
        return urlpatterns 
Example #3
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_nonmatching_urls(self):
        test_data = (
            ('int', {'-1', 'letters'}),
            ('str', {'', '/'}),
            ('path', {''}),
            ('slug', {'', 'stars*notallowed'}),
            ('uuid', {
                '',
                '9da9369-838e-4750-91a5-f7805cd82839',
                '39da9369-838-4750-91a5-f7805cd82839',
                '39da9369-838e-475-91a5-f7805cd82839',
                '39da9369-838e-4750-91a-f7805cd82839',
                '39da9369-838e-4750-91a5-f7805cd8283',
            }),
        )
        for url_name, url_suffixes in test_data:
            for url_suffix in url_suffixes:
                url = '/%s/%s/' % (url_name, url_suffix)
                with self.subTest(url=url), self.assertRaises(Resolver404):
                    resolve(url) 
Example #4
Source File: sites.py    From weibo-analysis-system with MIT License 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example #5
Source File: sites.py    From myblog with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example #6
Source File: discovery.py    From omniport-backend with GNU General Public License v3.0 6 votes vote down vote up
def prepare_logging(self, server, site_id):
        """
        Populate the list of app-level loggers and handlers for both services
        and apps
        :param server: information required to generate log file path
        :param site_id: information required to generate log file path
        """

        self.service_logging_loggers = self._prepare_logging_loggers(
            self.services
        )
        self.app_logging_loggers = self._prepare_logging_loggers(
            self.apps
        )
        self.service_logging_handlers = self._prepare_logging_handlers(
            self.services,
            server,
            site_id
        )
        self.app_logging_handlers = self._prepare_logging_handlers(
            self.apps,
            server,
            site_id
        ) 
Example #7
Source File: sites.py    From CTF_AWD_Platform with MIT License 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example #8
Source File: discovery.py    From omniport-backend with GNU General Public License v3.0 6 votes vote down vote up
def _prepare_ws_urlpatterns(app_set):
        """
        Generate WS URL patterns for the given list of tuples of apps and
        configuration objects
        :param app_set: the given list of tuples of apps and their configuration
        objects
        :return: the WS URL patterns
        """

        ws_urlpatterns = list()
        for (app, app_configuration) in app_set:
            if app_configuration.is_allowed:
                url = app_configuration.base_urls.ws
                if url is not None:
                    module = importlib.import_module(f'{app}.ws_urls')
                    dictionary = module.__dict__
                    app_urlpatterns = dictionary['urlpatterns']
                    url_router = URLRouter(app_urlpatterns)
                    ws_urlpatterns.append(
                        path(url, url_router)
                    )
        return ws_urlpatterns 
Example #9
Source File: discovery.py    From omniport-backend with GNU General Public License v3.0 6 votes vote down vote up
def _prepare_http_urlpatterns(app_set):
        """
        Generate HTTP URL patterns for the given list of tuples of apps and
        configuration objects
        :param app_set: the given list of tuples of apps and their configuration
        objects
        :return: the HTTP URL patterns
        """

        http_urlpatterns = list()
        for (app, app_configuration) in app_set:
            if app_configuration.is_allowed:
                url = app_configuration.base_urls.http
                if url is not None:
                    if app_configuration.is_api:
                        url = f'api/{url}'
                    http_urlpatterns.append(
                        path(url, include(f'{app}.http_urls'))
                    )
        return http_urlpatterns 
Example #10
Source File: __init__.py    From rssant with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def urls(self):
        def key_func(r):
            f, url, methods, params, returns = r
            return url
        urls_map = {}
        routes = sorted(self._routes, key=key_func)
        groups = itertools.groupby(routes, key=key_func)
        for url, group in groups:
            view = self._make_view(list(group))
            urls_map[url] = path(url, view)
        # keep urls same order with self._routes
        # and constant url should priority then path argument
        urls = []
        urls_priority = []
        urls_added = set()
        for f, url, methods, params, returns in self._routes:
            if url not in urls_added:
                urls_added.add(url)
                if '<' in url and ':' in url and '>' in url:
                    urls.append(urls_map[url])
                else:
                    urls_priority.append(urls_map[url])
        return urls_priority + urls 
Example #11
Source File: discovery.py    From omniport-backend with GNU General Public License v3.0 6 votes vote down vote up
def _prepare_app_configuration_list(directory):
        """
        Produce a list of tuples of apps and their configurations after scanning
        the specified directory
        :param directory: the directory to scan for apps
        :return: the list of tuples of apps and their configuration objects
        """

        sub_directories = [
            sub_directory
            for sub_directory in os.listdir(path=directory)
            if os.path.isdir(os.path.join(directory, sub_directory))
        ]

        apps_and_configs = list()
        for sub_directory in sub_directories:
            config_path = os.path.join(directory, sub_directory, 'config.yml')
            if os.path.isfile(config_path):
                with open(config_path) as config_file:
                    config_dictionary = yaml.safe_load(config_file)
                config_object = AppConfiguration(dictionary=config_dictionary)
                apps_and_configs.append(
                    (sub_directory, config_object,)
                )
        return apps_and_configs 
Example #12
Source File: sites.py    From online with GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example #13
Source File: kmanager.py    From KerasUI with GNU General Public License v3.0 6 votes vote down vote up
def predict(image_path,datasetid):
        logger.info("predicting "+image_path+" "+str(datasetid))
        dataset=DataSet.objects.get(pk=datasetid)
        modelpath=dataset.model.path        
        logger.info("model path "+modelpath)

        model=load_model(modelpath)
        labels=json.loads(dataset.model_labels)
        
        img = Image.open(image_path)
        img = img.convert('L')
        img = img.resize((256, 256), Image.ANTIALIAS)

        result= model.predict(np.array(img).reshape(-1,256,256, 1))
        max=result[0]
        idx=0
        for i in range(1,len(result)):
            if max<result[i]:
                max=result[i]
                idx=i

        logger.info(result[idx])
        logger.info(labels[idx])
        return labels[idx] 
Example #14
Source File: options.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
def get_urls(self):
        from django.urls import path

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

        info = self.model._meta.app_label, self.model._meta.model_name

        urlpatterns = [
            path('', wrap(self.changelist_view), name='%s_%s_changelist' % info),
            path('add/', wrap(self.add_view), name='%s_%s_add' % info),
            path('autocomplete/', wrap(self.autocomplete_view), name='%s_%s_autocomplete' % info),
            path('<path:object_id>/history/', wrap(self.history_view), name='%s_%s_history' % info),
            path('<path:object_id>/delete/', wrap(self.delete_view), name='%s_%s_delete' % info),
            path('<path:object_id>/change/', wrap(self.change_view), name='%s_%s_change' % info),
            # For backwards compatibility (was the change url before 1.9)
            path('<path:object_id>/', wrap(RedirectView.as_view(
                pattern_name='%s:%s_%s_change' % ((self.admin_site.name,) + info)
            ))),
        ]
        return urlpatterns 
Example #15
Source File: sites.py    From Mxonline3 with Apache License 2.0 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example #16
Source File: sites.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example #17
Source File: test_django.py    From openapi-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_no_resolver(self, request_factory):
        request = request_factory.get('/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 #18
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 #19
Source File: admin.py    From django-admin-actions with MIT License 6 votes vote down vote up
def get_urls(self):
        urls = super().get_urls()

        action_row_urls = []
        for method_name in self.actions_row:
            method = getattr(self, method_name)
            action_row_urls.append(
                path(getattr(method, 'url_path', method_name) + '/<path:pk>/', self.admin_site.admin_view(method), name=method_name))

        action_detail_urls = []
        for method_name in self.actions_detail:
            method = getattr(self, method_name)
            action_detail_urls.append(
                path(getattr(method, 'url_path', method_name) + '/<path:pk>/', self.admin_site.admin_view(method), name=method_name))

        action_list_urls = []
        for method_name in self.actions_list:
            method = getattr(self, method_name)

            action_list_urls.append(
                path(getattr(method, 'url_path', method_name), self.admin_site.admin_view(method), name=method_name)
            )

        return action_list_urls + action_row_urls + action_detail_urls + urls 
Example #20
Source File: admin.py    From django-admin-actions with MIT License 6 votes vote down vote up
def change_view(self, request, object_id, form_url='', extra_context=None):
        if extra_context is None:
            extra_context = {}

        actions = []
        for method_name in self.actions_detail:
            method = getattr(self, method_name)

            actions.append({
                'title': getattr(method, 'short_description', method_name),
                'path': reverse('admin:' + method_name, args=(object_id, ))
            })

        extra_context.update({
            'actions_list': actions,
        })

        return super(ActionsModelAdmin, self).change_view(request, object_id, form_url, extra_context) 
Example #21
Source File: sites.py    From django_OA with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

        self._registry = {}  # model_class class -> admin_class class
        self._registry_avs = {}  # admin_view_class class -> admin_class class
        self._registry_settings = {}  # settings name -> admin_class class
        self._registry_views = []
        # url instance contains (path, admin_view class, name)
        self._registry_modelviews = []
        # url instance contains (path, admin_view class, name)
        self._registry_plugins = {}  # view_class class -> plugin_class class

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example #22
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_override_static_root(self):
        """
        Overriding the STATIC_ROOT setting should be reflected in the
        location attribute of
        django.contrib.staticfiles.storage.staticfiles_storage.
        """
        with self.settings(STATIC_ROOT='/tmp/test'):
            self.assertEqual(staticfiles_storage.location, os.path.abspath('/tmp/test')) 
Example #23
Source File: test_debug.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_404_not_in_urls(self):
        response = self.client.get('/not-in-urls')
        self.assertNotContains(response, "Raised by:", status_code=404)
        self.assertContains(response, "Django tried these URL patterns", status_code=404)
        self.assertContains(response, "<code>not-in-urls</code>, didn't match", status_code=404)
        # Pattern and view name of a RegexURLPattern appear.
        self.assertContains(response, r"^regex-post/(?P&lt;pk&gt;[0-9]+)/$", status_code=404)
        self.assertContains(response, "[name='regex-post']", status_code=404)
        # Pattern and view name of a RoutePattern appear.
        self.assertContains(response, r"path-post/&lt;int:pk&gt;/", status_code=404)
        self.assertContains(response, "[name='path-post']", status_code=404) 
Example #24
Source File: test_debug.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_404_empty_path_not_in_urls(self):
        response = self.client.get('/')
        self.assertContains(response, "The empty path didn't match any of these.", status_code=404) 
Example #25
Source File: test_debug.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_template_not_found_error(self):
        # Raises a TemplateDoesNotExist exception and shows the debug view.
        url = reverse('raises_template_does_not_exist', kwargs={"path": "notfound.html"})
        with self.assertLogs('django.request', 'ERROR'):
            response = self.client.get(url)
        self.assertContains(response, '<div class="context" id="', status_code=500) 
Example #26
Source File: route.py    From django-request-mapping with GNU General Public License v3.0 5 votes vote down vote up
def register(self, clazz):
        class_request_mapping: RequestMapping = getattr(clazz, 'request_mapping', None)
        if class_request_mapping is None:
            raise RuntimeError('view class should use request_mapping decorator.')

        # path value on class decorator
        class_path_value = class_request_mapping.value

        url_patterns_dict: Dict[Tuple[str, str], Dict] = dict()
        for func_name in dir(clazz):
            func = getattr(clazz, func_name)
            mapping: RequestMapping = getattr(func, 'request_mapping', None)
            if mapping is None:
                continue
            request_method = mapping.method
            # path value on method decorator
            method_path_value = mapping.value
            path_type = mapping.path_type
            full_value = class_path_value + method_path_value
            full_value = self._fix_path_value(full_value, path_type)

            if (path_type, full_value) in url_patterns_dict:
                temp_func_name = url_patterns_dict[(path_type, full_value)].setdefault(request_method, func_name)
                # check if method and path are duplicated
                assert temp_func_name == func_name, "path: {} with method: {} is duplicated".format(
                    full_value,
                    request_method
                )
            else:
                url_patterns_dict[(path_type, full_value)] = {request_method: func_name}

        self.update_urlpatterns(clazz, url_patterns_dict) 
Example #27
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_not_equal(self):
        invalid_tests = (
            # Protocol must be the same.
            ('http://example.com/', 'https://example.com/'),
            ('http://example.com/?x=1&x=2', 'https://example.com/?x=2&x=1'),
            ('http://example.com/?x=1&y=bar&x=2', 'https://example.com/?y=bar&x=2&x=1'),
            # Parameters of the same name must be in the same order.
            ('/path/to?a=1&a=2', '/path/to/?a=2&a=1')
        )
        for url1, url2 in invalid_tests:
            with self.subTest(url=url1), self.assertRaises(AssertionError):
                self.assertURLEqual(url1, url2) 
Example #28
Source File: sites.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def register_modelview(self, path, admin_view_class, name):
        from xadmin.views.base import BaseAdminView
        if issubclass(admin_view_class, BaseAdminView):
            self._registry_modelviews.append((path, admin_view_class, name))
        else:
            raise ImproperlyConfigured(u'The registered view class %s isn\'t subclass of %s' %
                                       (admin_view_class.__name__, BaseAdminView.__name__)) 
Example #29
Source File: admin.py    From govready-q with GNU General Public License v3.0 5 votes vote down vote up
def get_urls(self):
		from django.urls import path
		return [
			path(r'import-app/<int:appsourceid>/<str:appname>', self.admin_site.admin_view(self.import_app_view)),
		] + super().get_urls() 
Example #30
Source File: sites.py    From Mxonline3 with Apache License 2.0 5 votes vote down vote up
def register_view(self, path, admin_view_class, name):
        self._registry_views.append((path, admin_view_class, name))