Python django.conf.urls.url() Examples

The following are code examples for showing how to use django.conf.urls.url(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 7 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 2
Project: xadmin_bugfix   Author: vip68   File: sites.py    BSD 3-Clause "New" or "Revised" 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 3
Project: django-xadmin   Author: MarkHoo   File: sites.py    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 4
Project: django-xadmin   Author: MarkHoo   File: sites.py    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
Project: django-dynamic-views   Author: ddaan   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def order_by(self):
        """
        Propery method to determine the order by.
        First check if it is used in the url, then retrieve the user setting and else it is an empty string

        :return: string order by
        """
        order_by = self.request.GET.get('order_by', None)
        if order_by in self.get_field_names():
            if order_by in self.get_order_fields():
                if self.request.GET.get('sort') == 'DESC':
                    return '-%s' % order_by
                else:
                    return order_by

        return '' 
Example 6
Project: django-dynamic-views   Author: ddaan   File: views.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def urls(self):
        urls = []
        for link in self.links:
            if hasattr(self, '{}_link'.format(link)):
                link_name = getattr(self, '{}_link'.format(link))
            else:
                link_name = link

            url_check = r'{}/{}/'.format(self.model_name, link_name)

            if hasattr(self, '{}_kwargs'.format(link)):
                link_kwargs = getattr(self, '{}_kwargs_regexp'.format(link))
                url_check += '{}/'.format(link_kwargs)

            # Add start and end of line to regex pattern
            url_check = '^%s$' % url_check

            action_cls = getattr(self, '{}_class'.format(link))
            urls.append(url(url_check, action_cls, name=self.link_name(link)))

        return urls 
Example 7
Project: omni-forms   Author: omni-digital   File: wagtail_hooks.py    MIT License 6 votes vote down vote up
def add_field_button(self, pk, classnames_add=None, classnames_exclude=None):
        """
        Helper method for generating a button to display in the list view
        for the WagtailOmniForm ModelAdmin class. The button itself will
        be displayed in each row, next to the  edit and delete buttons

        :param pk: The primary key of the OmniForm model instance
        :param classnames_add: List of extra class names to add to the button
        :param classnames_exclude: List class names to remove from the button
        :return: Dict of data required to construct a button in the template
        """
        if classnames_add is None:
            classnames_add = []
        if classnames_exclude is None:
            classnames_exclude = []

        classnames = self.edit_button_classnames + classnames_add
        classname = self.finalise_classname(classnames, classnames_exclude)
        return {
            'url': self.url_helper.get_action_url('select_field', pk),
            'label': 'Add field',
            'classname': classname,
            'title': 'Add a new field',
        } 
Example 8
Project: omni-forms   Author: omni-digital   File: wagtail_hooks.py    MIT License 6 votes vote down vote up
def add_handler_button(self, pk, classnames_add=None, classnames_exclude=None):
        """
        Helper method for generating a button to display in the list view
        for the WagtailOmniForm ModelAdmin class. The button itself will
        be displayed in each row, next to the edit and delete buttons

        :param pk: The primary key of the OmniForm model instance
        :param classnames_add: List of extra class names to add to the button
        :param classnames_exclude: List class names to remove from the button
        :return: Dict of data required to construct a button in the template
        """
        if classnames_add is None:
            classnames_add = []
        if classnames_exclude is None:
            classnames_exclude = []

        classnames = self.edit_button_classnames + classnames_add
        classname = self.finalise_classname(classnames, classnames_exclude)
        return {
            'url': self.url_helper.get_action_url('select_handler', pk),
            'label': 'Add handler',
            'classname': classname,
            'title': 'Add a new handler',
        } 
Example 9
Project: omni-forms   Author: omni-digital   File: wagtail_hooks.py    MIT License 6 votes vote down vote up
def clone_form_button(self, pk, classnames_add=None, classnames_exclude=None):
        """
        Helper method for generating a button to display in the list view
        for the WagtailOmniForm ModelAdmin class. The button itself will
        be displayed in each row, next to the  edit and delete buttons

        :param pk: The primary key of the OmniForm model instance
        :param classnames_add: List of extra class names to add to the button
        :param classnames_exclude: List class names to remove from the button
        :return: Dict of data required to construct a button in the template
        """
        if classnames_add is None:
            classnames_add = []
        if classnames_exclude is None:
            classnames_exclude = []

        classnames = self.edit_button_classnames + classnames_add
        classname = self.finalise_classname(classnames, classnames_exclude)
        return {
            'url': self.url_helper.get_action_url('clone_form', pk),
            'label': 'Clone form',
            'classname': classname,
            'title': 'Clone form',
        } 
Example 10
Project: django-performance-testing   Author: PaesslerAG   File: test_integrates_with_django_test_client.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_can_specify_limits_through_settings_for_django_test_client(
        db, settings, client, method, limit, value, cfg_key, items_name,
        view_ctx):
    settings.PERFORMANCE_LIMITS = {
        'django.test.client.Client': {
            cfg_key: {
                'total': limit
            }
        }
    }
    with view_ctx(value=value) as vctx:
        with pytest.raises(LimitViolationError) as excinfo:
            vctx.request(getattr(client, method.lower()))
        assert excinfo.value.context == {
            'Client.request': ['{method} {url}'.format(
                url=vctx.url, method=method)]}
        assert excinfo.value.items_name == items_name, \
            excinfo.value.base_error_msg 
Example 11
Project: django-glitter   Author: developersociety   File: admin.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_fieldsets(self, request, obj=None):
        fields = [
            'url', 'title', 'parent', 'tags', 'login_required', 'show_in_navigation',
        ]

        # Don't show login_required unless needed
        if not getattr(settings, 'GLITTER_SHOW_LOGIN_REQUIRED', False):
            fields.remove('login_required')

        # Show glitter tags if it's set to show.
        if not getattr(settings, 'GLITTER_PAGES_TAGS', False):
            fields.remove('tags')

        fieldsets = [
            [None, {'fields': fields}],

            ['Advanced options', {
                'classes': ['collapse'],
                'fields': ['glitter_app_name'],
            }]
        ]
        return fieldsets 
Example 12
Project: chattR   Author: patrickstocklin   File: sites.py    GNU General Public License v2.0 6 votes vote down vote up
def password_change(self, request, extra_context=None):
        """
        Handles the "change password" task -- both form display and validation.
        """
        from django.contrib.admin.forms import AdminPasswordChangeForm
        from django.contrib.auth.views import password_change
        url = reverse('admin:password_change_done', current_app=self.name)
        defaults = {
            'current_app': self.name,
            'password_change_form': AdminPasswordChangeForm,
            'post_change_redirect': url,
            'extra_context': dict(self.each_context(request), **(extra_context or {})),
        }
        if self.password_change_template is not None:
            defaults['template_name'] = self.password_change_template
        return password_change(request, **defaults) 
Example 13
Project: chattR   Author: patrickstocklin   File: options.py    GNU General Public License v2.0 6 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url

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

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

        urlpatterns = [
            url(r'^$', wrap(self.changelist_view), name='%s_%s_changelist' % info),
            url(r'^add/$', wrap(self.add_view), name='%s_%s_add' % info),
            url(r'^(.+)/history/$', wrap(self.history_view), name='%s_%s_history' % info),
            url(r'^(.+)/delete/$', wrap(self.delete_view), name='%s_%s_delete' % info),
            url(r'^(.+)/$', wrap(self.change_view), name='%s_%s_change' % info),
        ]
        return urlpatterns 
Example 14
Project: django-admin-reset   Author: tiborhari   File: admin.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def password_reset_url(self, request, id, form_url=''):
        if not self.has_change_permission(request):
            raise PermissionDenied
        user = self.get_object(request, unquote(id))
        if user is None:
            raise Http404(_('%(name)s object with primary key %(key)r does '
                            'not exist.') % {
                'name': self.model._meta.verbose_name,
                'key': escape(id),
            })

        token_generator = PasswordResetTokenGenerator()
        url = reverse(
            'admin:password_reset_confirm',
            kwargs={'uidb64': force_text(
                urlsafe_base64_encode(force_bytes(user.pk))),
                'token': token_generator.make_token(user)})
        url = request.build_absolute_uri(url)
        return TemplateResponse(
            request,
            'admin/password_reset_url.html',
            context={'user': user, 'url': url, 'title': _('Password reset'),
                     'timeout_days': settings.PASSWORD_RESET_TIMEOUT_DAYS}) 
Example 15
Project: opadmin   Author: cc0411   File: sites.py    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 16
Project: StormOnline   Author: stormsha   File: sites.py    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
Project: heltour   Author: cyanfish   File: admin.py    MIT License 6 votes vote down vote up
def link_reminder(self, request, queryset):
        slack_users = slackapi.get_user_list()
        by_email = {u.email: u.id for u in slack_users}

        for sp in queryset.filter(is_active=True, player__slack_user_id='').select_related(
            'player').nocache():
            uid = by_email.get(sp.player.email)
            if uid:
                token = LoginToken.objects.create(slack_user_id=uid,
                                                  username_hint=sp.player.lichess_username,
                                                  expires=timezone.now() + timedelta(days=30))
                url = reverse('by_league:login_with_token',
                              args=[sp.season.league.tag, token.secret_token])
                url = request.build_absolute_uri(url)
                text = 'Reminder: You need to link your Slack and Lichess accounts. <%s|Click here> to do that now. Contact a mod if you need help.' % url
                slackapi.send_message(uid, text)

        return redirect('admin:tournament_seasonplayer_changelist') 
Example 18
Project: pyaedj   Author: google   File: extensions.py    Apache License 2.0 6 votes vote down vote up
def _get_cancel_url(self, request, object_id):
    """Creates an appropriate cancel URL: to list view or to obejct view."""
    if self._use_query_string_view_routing():
      # current path: /cms/{{ model }}-{{ pk }}/change/?cms-action{{ action }}
      if object_id is None:
        url = request.path + '../'
      else:
        url = request.path
      return HttpResponseRedirect(url)
    else:
      # current path: /cms/{{ model }}-{{ pk }}/{{ action }}/
      if object_id is None:
        url = request.path + '../'
      else:
        url = request.path + '../%s/' % self._ACTION_CHANGE_NAME
      return HttpResponseRedirect(url) 
Example 19
Project: AneMo   Author: jspargo   File: options.py    GNU General Public License v2.0 6 votes vote down vote up
def get_urls(self):
        from django.conf.urls import patterns, url

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

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

        urlpatterns = patterns('',
            url(r'^$', wrap(self.changelist_view), name='%s_%s_changelist' % info),
            url(r'^add/$', wrap(self.add_view), name='%s_%s_add' % info),
            url(r'^(.+)/history/$', wrap(self.history_view), name='%s_%s_history' % info),
            url(r'^(.+)/delete/$', wrap(self.delete_view), name='%s_%s_delete' % info),
            url(r'^(.+)/$', wrap(self.change_view), name='%s_%s_change' % info),
        )
        return urlpatterns 
Example 20
Project: xadmin_bugfix   Author: vip68   File: sites.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 21
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 22
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 23
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 24
Project: django-dynamic-views   Author: ddaan   File: views.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_paginate_url(self):
        """
        The url it should paginate on. By default an empty string

        :return: string url
        """
        return '' 
Example 25
Project: omni-forms   Author: omni-digital   File: wagtail_hooks.py    MIT License 5 votes vote down vote up
def _get_object_specific_action_url_pattern(self, action):
        """
        Allows us to hook extra urls into the model admin

        :param action: View action to get the url pattern for
        :return:
        """
        if action == 'clone_form':
            return r'^{0}/{1}/{2}/(?P<instance_pk>[-\w]+)/$'.format(
                self.opts.app_label,
                self.opts.model_name,
                action
            )
        elif action == 'add_field':
            return r'^{0}/{1}/{2}/(?P<instance_pk>[-\w]+)/(?P<related_object_ctype_id>[\d]+)/$'.format(
                self.opts.app_label,
                self.opts.model_name,
                action
            )
        elif action in ('change_field', 'delete_field'):
            return r'^{0}/{1}/{2}/(?P<instance_pk>[-\w]+)/(?P<related_object_id>[\d]+)/$'.format(
                self.opts.app_label,
                self.opts.model_name,
                action
            )
        elif action == 'add_handler':
            return r'^{0}/{1}/{2}/(?P<instance_pk>[-\w]+)/(?P<related_object_ctype_id>[\d]+)/$'.format(
                self.opts.app_label,
                self.opts.model_name,
                action
            )
        elif action in ('change_handler', 'delete_handler'):
            return r'^{0}/{1}/{2}/(?P<instance_pk>[-\w]+)/(?P<related_object_id>[\d]+)/$'.format(
                self.opts.app_label,
                self.opts.model_name,
                action
            )
        return super(WagtailOmniFormURLHelper, self)._get_object_specific_action_url_pattern(action) 
Example 26
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    MIT License 5 votes vote down vote up
def setUp(self):
        self.url_patterns = patterns(
            '',
            url(r'a-view/$', MockApiView.as_view(), name='a test view'),
            url(r'b-view$', MockApiView.as_view(), name='a test view'),
            url(r'c-view/$', MockApiView.as_view(), name='a test view'),
            url(r'a-view/child/?$', MockApiView.as_view()),
            url(r'a-view/child2/?$', MockApiView.as_view()),
            url(r'another-view/?$', MockApiView.as_view(),
                name='another test view'),
            url(r'view-with-param/(:?<ID>\d+)/?$', MockApiView.as_view(),
                name='another test view'),
            url(r'a-view-honky/?$', MockApiView.as_view(), name='a test view'),
        )
        self.urlparser = UrlParser() 
Example 27
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    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 28
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    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 29
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    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 30
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    MIT License 5 votes vote down vote up
def test_get_api_callback_not_rest_view(self):
        non_api = patterns(
            '',
            url(r'something', NonApiView.as_view())
        )
        callback = self.urlparser.filter_api_view_callbacks(non_api[0])

        self.assertIsNone(callback) 
Example 31
Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    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 32
Project: django-performance-testing   Author: PaesslerAG   File: test_integrates_with_django_test_client.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __enter__(self):
        urlpatterns.append(url(self.reverse_name, self, {}, self.reverse_name))
        return self 
Example 33
Project: django-performance-testing   Author: PaesslerAG   File: test_integrates_with_django_test_client.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def url(self):
        return reverse(self.reverse_name) 
Example 34
Project: django-performance-testing   Author: PaesslerAG   File: test_integrates_with_django_test_client.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def request(self, method):
        response = method(self.url)
        print(response.status_code)  # helps when it fails
        return response 
Example 35
Project: wagtailcloudinary   Author: dteskera   File: sites.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url
        urlpatterns = [
            url(r'^browse/$', staff_nocache(self.browse), name="browse"),
            url(r'^select/(.*)$', staff_nocache(self.select), name="select"),
            url(r'^update/(.*)$', staff_nocache(self.update), name="update"),
            url(r'^upload/$', staff_nocache(self.upload), name="upload"),
        ]
        return urlpatterns 
Example 36
Project: wagtailcloudinary   Author: dteskera   File: sites.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def select(self, request, path):
        slugs = path.split('/')
        slugs.insert(2, self.admin_image_version)
        transformed = '/'.join(slugs)
        return render_modal_workflow(
            request,
            None,
            'wagtailcloudinary/image_chosen.js',
            {
                'image_json': {
                    'value': path,
                    'url': '{}{}'.format(self.base_url, transformed)
                }
            }
        ) 
Example 37
Project: django-glitter   Author: developersociety   File: admin.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_urls(self):
        def wrap(view):
            def wrapper(*args, **kwargs):
                return self.admin_site.admin_view(view)(*args, **kwargs)
            return update_wrapper(wrapper, view)
        urlpatterns = super().get_urls()

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

        urlpatterns = [
            url(r'^$', wrap(self.grid_view)),
            url(r'^tree/$', wrap(self.changelist_view), name='%s_%s_tree' % info),
            url(r'^(\d+)/duplicate/$', wrap(self.duplicate_page), name='%s_%s_duplicate' % info),
        ] + urlpatterns
        return urlpatterns 
Example 38
Project: chattR   Author: patrickstocklin   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def media(self):
        extra = '' if settings.DEBUG else '.min'
        js = [
            'core.js',
            'admin/RelatedObjectLookups.js',
            'jquery%s.js' % extra,
            'jquery.init.js'
        ]
        if self.actions is not None:
            js.append('actions%s.js' % extra)
        if self.prepopulated_fields:
            js.extend(['urlify.js', 'prepopulate%s.js' % extra])
        return forms.Media(js=[static('admin/js/%s' % url) for url in js]) 
Example 39
Project: normandy   Author: mozilla   File: routers.py    Mozilla Public License 2.0 5 votes vote down vote up
def register_view(self, prefix, View, *, name, allow_cdn=True, **kwargs):
        url_pattern = url(r"^{}/$".format(prefix), View.as_view(), name=name, **kwargs)
        url_pattern.allow_cdn = allow_cdn
        self.registered_view_urls.append(url_pattern) 
Example 40
Project: normandy   Author: mozilla   File: test_api.py    Mozilla Public License 2.0 5 votes vote down vote up
def static_url_pattern_conf(cls, mock_conf, dummy_view):
        mock_conf.urlpatterns = [url("^test$", dummy_view, name="test-view")]
        return mock_conf 
Example 41
Project: normandy   Author: mozilla   File: test_api.py    Mozilla Public License 2.0 5 votes vote down vote up
def dynamic_url_pattern_conf(cls, mock_conf, dummy_view):
        url_pattern = url("^test$", dummy_view, name="test-view")
        url_pattern.allow_cdn = False
        mock_conf.urlpatterns = [url_pattern]
        return mock_conf 
Example 42
Project: ramlwrap   Author: jmons   File: raml.py    MIT License 5 votes vote down vote up
def raml_url_patterns(raml_filepath, function_map):
    """
    creates url patterns that match the endpoints in the raml file, so can be quickly inserted into django urls.
    Note these
    :param raml_filepath: the path to the raml file (not a file pointer)
    :param function_map: a dictionary of urls to functions for mapping
    :return:
    """

    # This function will run in three phases:
    # 1) Load the raml (as a yaml document)
    # 2) Parse the raml into nodes that represent 'endpoints'
    # 3) Convert endpoints into a url structure

    # migrating from pyraml: file handling now has to be done by us
    # worry about streaming files in future version (for VERY BIG raml?)
    f = open(raml_filepath)
    tree = yaml.load(f, Loader=Loader)  # This loader has the !include directive
    f.close()

    # The resource map is the found nodes

    patterns = []
    to_look_at = [
        {
            "node": tree,
            "path": ""
        }
    ]

    # FIXME: get baseuri, and default media types out here

    defaults = {
        "content_type": "application/json",
    }

    for item in to_look_at:
        _parse_child(item, patterns, to_look_at, function_map, defaults)

    return patterns 
Example 43
Project: tg-apicore   Author: thorgate   File: views.py    ISC License 5 votes vote down vote up
def get_site_url(self) -> str:
        """ Should return your site's url without path, e.g. https://example.com/ """
        raise NotImplementedError() 
Example 44
Project: tg-apicore   Author: thorgate   File: views.py    ISC License 5 votes vote down vote up
def urlpatterns(cls):
        return [
            # This one is for when the version is valid
            url(r'^(?P<version>(\d{4}-\d{2}-\d{2}))/', cls.as_view()),
            # This one is catch-all for everything else, including invalid versions
            url(r'^', cls.as_view()),
        ] 
Example 45
Project: django-admin-reset   Author: tiborhari   File: admin.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_urls(self):
        return [
            url('^(?P<id>[^/.]+)/password_reset_url/$',
                self.admin_site.admin_view(self.password_reset_url),
                name='password_reset_url'),
            url(r'^password_reset_confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/'
                r'(?P<token>[0-9A-Za-z]+-[0-9A-Za-z]+)/$',
                PasswordResetConfirmView.as_view(
                    success_url=reverse_lazy('admin:password_reset_complete')),
                name='password_reset_confirm'),
            url(r'^password_reset_complete/done/$',
                AdminResetCompleteView.as_view(),
                name='password_reset_complete')
        ] + super(PasswordResetUserAdmin, self).get_urls() 
Example 46
Project: opadmin   Author: cc0411   File: sites.py    GNU General Public License v3.0 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 47
Project: wagtailplus   Author: MechanisM   File: utils.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_component_urls():
    """
    Returns list of address component URLs based on address attribute map.

    :rtype: list.
    """
    component_patterns = []
    
    for component, label in ADDRESS_ATTR_MAP.iteritems():
        label           = unicode(label)
        chooser_name    = 'wagtailaddresses_{0}_chooser'.format(component)
        create_name     = 'wagtailaddresses_{0}_create'.format(component)
        
        component_patterns.append(url(
            r'^{0}-chooser/$'.format(label.lower().replace(' ', '-')),
            choosers.ChooseComponentView.as_view(
                comp_type=label,
                chooser_name=chooser_name,
                create_name=create_name
            ),
            name=chooser_name
        ))
        
        component_patterns.append(url(
            r'^{0}-chooser/create/$'.format(label.lower().replace(' ', '-')),
            choosers.CreateComponentView.as_view(
                comp_type=label,
                chooser_name=chooser_name,
                create_name=create_name
            ),
            name=create_name
        ))

    return component_patterns 
Example 48
Project: StormOnline   Author: stormsha   File: sites.py    Apache License 2.0 5 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request) and getattr(view, 'need_site_permission', True):
                return self.create_admin_view(self.login_view)(request, *args, **kwargs)
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        return update_wrapper(inner, view) 
Example 49
Project: litmus-site   Author: alps-jbnu   File: submission.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_urls(self):
        return [url(r'^(\d+)/judge/$', self.judge_view, name='judge_submission_rejudge')] + \
               super(SubmissionAdmin, self).get_urls() 
