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 File: urls.py    From waliki with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def waliki_urls():
    base = [url(r'^$', home, name='waliki_home'),
            url(r'^_new$', new, name='waliki_new'),
            url(r'^_get_slug$', get_slug, name='waliki_get_slug'),
            url(r'^_preview$', preview, name='waliki_preview')]

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

    base += [url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')/edit$', edit, name='waliki_edit'),
             url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')/delete$',
                 delete, name='waliki_delete'),
             url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')/move$',
                 move, name='waliki_move'),
             url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')/raw$',
                 detail, {'raw': True}, name='waliki_detail_raw'),
             url(r'^(?P<slug>' + WALIKI_SLUG_PATTERN + ')$',
                 detail, name='waliki_detail'),
             ]
    return base 
Example #2
Source File: sites.py    From GTDWeb with 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 #3
Source File: sites.py    From weibo-analysis-system with MIT License 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

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

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example #4
Source File: admin.py    From heltour with 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 #5
Source File: sites.py    From StormOnline with Apache License 2.0 6 votes vote down vote up
def __init__(self, name='xadmin'):
        self.name = name
        self.app_name = 'xadmin'

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

        self._admin_view_cache = {}

        # self.check_dependencies()

        self.model_admins_order = 0 
Example #6
Source File: urls.py    From django-cruds with 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 #7
Source File: router.py    From jet-bridge with 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 #8
Source File: router.py    From jet-bridge with 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 #9
Source File: test_middleware.py    From mozilla-django-oidc with 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 #10
Source File: admin.py    From crowdata with 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 #11
Source File: admin.py    From crowdata with 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 #12
Source File: options.py    From GTDWeb with 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 #13
Source File: test_middleware.py    From mozilla-django-oidc with Mozilla Public License 2.0 5 votes vote down vote up
def test_expired_token_forces_renewal(self, mock_random_string):
        mock_random_string.return_value = 'examplestring'

        request = self.factory.get('/foo')
        request.user = self.user
        request.session = {
            'oidc_id_token_expiration': time.time() - 10
        }

        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))


# This adds a "home page" we can test against. 
Example #14
Source File: integrations.py    From zulip with Apache License 2.0 5 votes vote down vote up
def get_logo_url(self) -> Optional[str]:
        if self.logo_path is not None:
            return staticfiles_storage.url(self.logo_path)

        return None 
Example #15
Source File: test_middleware.py    From mozilla-django-oidc with Mozilla Public License 2.0 5 votes vote down vote up
def test_expired_token_redirects_to_sso(self, mock_random_string):
        mock_random_string.return_value = 'examplestring'

        client = ClientWithUser()
        client.login(username=self.user.username, password='password')

        # Set expiration to some time in the past
        session = client.session
        session['oidc_id_token_expiration'] = time.time() - 100
        session['_auth_user_backend'] = 'mozilla_django_oidc.auth.OIDCAuthenticationBackend'
        session.save()

        resp = client.get('/mdo_fake_view/')
        self.assertEqual(resp.status_code, 302)

        url, qs = resp.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 #16
Source File: router.py    From jet-bridge with MIT License 5 votes vote down vote up
def add_route_actions(self, view, route, prefix):
        viewset = view.view_cls
        actions = route['method_mapping']
        actions = dict(filter(lambda x: hasattr(viewset, x[1]), actions.items()))

        if len(actions) == 0:
            return

        url = '{}{}'.format(prefix, route['path'])
        self.add_handler(view, url, actions) 
Example #17
Source File: admin.py    From django-fcm with MIT License 5 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)

        urlpatterns = [
            url(r'^send-message/$', wrap(self.send_message_view),
                name=self.build_admin_url('send_message'))]
        return urlpatterns + super(DeviceAdmin, self).get_urls() 
Example #18
Source File: admin.py    From django-fcm with MIT License 5 votes vote down vote up
def send_message_action(self, request, queryset):
        ids = queryset.values_list('id', flat=True)
        request.session['device_ids'] = list(ids)
        url = 'admin:%s' % self.build_admin_url('send_message')
        return redirect(url) 
