Python django.conf.urls.url() Examples

The following are 30 code examples of django.conf.urls.url(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.conf.urls , or try the search function .
Example #1
Source Project: GTDWeb   Author: lanbing510   File: sites.py    License: GNU General Public License v2.0 7 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 #2
Source Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 6 votes vote down vote up
def get_urls(self):
        urls = super(DocumentSetAdmin, self).get_urls()

        extra_urls = patterns('',
                              url('^(?P<document_set_id>\d+)/answers/$',
                                  self.admin_site.admin_view(self.answers_view),
                                  name="document_set_answers_csv"),
                              url('^(?P<document_set_id>\d+)/add_documents/$',
                                  self.admin_site.admin_view(self.add_documents_view),
                                  name='document_set_add_documents'),
                              url('^(?P<document_set_id>\d+)/update_canons/$',
                                  self.admin_site.admin_view(self.update_canons_view),
                                  name='document_set_update_canons'),
                              url('^(?P<document_set_id>\d+)/reverify_documents/$',
                                self.admin_site.admin_view(self.reverify_documents_view),
                                  name='document_set_reverify_documents')
                             )

        return extra_urls + urls 
Example #3
Source Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 6 votes vote down vote up
def answers(self, obj):
        field_template = "<li><input type=\"checkbox\" data-change-url=\"%s\" data-field-entry=\"%d\" data-document=\"%d\" data-entry-value=\"%s\" %s><span class=\"%s\">%s</span>: <strong>%s</strong> - <em>%s</em></li>"
        rv = '<ul>'
        form_fields = obj.form.fields.order_by('id').all()
        rv += ''.join([field_template % (reverse('admin:document_set_field_entry_change', args=(obj.document.pk, e.pk,)),
                                         e.pk,
                                         obj.document.pk,
                                         e.value,
                                         'checked' if e.verified else '',
                                         'verify' if f.verify else '',
                                         f.label,
                                         e.value,
                                         e.assigned_canonical_value())
                       for f, e in zip(form_fields,
                                       obj.fields.order_by('field_id').all())])
        rv += '</ul>'

        return mark_safe(rv) 
Example #4
Source Project: StormOnline   Author: stormsha   File: sites.py    License: 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 #5
Source Project: heltour   Author: cyanfish   File: admin.py    License: 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 #6
Source Project: GTDWeb   Author: lanbing510   File: options.py    License: 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 #7
Source Project: waliki   Author: mgaitan   File: urls.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def waliki_urls():
    base = [url(r'^$', home, name='waliki_home'),
            url(r'^_new$', new, name='waliki_new'),
            url(r'^_get_slug$', get_slug, name='waliki_get_slug'),
            url(r'^_preview$', preview, name='waliki_preview')]

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

    base += [url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')/edit$', edit, name='waliki_edit'),
             url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')/delete$',
                 delete, name='waliki_delete'),
             url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')/move$',
                 move, name='waliki_move'),
             url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')/raw$',
                 detail, {'raw': True}, name='waliki_detail_raw'),
             url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')$',
                 detail, name='waliki_detail'),
             ]
    return base 
Example #8
Source Project: jet-bridge   Author: jet-admin   File: router.py    License: MIT License 6 votes vote down vote up
def add_handler(self, view, url_, actions):
        class ActionHandler(view):
            pass

        for method, method_action in actions.items():
            def create_action_method(action):
                def action_method(inner_self, *args, **kwargs):
                    try:
                        inner_self.view.action = action
                        inner_self.before_dispatch()
                        response = inner_self.view.dispatch(action, *args, **kwargs)
                        return inner_self.write_response(response)
                    except Exception:
                        exc_type, exc, traceback = sys.exc_info()
                        response = inner_self.view.error_response(exc_type, exc, traceback)
                        return inner_self.write_response(response)
                    finally:
                        inner_self.on_finish()

                return action_method

            func = create_action_method(method_action)
            setattr(ActionHandler, method, func)

        self.urls.append(url(url_, ActionHandler.as_view())) 
Example #9
Source Project: jet-bridge   Author: jet-admin   File: router.py    License: MIT License 6 votes vote down vote up
def add_route_extra_actions(self, view, route, prefix):
        viewset = view.view_cls
        for attr in dir(viewset):
            method = getattr(viewset, attr)
            bind_to_methods = getattr(method, 'bind_to_methods', None)

            if bind_to_methods is None:
                continue

            detail = getattr(method, 'detail', None)

            if detail != route['detail']:
                continue

            extra_actions = dict(map(lambda x: (x, attr), bind_to_methods))

            url = '{}{}{}/'.format(prefix, route['path'], attr)
            self.add_handler(view, url, extra_actions) 
Example #10
Source Project: django-cruds   Author: bmihelac   File: urls.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def crud_for_model(model, urlprefix=None):
    """Returns list of ``url`` items to CRUD a model.
    """
    model_lower = model.__name__.lower()

    if urlprefix is None:
        urlprefix = ''
    urlprefix += model_lower + '/'

    urls = crud_urls(
        model,
        list_view=CRUDListView.as_view(model=model),
        create_view=CRUDCreateView.as_view(model=model),
        detail_view=CRUDDetailView.as_view(model=model),
        update_view=CRUDUpdateView.as_view(model=model),
        delete_view=CRUDDeleteView.as_view(model=model),
        url_prefix=urlprefix,
    )
    return urls 