Example 50
Project: litmus-site   Author: alps-jbnu   File: contest.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def get_urls(self):
        return [url(r'^rate/all/$', self.rate_all_view, name='judge_contest_rate_all'),
                url(r'^(\d+)/rate/$', self.rate_view, name='judge_contest_rate')] + super(ContestAdmin, self).get_urls() 
Example 51
Project: litmus-site   Author: alps-jbnu   File: urls.py    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 52
Project: heltour   Author: cyanfish   File: admin.py    MIT License 5 votes vote down vote up
def get_urls(self):
        urls = super(LeagueAdmin, self).get_urls()
        my_urls = [
            url(r'^(?P<object_id>[0-9]+)/import_season/$',
                self.admin_site.admin_view(self.import_season_view),
                name='import_season'),
            url(r'^(?P<object_id>[0-9]+)/export_forfeit_data/$',
                self.admin_site.admin_view(self.export_forfeit_data_view),
                name='export_forfeit_data'),
        ]
        return my_urls + urls 
Example 53
Project: heltour   Author: cyanfish   File: admin.py    MIT License 5 votes vote down vote up
def get_urls(self):
        urls = super(RoundAdmin, self).get_urls()
        my_urls = [
            url(r'^(?P<object_id>[0-9]+)/generate_pairings/$',
                self.admin_site.admin_view(self.generate_pairings_view),
                name='generate_pairings'),
            url(r'^(?P<object_id>[0-9]+)/review_pairings/$',
                self.admin_site.admin_view(self.review_pairings_view),
                name='review_pairings'),
        ]
        return my_urls + urls 