Example #19
Source File: urls.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_urls(self):
        ret = []

        if self.include_root_view:
            root_url = url(r'^$', self.get_api_root_view(),
                           name=self.root_view_name)
            ret.append(root_url)
        for prefix, viewset, basename in self.registry:
            lookup = self.get_lookup_regex(viewset)
            lookup_list = self.get_lookup_regexes(viewset)
            if lookup_list:
                # lookup = lookups[0]
                lookup_list = [u'/'.join(k) for k in lookup_list]
            else:
                lookup_list = [u'']
            routes = self.get_routes(viewset)
            for route in routes:
                mapping = self.get_method_map(viewset, route.mapping)
                if not mapping:
                    continue
                for lookups in lookup_list:
                    regex = route.url.format(
                        prefix=prefix,
                        lookup=lookup,
                        lookups=lookups,
                        trailing_slash=self.trailing_slash,
                        extra=self.get_extra_lookup_regexes(route)
                    )
                    view = viewset.as_view(mapping, **route.initkwargs)
                    name = route.name.format(basename=basename)
                    ret.append(url(regex, view, name=name))
        if self.include_format_suffixes:
            ret = format_suffix_patterns(ret, allowed=['[a-z0-9]+'])
        return ret 
Example #20
Source File: integrations.py    From zulip with Apache License 2.0 5 votes vote down vote up
def __init__(self, name: str, categories: List[str], client_name: Optional[str]=None,
                 logo: Optional[str]=None, secondary_line_text: Optional[str]=None,
                 function: Optional[str]=None, url: Optional[str]=None,
                 display_name: Optional[str]=None, doc: Optional[str]=None,
                 stream_name: Optional[str]=None, legacy: bool=False,
                 config_options: Sequence[Tuple[str, str, Validator[object]]]=[]) -> None:
        if client_name is None:
            client_name = self.DEFAULT_CLIENT_NAME.format(name=name.title())
        super().__init__(
            name,
            client_name,
            categories,
            logo=logo,
            secondary_line_text=secondary_line_text,
            display_name=display_name,
            stream_name=stream_name,
            legacy=legacy,
            config_options=config_options,
        )

        if function is None:
            function = self.DEFAULT_FUNCTION_PATH.format(name=name)

        if isinstance(function, str):
            function = import_string(function)

        self.function = function

        if url is None:
            url = self.DEFAULT_URL.format(name=name)
        self.url = url

        if doc is None:
            doc = self.DEFAULT_DOC_PATH.format(name=name, ext='md')

        self.doc = doc 
Example #21
Source File: urls.py    From django-nyt with Apache License 2.0 5 votes vote down vote up
def get_pattern(app_name=app_name, namespace="nyt"):
    """Every url resolution takes place as "nyt:view_name".
       https://docs.djangoproject.com/en/dev/topics/http/urls/#topics-http-reversing-url-namespaces
    """
    import warnings
    warnings.warn(
        'django_nyt.urls.get_pattern is deprecated and will be removed in next version,'
        ' just use include(\'django_nyt.urls\')', DeprecationWarning
    )
    return include('django_nyt.urls') 
Example #22
Source File: urls.py    From django-nyt with Apache License 2.0 5 votes vote down vote up
def get_pattern(app_name=app_name, namespace="nyt"):
    """Every url resolution takes place as "nyt:view_name".
       https://docs.djangoproject.com/en/dev/topics/http/urls/#topics-http-reversing-url-namespaces
    """
    import warnings
    warnings.warn(
        'django_nyt.urls.get_pattern is deprecated and will be removed in next version,'
        ' just use include(\'django_nyt.urls\')', DeprecationWarning
    )
    return include('django_nyt.urls') 
Example #23
Source File: junebug.py    From casepro with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_url_patterns(self):
        """
        Returns the list of URL patterns that should be registered for this backend.

        :return: a list of URL patterns.
        """
        return [
            url(settings.JUNEBUG_INBOUND_URL, received_junebug_message, name="inbound_junebug_message"),
            url(settings.IDENTITY_STORE_OPTOUT_URL, receive_identity_store_optout, name="identity_store_optout"),
        ] 
