def get_models(self, options): # Load admin classes. admin.autodiscover() # Get options. app_labels = options["app_label"] # Parse model classes. if len(app_labels) == 0: selected_models = apps.get_models() else: selected_models = set() for label in app_labels: if "." in label: # This is an app.Model specifier. try: model = apps.get_model(label) except LookupError: raise CommandError("Unknown model: {}".format(label)) selected_models.add(model) else: # This is just an app - no model qualifier. app_label = label try: app = apps.get_app_config(app_label) except LookupError: raise CommandError("Unknown app: {}".format(app_label)) selected_models.update(app.get_models()) for model in selected_models: if is_registered(model): yield model
def test_admin(self): """ Admin interface testing ... """ username = self.username password = self.password urls = [] admin.autodiscover() for model, model_admin in admin.site._registry.items(): app_label = model._meta.app_label if app_label in ("mt", "mo", "manager", "accounting"): model_url = "/%(urlBase)sadmin/%(app)s/%(model)s/" % { "urlBase": settings.URL_BASE, "app": app_label, "model": model.__name__.lower(), } urls.append(model_url) for obj in model.objects.all()[:10]: urls.append("%(modelUrl)s%(modelId)s/" % {"modelUrl": model_url, "modelId": obj.id}) c = Client() if not c.login(username=username, password=password): self.fail("Don't login") else: for url in urls: response = c.get(url) self.assertEqual( response.status_code, 200, 'url="%(url)s", response=%(code)d' % {"url": url, "code": response.status_code}, )
def test_get_config_data(self): from django.contrib import admin article = Article.objects.create(title='news_1_app_1_config1', slug='news_1_app_1_config1', section=self.ns_app_1) admin.autodiscover() admin_instance = admin.site._registry[Article] # correct parameter passed by the request request = self.get_page_request(self.page_3, self.user) request.GET = deepcopy(request.GET) request.GET['section'] = self.ns_app_1.pk retrieved = admin_instance.get_config_data(request, article, 'property') self.assertEqual(retrieved, self.ns_app_1.property) # correct parameter passed by the request - no existing object request = self.get_page_request(self.page_3, self.user) request.GET = deepcopy(request.GET) request.GET['section'] = self.ns_app_1.pk retrieved = admin_instance.get_config_data(request, Article(), 'property') self.assertEqual(retrieved, self.ns_app_1.property) # no parameter from request - config retrieved form existing instance request = self.get_page_request(self.page_3, self.user) retrieved = admin_instance.get_config_data(request, article, 'property') self.assertEqual(retrieved, self.ns_app_1.property)
def get_export_models(admin_only=False): """ Gets a list of models that can be exported. """ export_conf = settings.EXPORTDB_EXPORT_CONF.get('models') if export_conf is None: if admin_only: if admin.site._registry == {}: admin.autodiscover() return admin.site._registry.keys() return get_models() else: models = [] not_installed = [] for model, _ in export_conf.items(): app_label, model_class_name = model.split('.') model_class = get_model(app_label, model_class_name) if model_class is not None: models.append(model_class) else: not_installed.append(model) if not_installed: raise ImproperlyConfigured( 'The following models can\'t be exported because they haven\'t ' 'been installed: %s' % u', '.join(not_installed) ) return models
def run_tests(self, *args, **kwargs): """Run the test suite. This is a light wrapper around :py:meth:`~djblets.testing.testrunners.TestRunner.run_tests` that just checks for deprecated options. See that method for arguments. Args: *args (tuple, unused): Positional arguments for the test runner. **kwargs (dict, unused): Keyword arguments for the test runner. Returns: int: The exit code. 0 means all tests passed, while 1 means there were failures. """ if '--with-profiling' in sys.argv: sys.stderr.write('--with-profiling is no longer supported. Use ' '--with-profile instead.\n') sys.exit(1) # Load in all the models for the admin UI, so tests have access to # admin URLS. admin.autodiscover() return super(RBTestRunner, self).run_tests(*args, **kwargs)
def test_apphook_admin(self): from django.contrib import admin admin.autodiscover() admin_instance = admin.site._registry[ExampleConfig] request = self.get_page_request(self.page_3, self.user) # Testing Readonly field self.assertEqual( admin_instance.get_readonly_fields(request), ('type',) ) self.assertEqual( admin_instance.get_readonly_fields(request, self.ns_app_1), ('type', 'namespace') ) # Testing admin output for sample app specific implementation response = admin_instance.change_view(request, str(self.ns_app_1.pk)) try: self.assertContains( response, '<div class="readonly">aldryn_apphooks_config.tests.utils.example.cms_appconfig.ExampleConfig</div>' ) self.assertContains(response, '<div class="readonly">app1</div>') self.assertContains(response, 'value="app1_property"') except AssertionError: self.assertContains( response, '<p>aldryn_apphooks_config.tests.utils.example.cms_appconfig.ExampleConfig</p>' ) self.assertContains(response, '<p>app1</p>') self.assertContains(response, 'name="config-property" type="text" value="app1_property"')
def test_admin(self): from django.contrib import admin admin.autodiscover() admin_instance = admin.site._registry[Article] # testing behavior when more than 1 namespace instance exists - the selection form # should be shown request = self.get_page_request(self.page_3, self.user) response = admin_instance.add_view(request) self.assertContains(response, '$(this).apphook_reload_admin') self.assertContains(response, 'aldryn_apphooks_config') self.assertContains(response, '<option value="1">%s</option>' % self.ns_app_1) self.assertContains(response, '<option value="2">%s</option>' % self.ns_app_2) self.assertContains(response, '<h2>Select app config</h2>') # only one namespace instance exists, the normal changeform is used self.ns_app_2.delete() response = admin_instance.add_view(request) self.assertContains(response, '$(this).apphook_reload_admin') self.assertContains(response, 'aldryn_apphooks_config') self.assertContains(response, '<option value="1" selected="selected">%s</option>' % self.ns_app_1) self.assertContains(response, '<input id="id_published"') self.ns_app_1.app_data.config.published_default = True self.ns_app_1.save() response = admin_instance.add_view(request) self.assertContains(response, '<input checked="checked" id="id_published"')
def test_admin_owner_default(self): from django.contrib import admin admin.autodiscover() # since we now have data migration to create the default # NewsBlogConfig (if migrations were not faked, django >1.7) # we need to delete one of configs to be sure that it is pre selected # in the admin view. if NewsBlogConfig.objects.count() > 1: # delete the app config that was created during test set up. NewsBlogConfig.objects.filter(namespace='NBNS').delete() user = self.create_user() user.is_superuser = True user.save() Person.objects.create(user=user, name=u' '.join( (user.first_name, user.last_name))) admin_inst = admin.site._registry[Article] self.request = self.get_request('en') self.request.user = user self.request.META['HTTP_HOST'] = 'example.com' response = admin_inst.add_view(self.request) option = '<option value="1" selected="selected">%s</option>' self.assertContains(response, option % user.username) self.assertContains(response, option % user.get_full_name())
def autodiscover(self, with_batteries=True, with_modeladmins=True): """ :func:`djam.autodiscover` loops through ``INSTALLED_APPS`` and loads any ``riffs.py`` modules in those apps - similar to the django admin's autodiscovery. On top of that, :mod:`djam` will by default include :class:`ModelRiffs <ModelRiff>` which have been auto-generated from registered ModelAdmins. This can be turned of by passing in ``with_modeladmins=False``. For some commonly-used models (such as ``django.contrib.auth.User``) :mod:`djam` provides a Riff which handles some functionality that would otherwise be lost during the conversion from ModelAdmin to :class:`ModelRiff`. This can be disabled by passing in ``with_batteries=False``. The order that these are loaded is: app riff modules, "batteries", and ModelAdmins. If two riffs are registered using the same namespace, the first one registered will take precedence; any others will be ignored. """ if not self._autodiscovered: from django.conf import settings if with_modeladmins: from django.contrib.admin import autodiscover, site autodiscover() # for app in installed_apps register module for app in settings.INSTALLED_APPS: # Don't register riffs from djam.riffs. if app == 'djam': continue mod = import_module(app) before_import = self._riffs.copy() try: self.register_module('{0}.riffs'.format(app)) except: # Reset riffs registry. self._riffs = before_import # If the app has a riffs module, but something went wrong, # reraise the exception. if module_has_submodule(mod, 'riffs'): raise if with_batteries: self.register_module('djam.batteries') if with_modeladmins: for model in site._registry: try: self.register_model(model) except ValueError: pass self.sort_riffs() self._autodiscovered = True
def get_patterns(self): # self.site.startup() database_ready.send(self.site) urlpatterns = self.get_media_urls() # urlpatterns += patterns( # '', ('^$', self.default_renderer.plugin.get_index_view())) for p in self.site.installed_plugins: if isinstance(p, LinoPlugin): # urlpatterns += p.get_patterns(self) pat = p.get_patterns(self) if p.url_prefix: urlpatterns += patterns( '', url('^' + p.url_prefix + "/?", include(pat))) else: urlpatterns += pat if self.site.django_admin_prefix: # experimental from django.contrib import admin admin.autodiscover() urlpatterns += patterns('', ('^' + self.site.django_admin_prefix[1:] + "/", include(admin.site.urls)) ) return urlpatterns
def update_admin_urls(): """Admin urls set have to be updated or all new registered models will be shown as disabled in admin area""" # Delete the old admin URLs old_pattern = None admin_regex = r'^admin/' project_urls = import_module(settings.ROOT_URLCONF) for url_item in project_urls.urlpatterns: try: if url_item.app_name == 'admin': old_pattern = url_item admin_regex = url_item.regex.pattern project_urls.urlpatterns.remove(url_item) break except AttributeError: # Bypass the non-admin URLconf logger.error('Error when finding and removing old admin URLconf.') # Reload updated admin URLs try: admin.autodiscover() project_urls.urlpatterns.append( url(admin_regex, include(admin.site.urls)) ) except: logger.error('Error when updating new admin URLconfs.') if old_pattern: project_urls.urlpatterns.append(old_pattern)
def load_edc(): if 'test' in sys.argv: f = open(os.path.join( Path(os.path.dirname(os.path.realpath(__file__))).ancestor(1).child('td_maternal').child('tests'), 'test_randomization.csv')) # else: # f = open(os.path.join( # Path(os.path.dirname(os.path.realpath(__file__))).ancestor(2).child('etc'), 'randomization.csv')) # for index, line in enumerate(f.readlines()): # if index == 0: # continue # seq, drug_assignment = line.split(',') # RandomizationItem.objects.get_or_create(name=seq, field_name=drug_assignment) edc_base_startup() site_lab_profiles.autodiscover() AppConfiguration(lab_profiles=site_lab_profiles).prepare() site_visit_schedules.autodiscover() site_visit_schedules.build_all() site_rule_groups.autodiscover() data_manager.prepare() site_sections.autodiscover() site_sections.update_section_lists() site_model_callers.autodiscover() admin.autodiscover()
def test_config_select(self): from django.contrib import admin article = Article.objects.create(title='news_1_app_1_config1', slug='news_1_app_1_config1', section=self.ns_app_1) admin.autodiscover() admin_instance = admin.site._registry[Article] # no object is set, no parameter passed through the request, two namespaces request = self.get_page_request(self.page_3, self.user) value = admin_instance._app_config_select(request, None) self.assertEqual(value, None) # object is set, no parameter passed through the request, two namespaces request = self.get_page_request(self.page_3, self.user) value = admin_instance._app_config_select(request, article) self.assertEqual(value, article.section) self.ns_app_2.delete() # no object is set, no parameter passed through the request, one namespace request = self.get_page_request(self.page_3, self.user) value = admin_instance._app_config_select(request, None) self.assertEqual(value, self.ns_app_1)
def setUp(self): """ Create credential and associated superuser """ self.cred = Credential('admin', 'adminpass') self.superuser = create_superuser_from_cred(self.cred) admin.autodiscover()
def test_install_from_admin_site(self): site = ResourceSite() admin.autodiscover() site.install_models_from_site(admin.site) self.assertTrue(site.registry)
def add_admin(self, url): if not UrlList.admin_added: admin.autodiscover() self.include(url, admin.site.urls, 'admin') UrlList.admin_added = True
def register_app_urls(app_name): urlpatterns.append(app_url(app_name)) import_app_rest(app_name) rest_api.register_app_urls(app_name) from django.contrib import admin admin.autodiscover() print 'app urls registerd.'
def configure(**extra): from django.conf import settings os.environ["DJANGO_SETTINGS_MODULE"] = "hvad.test_utils.cli" defaults = dict( CACHE_BACKEND="locmem:///", DEBUG=True, TEMPLATE_DEBUG=True, DATABASE_SUPPORTS_TRANSACTIONS=True, DATABASES={"default": config(default="sqlite://localhost/hvad.db")}, TEST_DATABASE_CHARSET="utf8", TEST_DATABASE_COLLATION="utf8_general_ci", SITE_ID=1, USE_I18N=True, MEDIA_ROOT="/media/", STATIC_ROOT="/static/", MEDIA_URL="/media/", STATIC_URL="/static/", ADMIN_MEDIA_PREFIX="/static/admin/", EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend", SECRET_KEY="key", TEMPLATE_LOADERS=( "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", "django.template.loaders.eggs.Loader", ), TEMPLATE_DIRS=[os.path.abspath(os.path.join(os.path.dirname(__file__), "project", "templates"))], MIDDLEWARE_CLASSES=[ "django.contrib.sessions.middleware.SessionMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.doc.XViewMiddleware", "django.middleware.csrf.CsrfViewMiddleware", ], INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.admin", "django.contrib.sites", "django.contrib.staticfiles", "hvad", "hvad.test_utils.project.app", "hvad.test_utils.project.alternate_models_app", ], LANGUAGE_CODE="en", LANGUAGES=(("en", "English"), ("ja", u"日本語")), JUNIT_OUTPUT_DIR="junit-dj%s-py%s" % (DJANGO_VERSION, PYTHON_VERSION), ROOT_URLCONF="hvad.test_utils.project.urls", PASSWORD_HASHERS=("django.contrib.auth.hashers.MD5PasswordHasher",), ) defaults.update(extra) settings.configure(**defaults) from django.contrib import admin admin.autodiscover()
def setUp(self): try: del admin.site._registry[MyTestModel] except KeyError: pass admin.site.register(MyTestModel, MyTestModelAdmin) admin.autodiscover() self.model_admin = admin.site._registry.get(MyTestModel)
def test_all_our_models_use_our_admin(self): admin.autodiscover() for model, modeladmin in admin.site._registry.iteritems(): # skip third party modules if model.__module__.split('.')[0] in THIRD_PARTY_MODULES: continue if issubclass(model, AbstractTrashBinModel): self.assertTrue(issubclass(type(modeladmin), LibyaAdminModel), "%s needs to use LibyaAdminModel" % model)
def scrape(spider, **kwargs): from django.contrib import admin admin.autodiscover() with transaction.atomic(): process = CrawlerProcess(DEFAULT_CRAWLER_OPTIONS) process.crawl(spider, **kwargs) # the script will block here until the crawling is finished process.start() return
def test_admin(self): """ Checking for ADRest models are registered. """ from django.contrib import admin admin.autodiscover() from adrest.models import AccessKey self.assertTrue(AccessKey in admin.site._registry) from adrest.models import Access self.assertTrue(Access in admin.site._registry)
def configure_urls(self, cls, urls): from django.conf.urls import patterns, url, include from django.contrib import admin admin.autodiscover() urls += patterns('', url(self.prefix, include(admin.site.urls)), )
def add_admin(self, url): from django.contrib import admin if not UrlList.admin_added: admin.autodiscover() self.include(url, admin.site.urls, 'admin') UrlList.admin_added = True
def __init__(self): self._model = None self._fields = None self._model_admin = None self._model_fields = None self._visit_definition = None admin.autodiscover() site_visit_schedules.autodiscover() site_visit_schedules.build_all() site_rule_groups.autodiscover()
def get_admin(base=admin_base): from django.contrib import admin admin.autodiscover() patterns = [ url(r'^{0}'.format(base), include(admin.site.urls)), ] return patterns
def main(): if django.VERSION >= (1, 7): django.setup() if not os.path.exists(os.path.join(here, 'testapp/migrations/0001_initial.py')): call_command('makemigrations') from django.contrib import admin admin.autodiscover() from django.test.runner import DiscoverRunner runner = DiscoverRunner(failfast=True, verbosity=int(os.environ.get('DJANGO_DEBUG', 1))) failures = runner.run_tests(['testapp'], interactive=True) sys.exit(failures)
def test_bug_8245(self): # The first time autodiscover is called, we should get our real error. with self.assertRaises(Exception) as cm: admin.autodiscover() self.assertEqual(str(cm.exception), "Bad admin module") # Calling autodiscover again should raise the very same error it did # the first time, not an AlreadyRegistered error. with self.assertRaises(Exception) as cm: admin.autodiscover() self.assertEqual(str(cm.exception), "Bad admin module")
def scrape(spider, **kwargs): from django.contrib import admin admin.autodiscover() with transaction.atomic(), reversion.create_revision(): process = CrawlerProcess(DEFAULT_CRAWLER_OPTIONS) process.crawl(spider, **kwargs) # the script will block here until the crawling is finished process.start() createinitialrevisions.Command().handle( comment='Initial version', batch_size=500) return
def main(): from django.conf import settings settings.configure( DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:' } }, INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'versioning', ], MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "versioning.middleware.VersioningMiddleware", ], STATIC_URL = '/static/', TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner', TEMPLATE_DIRS = [], DEBUG = True, TEMPLATE_DEBUG = True, ROOT_URLCONF = 'runtests', ) from django.conf.urls import patterns, include, url from django.contrib import admin global urlpatterns urlpatterns = patterns( '', url(r'^admin/', include(admin.site.urls)), url(r'^versioning/', include('versioning.urls')), ) admin.autodiscover() # Run the test suite, including the extra validation tests. from django.test.utils import get_runner TestRunner = get_runner(settings) test_runner = TestRunner(verbosity=1, interactive=False, failfast=False) failures = test_runner.run_tests(['versioning']) sys.exit(failures)
from django.conf import settings from django.conf.urls.defaults import patterns, include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.http import HttpResponse from django_browserid.admin import site as browserid_admin_site from funfactory.monkeypatches import patch patch() # Apply funfactory monkeypatches. admin.autodiscover() # Discover admin.py files for the admin interface. # Copy ModelAdmin entries from the default admin site. browserid_admin_site.copy_registry(admin.site) urlpatterns = patterns('', (r'', include('nucleus.base.urls')), url(r'^admin/', include(browserid_admin_site.urls)), url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'), url(r'^rna/', include('rna.urls')), (r'', include('django_browserid.urls')), (r'^robots\.txt$', lambda r: HttpResponse( "User-agent: *\n%s: /" % 'Allow' if settings.ENGAGE_ROBOTS else 'Disallow' , mimetype="text/plain" ) ),
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin ###comment these 3 should work admin.autodiscover() ### urlpatterns = patterns('', # Examples: # url(r'^$', 'mysite.views.home', name='home'), # url(r'^mysite/', include('mysite.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), ### url(r'^menus/', include('menus.urls')), #####added to try n sync with menus.urls )
from django.conf.urls.defaults import * from dom.selector.views import * # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns( '', (r'^$', formview), # Examples: # url(r'^$', 'dom.views.home', name='home'), # url(r'^dom/', include('dom.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), )
1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin #from AutoMan.view import hello,greet,indexPage from AutoMan import view #from AutoMan import books #import AutoMan.view from django.contrib import admin admin.autodiscover(); urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello/$',view.hello), url(r'^index/$',view.indexPage), url(r'^greet/name/([A-Za-z]*)/$',view.greet), # url(r'^search-form/$',books.search_form), # url(r'^search/$',books.search), # url(r'^edit/$',view.compilePage), # url(r'^link/$',view.returnJson), url(r'^hint/$',view.hint), # url(r'^edit/$',view.edit), url(r'^save/$',view.save), url(r'^compile/$',view.compileFun), url(r'^$',view.compileFun),
Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from myapp import views urlpatterns = [ path('admin/', admin.site.urls), #path('hello/', 'myapp.views.hello',name = 'hello'), path('', views.hello, name="hello"), path('myapp/', include('myapp.urls')), ] ''' old version code -for old django 1.9 h from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^hello/', 'myapp.views.hello', name = 'hello') ]