Example 54
Project: heltour   Author: cyanfish   File: admin.py    MIT License 5 votes vote down vote up
def get_urls(self):
        urls = super(PlayerLateRegistrationAdmin, self).get_urls()
        my_urls = [
            url(r'^(?P<object_id>[0-9]+)/move_latereg/$',
                self.admin_site.admin_view(self.move_latereg_view),
                name='move_latereg'),
        ]
        return my_urls + urls 
Example 55
Project: heltour   Author: cyanfish   File: admin.py    MIT License 5 votes vote down vote up
def game_link_url(self, obj):
        if not obj.game_link:
            return ''
        return format_html("<a href='{url}'>{url}</a>", url=obj.game_link) 
Example 56
Project: heltour   Author: cyanfish   File: admin.py    MIT License 5 votes vote down vote up
def game_link_url(self, obj):
        if not obj.game_link:
            return ''
        return format_html("<a href='{url}'>{url}</a>", url=obj.game_link) 
Example 57
Project: heltour   Author: cyanfish   File: admin.py    MIT License 5 votes vote down vote up
def get_urls(self):
        urls = super(RegistrationAdmin, self).get_urls()
        my_urls = [
            url(r'^(?P<object_id>[0-9]+)/review/$',
                self.admin_site.admin_view(self.review_registration),
                name='review_registration'),
            url(r'^(?P<object_id>[0-9]+)/approve/$',
                self.admin_site.admin_view(self.approve_registration),
                name='approve_registration'),
            url(r'^(?P<object_id>[0-9]+)/reject/$',
                self.admin_site.admin_view(self.reject_registration),
                name='reject_registration')
        ]
        return my_urls + urls 