Example #11
Source Project: mozilla-django-oidc   Author: mozilla   File: test_middleware.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def test_no_oidc_token_expiration_forces_renewal(self, mock_random_string):
        mock_random_string.return_value = 'examplestring'

        request = self.factory.get('/foo')
        request.user = self.user
        request.session = {}

        response = self.middleware.process_request(request)

        self.assertEqual(response.status_code, 302)
        url, qs = response.url.split('?')
        self.assertEqual(url, 'http://example.com/authorize')
        expected_query = {
            'response_type': ['code'],
            'redirect_uri': ['http://testserver/callback/'],
            'client_id': ['foo'],
            'nonce': ['examplestring'],
            'prompt': ['none'],
            'scope': ['openid email'],
            'state': ['examplestring'],
        }
        self.assertEqual(expected_query, parse_qs(qs)) 
Example #12
Source Project: weibo-analysis-system   Author: Superbsco   File: sites.py    License: 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 #13
Source Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    License: 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 #14
Source Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    License: MIT License 5 votes vote down vote up
def test_format_api_patterns_url_import(self):
        urls = patterns('', url(r'api/base/path/', include(self.url_patterns)))
        apis = self.urlparser.get_apis(urls)

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

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

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

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

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

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

        self.assertEqual(
            4, sum(api['path'].find('api') != -1 for api in apis))
        self.assertEqual(
            4, sum(api['path'].find('test') != -1 for api in apis)) 
Example #17
Source Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    License: 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 #18
Source Project: py2swagger   Author: Arello-Mobile   File: test_urlparser.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        class FuzzyApiView(APIView):
            def get(self, request):
                pass

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

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

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

        self.project_urls = patterns(
            '',
            url('my_fuzzy_app/', include(fuzzy_app_urls)),
            url('my_shiny_app/', include(shiny_app_urls)),
        ) 
Example #19
Source Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 5 votes vote down vote up
def get_urls(self):
        urls = super(CanonicalFieldEntryLabelAdmin, self).get_urls()

        extra_urls = patterns('',
                              url('^cluster/$',
                                  self.admin_site.admin_view(self.cluster_canons),
                                  name="cluster_canons"),
                                  )
        return extra_urls + urls 
Example #20
Source Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 5 votes vote down vote up
def add_documents_view(self, request, document_set_id):
        """ add a bunch of documents to
         a DocumentSet by uploading a CSV """
        document_set = get_object_or_404(self.model, pk=document_set_id)
        if request.FILES.get('csv_file'):
            # got a CSV, process, check and create
            csvreader = csv.reader(request.FILES.get('csv_file'))

            header_row = csvreader.next()
            if [h.strip() for h in header_row] != ['document_title', 'document_url']:
                messages.error(request,
                               _('Header cells must be document_title and document_url'))


            count = 0
            try:
                with transaction.commit_on_success():
                    for row in csvreader:
                        document_set.documents.create(name=row[0].strip(),
                                                      url=row[1].strip())
                        count += 1
            except:
                messages.error(request,
                               _('Could not create documents'))

                return redirect(reverse('admin:document_set_add_documents',
                                        args=(document_set_id,)))

            messages.info(request,
                          _('Successfully created %(count)d documents') % { 'count': count })

            return redirect(reverse('admin:crowdataapp_documentset_changelist'))

        else:
            return render_to_response('admin/document_set_add_documents.html',
                                      {
                                          'document_set': document_set,
                                          'current_app': self.admin_site.name,
                                      },
                                      RequestContext(request)) 
Example #21
Source Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 5 votes vote down vote up
def user_link(self, obj):
        url = reverse('admin:auth_user_change', args=(obj.user.id,))
        return mark_safe('<a href="%s">%s</a>' % (url, obj.user.get_full_name())) 
Example #22
Source Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 5 votes vote down vote up
def document_set_link(self, obj):
        url = reverse('admin:crowdataapp_documentset_change', args=(obj.document.document_set.id,))
        return mark_safe('<a href="%s">%s</a>' % (url, obj.document.document_set.name)) 
Example #23
Source Project: crowdata   Author: crowdata   File: admin.py    License: MIT License 5 votes vote down vote up
def get_urls(self):
        urls = super(DocumentAdmin, self).get_urls()
        my_urls = patterns('',
                           url('^(?P<document>\d+)/document_set_field_entry/(?P<document_set_field_entry>\d+)/$',
                               self.admin_site.admin_view(self.field_entry_set),
                               name='document_set_field_entry_change')
        )
        return my_urls + urls 
Example #24
Source Project: normandy   Author: mozilla   File: routers.py    License: 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 #25
Source Project: normandy   Author: mozilla   File: test_api.py    License: 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 #26
Source Project: normandy   Author: mozilla   File: test_api.py    License: 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 #27
Source Project: donation-tracker   Author: GamesDoneQuick   File: event.py    License: Apache License 2.0 5 votes vote down vote up
def get_urls(self):
        return super(EventAdmin, self).get_urls() + [
            url(
                'select_event',
                self.admin_site.admin_view(self.select_event),
                name='select_event',
            ),
        ] 
Example #28
Source Project: donation-tracker   Author: GamesDoneQuick   File: event.py    License: Apache License 2.0 5 votes vote down vote up
def get_urls(self):
        return super(SpeedRunAdmin, self).get_urls() + [
            url(
                r'start_run/(?P<run>\d+)',
                self.admin_site.admin_view(self.start_run_view),
                name='start_run',
            ),
        ] 
Example #29
Source Project: StormOnline   Author: stormsha   File: sites.py    License: 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 #30
Source Project: heltour   Author: cyanfish   File: admin.py    License: 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