Example #24
Source File: junebug.py    From casepro with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_message(self, message):
        if message.urn:
            _, to_addr = self.split_urn(message.urn)
            addresses = [to_addr]
        elif message.contact and message.contact.uuid:
            uuid = message.contact.uuid
            addresses = self.identity_store.get_addresses(uuid)
        else:
            # If we don't have an URN for a message, we cannot send it.
            raise JunebugMessageSendingError("Cannot send message without URN: %r" % message)
        for to_addr in addresses:
            data = {"to": to_addr, "from": self.from_address, "content": message.text}
            self.session.post(self.url, json=data)
            self.hub_message_sender.send_helpdesk_outgoing_message(message, to_addr) 
Example #25
Source File: junebug.py    From casepro with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def url(self):
        return "%s/channels/%s/messages/" % (self.base_url.rstrip("/"), self.channel_id) 
Example #26
Source File: junebug.py    From casepro with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_identities(self, **params):
        """Get the list of identities filtered by the given kwargs."""
        url = "%s/api/v1/identities/?" % self.base_url

        identities = self.get_paginated_response(url, params=params)

        # Users who opt to be forgotten from the system have their details
        # stored as 'redacted'.
        return (IdentityStoreContact(i) for i in identities if i.get("details").get("name") != "redacted") 
Example #27
Source File: junebug.py    From casepro with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_paginated_response(self, url, params={}, **kwargs):
        """Get the results of all pages of a response. Returns an iterator that returns each of the items."""
        while url is not None:
            r = self.session.get(url, params=params, **kwargs)
            data = r.json()
            for result in data.get("results", []):
                yield result
            url = data.get("next", None)
            # params are included in the next url
            params = {} 
Example #28
Source File: toolbox.py    From django-sitemessage with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_sitemessage_urls() -> List:
    """Returns sitemessage urlpatterns, that can be attached to urlpatterns of a project:

        # Example from urls.py.

        from sitemessage.toolbox import get_sitemessage_urls

        urlpatterns = patterns('',
            # Your URL Patterns belongs here.

        ) + get_sitemessage_urls()  # Now attaching additional URLs.

    """
    url_unsubscribe = url(
        r'^messages/unsubscribe/(?P<message_id>\d+)/(?P<dispatch_id>\d+)/(?P<hashed>[^/]+)/$',
        unsubscribe,
        name='sitemessage_unsubscribe'
    )

    url_mark_read = url(
        r'^messages/ping/(?P<message_id>\d+)/(?P<dispatch_id>\d+)/(?P<hashed>[^/]+)/$',
        mark_read,
        name='sitemessage_mark_read'
    )

    if VERSION >= (1, 9):
        return [url_unsubscribe, url_mark_read]

    from django.conf.urls import patterns
    return patterns('', url_unsubscribe, url_mark_read) 
Example #29
Source File: toolbox.py    From django-sitemessage with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_undelivered(to: Optional[str] = None) -> int:
    """Sends a notification email if any undelivered dispatches.

    Returns undelivered (failed) dispatches count.

    :param to: Recipient address. If not set Django ADMINS setting is used.

    """
    failed_count = Dispatch.objects.filter(dispatch_status=Dispatch.DISPATCH_STATUS_FAILED).count()

    if failed_count:
        from sitemessage.shortcuts import schedule_email
        from sitemessage.messages.email import EmailTextMessage

        if to is None:
            admins = settings.ADMINS

            if admins:
                to = list(dict(admins).values())

        if to:
            priority = 999

            register_message_types(EmailTextMessage)

            schedule_email(
                _('You have %(count)s undelivered dispatch(es) at %(url)s') % {
                    'count': failed_count,
                    'url': get_site_url(),
                },
                subject=_('[SITEMESSAGE] Undelivered dispatches'),
                to=to, priority=priority)

            send_scheduled_messages(priority=priority)

    return failed_count 
Example #30
Source File: urls.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def make_routes(template_text):
    return routers.Route(
        url=r'^{prefix}/{%s}{trailing_slash}$' % template_text,
        mapping={
            'get': 'list',
            'post': 'create'
        },
        name='{basename}-list',
        initkwargs={'suffix': 'List'})