Example 58
Project: heltour   Author: cyanfish   File: admin.py    MIT License 5 votes vote down vote up
def get_urls(self):
        urls = super(SeasonPlayerAdmin, self).get_urls()
        my_urls = [
            url(r'^(?P<object_ids>[0-9,]+)/bulk_email/$',
                self.admin_site.admin_view(self.bulk_email_view),
                name='bulk_email_by_players'),
        ]
        return my_urls + urls 
Example 59
Project: heltour   Author: cyanfish   File: admin.py    MIT License 5 votes vote down vote up
def url(self, obj):
        _url = reverse('by_league:document', args=[obj.league.tag, obj.tag])
        return mark_safe('<a href="%s">%s</a>' % (_url, _url))


# ------------------------------------------------------------------------------- 
Example 60
Project: heltour   Author: cyanfish   File: admin.py    MIT License 5 votes vote down vote up
def get_urls(self):
        urls = super(ModRequestAdmin, self).get_urls()
        my_urls = [
            url(r'^(?P<object_id>[0-9]+)/review/$',
                self.admin_site.admin_view(self.review_request),
                name='tournament_modrequest_review'),
            url(r'^(?P<object_id>[0-9]+)/approve/$',
                self.admin_site.admin_view(self.approve_request),
                name='tournament_modrequest_approve'),
            url(r'^(?P<object_id>[0-9]+)/reject/$',
                self.admin_site.admin_view(self.reject_request),
                name='tournament_modrequest_reject')
        ]
        return my_urls + urls 
