我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.urls.url()。
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
def setUp(self): def test_view(): pass # pragma: no cover root_patterns = [ url(r'^foo/$', url, name='foo'), url(r'^((?:[\w\-]+/)*)$', url, name='wagtail_serve'), url(r'^bar/$', url, name='bar'), ] self.patcher = patch.object( wagtail.wagtailcore.urls, 'urlpatterns', root_patterns ) self.patcher.start() self.addCleanup(self.patcher.stop) reload(wagtailsharing.urls) self.urlpatterns = wagtailsharing.urls.urlpatterns
def test_coreapi_schema_compatible(self): schema_generator = SchemaGenerator( title='Test View', patterns=urlpatterns2) schema = schema_generator.get_schema() expected = coreapi.Document( url='', title='Test View', content={ 'example-view': { 'create': coreapi.Link( url='/example-view/', action='post', description=description_format(ExampleView.__doc__, None, ), fields=[]), 'read': coreapi.Link( url='/example-view/', action='get', description=description_format(ExampleView.__doc__, None, ), fields=[]) } }) self.assertEquals(schema, expected)
def response_change(self, request, obj): """ Overrides the default to be able to forward to the directory listing instead of the default change_list_view """ if ( request.POST and '_continue' not in request.POST and '_saveasnew' not in request.POST and '_addanother' not in request.POST ): if obj.parent: url = reverse('admin:filer-directory_listing', kwargs={'folder_id': obj.parent.id}) else: url = reverse('admin:filer-directory_listing-root') url = "{0}{1}".format( url, admin_url_params_encoded(request), ) return HttpResponseRedirect(url) return super(FolderAdmin, self).response_change(request, obj)
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 = { '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 request.current_app = self.name return password_change(request, **defaults)
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) wrapper.model_admin = self 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'^(.+)/change/$', wrap(self.change_view), name='%s_%s_change' % info), # For backwards compatibility (was the change url before 1.9) url(r'^(.+)/$', wrap(RedirectView.as_view( pattern_name='%s:%s_%s_change' % ((self.admin_site.name,) + info) ))), ] return urlpatterns
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
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 PasswordChangeView url = reverse('admin:password_change_done', current_app=self.name) defaults = { 'form_class': AdminPasswordChangeForm, 'success_url': 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 request.current_app = self.name return PasswordChangeView.as_view(**defaults)(request)
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: """ tree = pyraml.parser.load(raml_filepath) resource_map = _get_resource_for_tree(tree) patterns = _generate_patterns(resource_map, function_map) return patterns
def no_redirect(pattern, locale_prefix=True, re_flags=None): """ Return a url matcher that will stop the redirect middleware and force Django to continue with regular URL matching. For use when you have a URL pattern you want to serve, and a broad catch-all pattern you want to redirect. :param pattern: regex URL patter that will definitely not redirect. :param locale_prefix: prepend the locale matching pattern. :param re_flags: a string of any of the characters: "iLmsux". Will modify the `pattern` regex based on the documented meaning of the flags (see python re module docs). :return: """ if locale_prefix: pattern = pattern.lstrip('^/') pattern = LOCALE_RE + pattern if re_flags: pattern = '(?{})'.format(re_flags) + pattern def _view(request, *args, **kwargs): return None return url(pattern, _view)
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
def get_urls(self): """ Generate the list of URL patterns, including a default root view for the API, and appending `.json` style format suffixes. """ urls = super(DefaultRouter, self).get_urls() if self.include_root_view: if self.schema_title: view = self.get_schema_root_view(api_urls=urls) else: view = self.get_api_root_view(api_urls=urls) root_url = url(r'^$', view, name=self.root_view_name) urls.append(root_url) if self.include_format_suffixes: urls = format_suffix_patterns(urls) return urls
def mock_urlopen(request, cafile=None): response = {} url = request.get_full_url() try: data = xmltodict.parse(request.data) except: data = {} try: if url == 'https://api.sofort.com/api/xml': if 'transaction_request' in data: if 'transaction' in data['transaction_request']: if data['transaction_request']['transaction'] == '123-abc-received': response = TEST_RESPONSES['123-abc-received'] elif data['transaction_request']['transaction'] == '123-abc-loss': response = TEST_RESPONSES['123-abc-loss'] except KeyError: response = False result = MockResponse(response) else: result = MockResponse(response) result.headers.update({'Content-type': 'application/xml; charset=UTF-8'}) result.headers.update({'Accept': 'application/xml; charset=UTF-8'}) return result
def setup_columns(self, *args, **kwargs): self.add_column(title="Machine", hideable=False, orderable=True, field_name="name") self.add_column(title="Description", field_name="description") select_btn_template = ''' <a href="{% url "project" extra.pid %}?setMachine={{data.name}}" class="btn btn-default btn-block select-machine-btn {% if extra.in_prj == 0%}disabled{%endif%}">Select machine</a> ''' self.add_column(title="Select machine", static_data_name="add-del-layers", static_data_template=select_btn_template)
def setup_columns(self, *args, **kwargs): name_link_template = ''' <a href="{% url 'recipedetails' extra.pid data.pk %}">{{data.name}}</a> ''' self.add_column(title="Image recipe", help_text="When you build an image recipe, you get an " "image: a root file system you can" "deploy to a machine", hideable=False, orderable=True, static_data_name="name", static_data_template=name_link_template, field_name="name") super(ImageRecipesTable, self).setup_columns(*args, **kwargs) self.add_column(title="Customise", hideable=False, filter_name="in_current_project", static_data_name="customise-or-add-recipe", static_data_template='{% include "customise_btn.html" %}')
def partner_patterns(*pattern_list): """Mark the url patterns used with partners.""" for pattern in pattern_list: if isinstance(pattern, RegexURLPattern): _partner_pattern_names.add(pattern.name) elif isinstance(pattern, RegexURLResolver): for url_pattern in pattern.url_patterns: ns = '' if pattern.app_name: ns = ns + pattern.app_name + ':' if pattern.namespace: ns = ns + pattern.namespace + ':' _partner_pattern_names.add(ns + url_pattern.name) else: raise Exception() return url(r'^(?P<partner_slug>[-\w_]+)/', include(list(pattern_list)))
def test_partner_patterns(partner_factory): partner = partner_factory(slug='automatic_partner', auto_set_partner=False) set_partner(partner) urlconf = (partner_patterns( *base_urlconf ),) url_ = reverse('static-url', urlconf) assert url_ == '/automatic_partner/static/' url_ = reverse('static-url', urlconf, kwargs=dict( partner_slug='manual_partner')) assert url_ == '/manual_partner/static/' url_ = reverse('dynamic-url', urlconf, kwargs=dict(pk=1)) assert url_ == '/automatic_partner/dynamic/1/' url_ = reverse('dynamic-url', urlconf, kwargs=dict( partner_slug='manual_partner', pk=1)) assert url_ == '/manual_partner/dynamic/1/' url_ = reverse('dynamic-url', urlconf, args=(1,)) assert url_ == '/automatic_partner/dynamic/1/'
def test_partner_patterns_instance_ns(partner_factory): partner = partner_factory(slug='automatic_partner', auto_set_partner=False) set_partner(partner) urlconf = (partner_patterns( url(r'^ns/', include(base_urlconf, namespace='instance-ns')) ),) url_ = reverse('instance-ns:static-url', urlconf) assert url_ == '/automatic_partner/ns/static/' url_ = reverse('instance-ns:static-url', urlconf, kwargs=dict( partner_slug='manual_partner')) assert url_ == '/manual_partner/ns/static/' url_ = reverse('instance-ns:dynamic-url', urlconf, kwargs=dict(pk=1)) assert url_ == '/automatic_partner/ns/dynamic/1/' url_ = reverse('instance-ns:dynamic-url', urlconf, kwargs=dict( partner_slug='manual_partner', pk=1)) assert url_ == '/manual_partner/ns/dynamic/1/' url_ = reverse('instance-ns:dynamic-url', urlconf, args=(1,)) assert url_ == '/automatic_partner/ns/dynamic/1/'
def get_urls(self): urls = super().get_urls() info = self.model._meta.app_label, self.model._meta.model_name csv_urls = [ url( r'^upload_csv/(?P<group_id>\d+)/$', self.admin_site.admin_view(self.upload_csv), name='%s_%s_upload_csv' % info ), url( r'^download_csv/(?P<group_id>\d+)/$', self.admin_site.admin_view(self.download_csv), name='%s_%s_download_csv' % info ), ] return csv_urls + urls
def network_icon(self, obj): icons_url = staticfiles_storage.url('social_networks/img/admin_icons.svg') try: icon_code, icon_title = next(( network_tuple for network_tuple in conf.ALL_NETWORKS if network_tuple[0] == obj.network )) except StopIteration: return offset = 100 / (len(SPRITE_ICONS) - 1) * SPRITE_ICONS.index(icon_code) return """ <span style="display:inline-block; width:21px; height:20px; margin:0; background:url(%s) %0.4f%% 0; vertical-align:middle;" title="%s"/>""" % ( icons_url, offset, icon_title )
def changelist_view(self, request, extra_context=None): if extra_context is None: extra_context = {} jobs = [] for job_name in self.get_job_names(): if self.show_job_on_changelist(job_name): jobs.append({ 'title': self.get_job_title(job_name), 'url': self.get_workflow_start_url(job_name), 'css': ' '.join(self.get_changelist_link_css(job_name)) }) extra_context.update({ 'changelist_jobs': jobs }) return super(JobAdminMixin, self).changelist_view(request, extra_context)
def changeform_view(self, request, object_id=None, form_url='', extra_context=None): if extra_context is None: extra_context = {} jobs = [] for job_name in self.get_job_names(): if self.show_job_on_changeform(job_name) and object_id: jobs.append({ 'title': self.get_job_title(job_name), 'url': self.get_workflow_start_url(job_name, object_id=object_id), 'css': ' '.join(self.get_changeform_link_css(job_name)) }) extra_context.update({ 'changeform_jobs': jobs }) return super(JobAdminMixin, self).changeform_view(request, object_id=object_id, form_url=form_url, extra_context=extra_context)
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)
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
def get_urls(self): """ Generate the list of URL patterns, including a default root view for the API, and appending `.json` style format suffixes. """ urls = [] if self.include_root_view: root_url = url(r'^$', self.get_api_root_view(), name=self.root_view_name) urls.append(root_url) default_urls = super(DefaultRouter, self).get_urls() urls.extend(default_urls) if self.include_format_suffixes: urls = format_suffix_patterns(urls) return urls
def _generateMountURLs(self, path, mapping, app=None): p = path @csrf_exempt # dispatcher (view) needs to be csrf exempted def dispatcher(req, *args, **kwargs): service = mapping.get(req.method, None) or mapping.get('*', None) if service: return service['src'](req, *args, **kwargs) else: return HttpResponseNotAllowed(mapping.keys()) # relative path if not p.startswith('/'): if app: p = '/'.join([app, p]) # add app name prefix in addition to 'path' # absolute path else: p = p[1:] # remove leading '/' # support reverse() in template for <a href=...> and <form action=...> reversable = mapping.get('*', None) or mapping.get('GET', None) or mapping.get('POST', None) return url(r'^{}$'.format(p), dispatcher, name='.'.join([reversable['src'].__module__, reversable['name']]) if reversable else None)
def register_modelview(self, path, admin_view_class, name): """ ?? ModelAdminView ?? :param path: url?? :param admin_view_class: ??? ModelAdminView ?? :param name: view???url name, ?????%%s, ?????? app_label?module_name ?? Model Base Admin View ???????xadmin??? Model ???? Admin View???????? Model ??? """ # ??????????? from xadmin.views.base import BaseView if issubclass(admin_view_class, BaseView): self._registry_modelviews.append((path, admin_view_class, name)) else: raise ImproperlyConfigured(u'The registered view class %s isn\'t subclass of %s' %(admin_view_class.__name__, BaseView.__name__))
def media(self): extra = '' if settings.DEBUG else '.min' js = [ 'core.js', 'admin/RelatedObjectLookups.js', 'jquery%s.js' % extra, 'jquery.init.js' ] css = [ 'block_admin.css' ] # 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], css={'all': [static('admin/css/%s' % url) for url in css]} )