Example 61
Project: longclaw   Author: JamesRamm   File: wagtail_hooks.py    MIT License 5 votes vote down vote up
def cancel_button(self, pk, classnames_add=None, classnames_exclude=None):
        if classnames_add is None:
            classnames_add = ['cancel-button']
        if classnames_exclude is None:
            classnames_exclude = []
        classnames = self.cancel_button_classnames + classnames_add
        cn = self.finalise_classname(classnames, classnames_exclude)
        return {
            'url': '',
            'label': _('Cancel'),
            'classname': cn,
            'title': _('Cancel this %s') % self.verbose_name,
        } 
Example 62
Project: longclaw   Author: JamesRamm   File: wagtail_hooks.py    MIT License 5 votes vote down vote up
def detail_button(self, pk, classnames_add=None, classnames_exclude=None):
        if classnames_add is None:
            classnames_add = ['detail-button']
        if classnames_exclude is None:
            classnames_exclude = []
        classnames = self.detail_button_classnames + classnames_add
        cn = self.finalise_classname(classnames, classnames_exclude)
        return {
            'url': self.url_helper.get_action_url('detail', quote(pk)),
            'label': _('View'),
            'classname': cn,
            'title': _('View this %s') % self.verbose_name,
        } 
Example 63
Project: longclaw   Author: JamesRamm   File: wagtail_hooks.py    MIT License 5 votes vote down vote up
def get_admin_urls_for_registration(self):
        """
        Utilised by Wagtail's 'register_admin_urls' hook to register urls for
        our the views that class offers.
        """
        urls = super(OrderModelAdmin, self).get_admin_urls_for_registration()
        urls = urls + (
            url(self.url_helper.get_action_url_pattern('detail'),
                self.detail_view,
                name=self.url_helper.get_action_url_name('detail')),
        )
        return urls 
Example 64
Project: pyaedj   Author: google   File: extensions.py    Apache License 2.0 5 votes vote down vote up
def _make_url(self, action, method):
    """Makes a URL for action view."""
    if action == self._ACTION_LIST_NAME:
      path = r'^$'
    elif action == self.ACTION_ADD_NAME:
      path = r'^add/$'
    else:
      path = r'^(.+)/{}/$'.format(action)
    return urls.url(
        path,
        method,
        name='_'.join((self.APP_NAME, self.model.__name__.lower(), action))) 
Example 65
Project: django-oscar-ficta   Author: okfish   File: app.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_urls(self):
        urlpatterns = super(InvoiceApplication, self).get_urls()
        urlpatterns += patterns('',
            url(r'^print/(?P<number>[\w-]+)/$', login_required(self.print_view.as_view()),
                name='print'),
            url(r'^view/(?P<pk>\d+)/$',
                self.detail_view.as_view(), name='detail'),
        )
#         urlpatterns += patterns('',
#             url(r'^person-lookup/', cache_page(60*10)(self.person_lookup_view.as_view()),
#                 name='person-lookup'),
#         )
        return self.post_process_urls(urlpatterns) 
Example 66
Project: TESTGIT   Author: B-ROY   File: options.py    Apache License 2.0 5 votes vote down vote up
def get_urls(self):
        from django.conf.urls import patterns, url

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

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

        urlpatterns = patterns('',
            url(r'^$',
                wrap(self.changelist_view),
                name='%s_%s_changelist' % info),
            url(r'^add/$',
                wrap(self.add_view),
                name='%s_%s_add' % info),
            url(r'^(.+)/history/$',
                wrap(self.history_view),
                name='%s_%s_history' % info),
            url(r'^(.+)/delete/$',
                wrap(self.delete_view),
                name='%s_%s_delete' % info),
            url(r'^(.+)/$',
                wrap(self.change_view),
                name='%s_%s_change' % info),
        )
        return urlpatterns 
Example 67
Project: TESTGIT   Author: B-ROY   File: options.py    Apache License 2.0 5 votes vote down vote up
def media(self):
        extra = '' if settings.DEBUG else '.min'
        js = [
            'core.js',
            'admin/RelatedObjectLookups.js',
            'jquery%s.js' % extra,
            'jquery.init.js'
        ]
        if self.actions is not None:
            js.append('actions%s.js' % extra)
        if self.prepopulated_fields:
            js.extend(['urlify.js', 'prepopulate%s.js' % extra])
        return forms.Media(js=[static('admin/js/%s' % url) for url in js]) 
Example 68
Project: TESTGIT   Author: B-ROY   File: options.py    Apache License 2.0 5 votes vote down vote up
def media(self):
        extra = '' if settings.DEBUG else '.min'
        js = ['jquery%s.js' % extra, 'jquery.init.js', 'inlines%s.js' % extra]
        if self.prepopulated_fields:
            js.extend(['urlify.js', 'prepopulate%s.js' % extra])
        if self.filter_vertical or self.filter_horizontal:
            js.extend(['SelectBox.js', 'SelectFilter2.js'])
        return forms.Media(js=[static('admin/js/%s' % url) for url in js]) 
Example 69
Project: AneMo   Author: jspargo   File: sites.py    GNU General Public License v2.0 5 votes vote down vote up
def password_change(self, request):
        """
        Handles the "change password" task -- both form display and validation.
        """
        from django.contrib.auth.views import password_change
        url = reverse('admin:password_change_done', current_app=self.name)
        defaults = {
            'current_app': self.name,
            'post_change_redirect': url,
            'extra_context': self.each_context(),
        }
        if self.password_change_template is not None:
            defaults['template_name'] = self.password_change_template
        return password_change(request, **defaults) 
Example 70
Project: AneMo   Author: jspargo   File: options.py    GNU General Public License v2.0 5 votes vote down vote up
def media(self):
        extra = '' if settings.DEBUG else '.min'
        js = [
            'core.js',
            'admin/RelatedObjectLookups.js',
            'jquery%s.js' % extra,
            'jquery.init.js'
        ]
        if self.actions is not None:
            js.append('actions%s.js' % extra)
        if self.prepopulated_fields:
            js.extend(['urlify.js', 'prepopulate%s.js' % extra])
        return forms.Media(js=[static('admin/js/%s' % url) for url in js]) 
Example 71
Project: django-xadmin   Author: MarkHoo   File: sites.py    MIT License 4 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 iteritems(self._registry):
            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 72
Project: omni-forms   Author: omni-digital   File: wagtail_hooks.py    MIT License 4 votes vote down vote up
def _omni_form_related(self, form, related_qs, change_action, delete_action):
        """
        Returns a comma delimited list of links for editing and deleting the related form objects

        :param form: OmniForm model instance
        :param related_qs: Queryset of related fields or handlers
        :param change_action: The name of the url change action
        :param delete_action: The name of the url delete action
        :return: comma delimited list of field links
        """
        links = []

        try:
            run_permission_hooks('update', form)
        except PermissionDenied:
            form_locked = True
        else:
            form_locked = False

        for related in related_qs:
            edit_url = self.url_helper.get_action_url(
                change_action,
                str(form.pk),
                str(related.pk)
            )

            delete_url = self.url_helper.get_action_url(
                delete_action,
                str(form.pk),
                str(related.pk)
            )

            links.append(render_to_string(
                'modeladmin/omniforms/wagtail/includes/related_controls.html',
                {
                    'button_text': related,
                    'edit_url': edit_url,
                    'delete_url': delete_url,
                    'form_locked': form_locked
                }
            ))
        return mark_safe(''.join(links)) 
Example 73
Project: django-glitter   Author: developersociety   File: admin.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def duplicate_page(self, request, obj_id):
        obj = get_object_or_404(Page, id=obj_id)

        if not self.has_add_permission(request):
            raise PermissionDenied

        if request.method == "POST":
            form = DuplicatePageForm(request.POST or None)
            if form.is_valid():
                new_page = form.save()

                # Use current version if exists if not get the latest
                if obj.current_version:
                    current_version = obj.current_version
                else:
                    current_version = obj.get_latest_version()

                if current_version:

                    # Create a new version
                    new_version = Version(content_object=new_page)
                    new_version.template_name = current_version.template_name
                    new_version.version_number = 1
                    new_version.owner = request.user
                    new_version.save()

                    self.duplicate_content(current_version, new_version)

                return HttpResponseRedirect(
                    reverse('admin:glitter_pages_page_change', args=(new_page.id,))
                )
        else:
            form = DuplicatePageForm(initial={
                'url': obj.url,
                'title': obj.title,
                'parent': obj.parent,
            })
        adminForm = admin.helpers.AdminForm(
            form=form,
            fieldsets=[('Duplicate Page: {}'.format(obj), {
                'fields': DuplicatePageForm.Meta.fields
            })],
            prepopulated_fields=self.get_prepopulated_fields(request, obj),
            readonly_fields=self.get_readonly_fields(request, obj),
            model_admin=self
        )
        context = {
            'adminform': adminForm,
            'opts': obj._meta,
            'change': False,
            'is_popup': False,
            'save_as': False,
            'has_delete_permission': self.has_delete_permission(request, obj),
            'has_add_permission': self.has_add_permission(request),
            'has_change_permission': self.has_change_permission(request, obj),
        }
        return render(
            request, 'admin/pages/page/duplicate_page.html', context
        ) 
Example 74
Project: chattR   Author: patrickstocklin   File: sites.py    GNU General Public License v2.0 4 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += [
                        url(r'^my_view/$', self.admin_view(some_view))
                    ]
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request):
                if request.path == reverse('admin:logout', current_app=self.name):
                    index_path = reverse('admin:index', current_app=self.name)
                    return HttpResponseRedirect(index_path)
                # Inner import to prevent django.contrib.admin (app) from
                # importing django.contrib.auth.models.User (unrelated model).
                from django.contrib.auth.views import redirect_to_login
                return redirect_to_login(
                    request.get_full_path(),
                    reverse('admin:login', current_app=self.name)
                )
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        # We add csrf_protect here so this function can be used as a utility
        # function for any view, without having to repeat 'csrf_protect'.
        if not getattr(view, 'csrf_exempt', False):
            inner = csrf_protect(inner)
        return update_wrapper(inner, view) 
Example 75
Project: chattR   Author: patrickstocklin   File: sites.py    GNU General Public License v2.0 4 votes vote down vote up
def get_urls(self):
        from django.conf.urls import url, include
        # Since this module gets imported in the application's root package,
        # it cannot import models from other applications at the module level,
        # and django.contrib.contenttypes.views imports ContentType.
        from django.contrib.contenttypes import views as contenttype_views

        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'^$', wrap(self.index), name='index'),
            url(r'^login/$', self.login, name='login'),
            url(r'^logout/$', wrap(self.logout), name='logout'),
            url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'),
            url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True),
                name='password_change_done'),
            url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
            url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$', wrap(contenttype_views.shortcut),
                name='view_on_site'),
        ]

        # Add in each model's views, and create a list of valid URLS for the
        # app_index
        valid_app_labels = []
        for model, model_admin in six.iteritems(self._registry):
            urlpatterns += [
                url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls)),
            ]
            if model._meta.app_label not in valid_app_labels:
                valid_app_labels.append(model._meta.app_label)

        # If there were ModelAdmins registered, we should have a list of app
        # labels for which we need to allow access to the app_index view,
        if valid_app_labels:
            regex = r'^(?P<app_label>' + '|'.join(valid_app_labels) + ')/$'
            urlpatterns += [
                url(regex, wrap(self.app_index), name='app_list'),
            ]
        return urlpatterns 
Example 76
Project: opadmin   Author: cc0411   File: sites.py    GNU General Public License v3.0 4 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 iteritems(self._registry):
            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 77
Project: StormOnline   Author: stormsha   File: sites.py    Apache License 2.0 4 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 iteritems(self._registry):
            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 78
Project: heltour   Author: cyanfish   File: admin.py    MIT License 4 votes vote down vote up
def get_urls(self):
        urls = super(SeasonAdmin, self).get_urls()
        my_urls = [
            url(r'^(?P<object_id>[0-9]+)/manage_players/$',
                self.admin_site.admin_view(self.manage_players_view),
                name='manage_players'),
            url(r'^(?P<object_id>[0-9]+)/create_teams/$',
                self.admin_site.admin_view(self.create_teams_view),
                name='create_teams'),
            url(r'^(?P<object_id>[0-9]+)/player_info/(?P<player_name>[\w-]+)/$',
                self.admin_site.admin_view(self.player_info_view),
                name='edit_rosters_player_info'),
            url(r'^(?P<object_id>[0-9]+)/round_transition/$',
                self.admin_site.admin_view(self.round_transition_view),
                name='round_transition'),
            url(r'^(?P<object_id>[0-9]+)/review_nominated_games/$',
                self.admin_site.admin_view(self.review_nominated_games_view),
                name='review_nominated_games'),
            url(r'^(?P<object_id>[0-9]+)/review_nominated_games/select/(?P<nom_id>[0-9]+)/$',
                self.admin_site.admin_view(self.review_nominated_games_select_view),
                name='review_nominated_games_select'),
            url(r'^(?P<object_id>[0-9]+)/review_nominated_games/deselect/(?P<sel_id>[0-9]+)/$',
                self.admin_site.admin_view(self.review_nominated_games_deselect_view),
                name='review_nominated_games_deselect'),
            url(r'^(?P<object_id>[0-9]+)/review_nominated_games/pgn/$',
                self.admin_site.admin_view(self.review_nominated_games_pgn_view),
                name='review_nominated_games_pgn'),
            url(r'^(?P<object_id>[0-9]+)/bulk_email/$',
                self.admin_site.admin_view(self.bulk_email_view),
                name='bulk_email'),
            url(r'^(?P<object_id>[0-9]+)/team_spam/$',
                self.admin_site.admin_view(self.team_spam_view),
                name='team_spam'),
            url(r'^(?P<object_id>[0-9]+)/mod_report/$',
                self.admin_site.admin_view(self.mod_report_view),
                name='mod_report'),
            url(r'^(?P<object_id>[0-9]+)/pre_round_report/$',
                self.admin_site.admin_view(self.pre_round_report_view),
                name='pre_round_report'),
            url(r'^(?P<object_id>[0-9]+)/export_players/$',
                self.admin_site.admin_view(self.export_players_view),
                name='export_players'),
        ]
        return my_urls + urls 
Example 79
Project: AneMo   Author: jspargo   File: sites.py    GNU General Public License v2.0 4 votes vote down vote up
def admin_view(self, view, cacheable=False):
        """
        Decorator to create an admin view attached to this ``AdminSite``. This
        wraps the view and provides permission checking by calling
        ``self.has_permission``.

        You'll want to use this from within ``AdminSite.get_urls()``:

            class MyAdminSite(AdminSite):

                def get_urls(self):
                    from django.conf.urls import patterns, url

                    urls = super(MyAdminSite, self).get_urls()
                    urls += patterns('',
                        url(r'^my_view/$', self.admin_view(some_view))
                    )
                    return urls

        By default, admin_views are marked non-cacheable using the
        ``never_cache`` decorator. If the view can be safely cached, set
        cacheable=True.
        """
        def inner(request, *args, **kwargs):
            if not self.has_permission(request):
                if request.path == reverse('admin:logout', current_app=self.name):
                    index_path = reverse('admin:index', current_app=self.name)
                    return HttpResponseRedirect(index_path)
                # Inner import to prevent django.contrib.admin (app) from
                # importing django.contrib.auth.models.User (unrelated model).
                from django.contrib.auth.views import redirect_to_login
                return redirect_to_login(
                    request.get_full_path(),
                    reverse('admin:login', current_app=self.name)
                )
            return view(request, *args, **kwargs)
        if not cacheable:
            inner = never_cache(inner)
        # We add csrf_protect here so this function can be used as a utility
        # function for any view, without having to repeat 'csrf_protect'.
        if not getattr(view, 'csrf_exempt', False):
            inner = csrf_protect(inner)
        return update_wrapper(inner, view) 
Example 80
Project: AneMo   Author: jspargo   File: sites.py    GNU General Public License v2.0 4 votes vote down vote up
def get_urls(self):
        from django.conf.urls import patterns, url, include
        # Since this module gets imported in the application's root package,
        # it cannot import models from other applications at the module level,
        # and django.contrib.contenttypes.views imports ContentType.
        from django.contrib.contenttypes import views as contenttype_views

        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'^$', wrap(self.index), name='index'),
            url(r'^login/$', self.login, name='login'),
            url(r'^logout/$', wrap(self.logout), name='logout'),
            url(r'^password_change/$', wrap(self.password_change, cacheable=True), name='password_change'),
            url(r'^password_change/done/$', wrap(self.password_change_done, cacheable=True), name='password_change_done'),
            url(r'^jsi18n/$', wrap(self.i18n_javascript, cacheable=True), name='jsi18n'),
            url(r'^r/(?P<content_type_id>\d+)/(?P<object_id>.+)/$', wrap(contenttype_views.shortcut), name='view_on_site'),
        )

        # Add in each model's views, and create a list of valid URLS for the
        # app_index
        valid_app_labels = []
        for model, model_admin in six.iteritems(self._registry):
            urlpatterns += patterns('',
                url(r'^%s/%s/' % (model._meta.app_label, model._meta.model_name), include(model_admin.urls))
            )
            if model._meta.app_label not in valid_app_labels:
                valid_app_labels.append(model._meta.app_label)

        # If there were ModelAdmins registered, we should have a list of app
        # labels for which we need to allow access to the app_index view,
        if valid_app_labels:
            regex = r'^(?P<app_label>' + '|'.join(valid_app_labels) + ')/$'
            urlpatterns += patterns('',
                url(regex, wrap(self.app_index), name='app_list'),
            )
        return urlpatterns