我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.get_version()。
def media(self): # taken from django.contrib.admin.options ModelAdmin extra = '' if settings.DEBUG else '.min' # if VERSION <= (1, 8): if StrictVersion(get_version()) < StrictVersion('1.9'): js = [ 'core.js', 'admin/RelatedObjectLookups.js', 'jquery%s.js' % extra, 'jquery.init.js', ] else: js = [ 'core.js', 'vendor/jquery/jquery%s.js' % extra, 'jquery.init.js', 'admin/RelatedObjectLookups.js', 'actions%s.js' % extra, 'urlify.js', 'prepopulate%s.js' % extra, 'vendor/xregexp/xregexp%s.js' % extra, ] return forms.Media(js=[static('admin/js/%s' % url) for url in js])
def test_create_instance(self): instance = TestEChoiceFieldEStrChoicesModel.objects.create(choice=ETestStrChoices.FIELD1) choice = instance.choice self.assertIsInstance(choice, ETestStrChoices) self.assertIs(choice, ETestStrChoices.FIELD1) self.assertEqual(choice.value, 'value1') self.assertEqual(choice.label, 'Label 1') if StrictVersion(django_version()) < StrictVersion('1.9.0'): self.assertEqual(instance._meta.fields[1].__class__.__name__, 'EChoiceField') else: self.assertEqual(instance._meta.fields[1].__class__.__name__, 'ETestStrChoicesField') self.assertEqual(instance._meta.fields[1].choices, ETestStrChoices.choices()) # Default value self.assertIs(instance._meta.fields[1].default, models.fields.NOT_PROVIDED) self.assertEqual(instance._meta.fields[1].get_default(), '') # to_python() self.assertIsNone(instance._meta.fields[1].to_python(None)) self.assertRaisesMessage(exceptions.ValidationError, '["Value \'foo\' is not a valid choice."]', instance._meta.fields[1].to_python, 'foo') # Custom flatchoices self.assertEqual(instance._meta.fields[1].flatchoices, [(ETestStrChoices.FIELD1, 'Label 1'), (ETestStrChoices.FIELD2, 'Label 2')]) instance.delete()
def test_create_instance(self): instance = TestEChoiceFieldEIntChoicesModel.objects.create(choice=ETestIntChoices.FIELD1) choice = instance.choice self.assertIsInstance(choice, ETestIntChoices) self.assertIs(choice, ETestIntChoices.FIELD1) self.assertEqual(choice.value, 10) self.assertEqual(choice.label, 'Label 1') if StrictVersion(django_version()) < StrictVersion('1.9.0'): self.assertEqual(instance._meta.fields[1].__class__.__name__, 'EChoiceField') else: self.assertEqual(instance._meta.fields[1].__class__.__name__, 'ETestIntChoicesField') self.assertEqual(instance._meta.fields[1].choices, ETestIntChoices.choices()) # Default value self.assertIs(instance._meta.fields[1].default, models.fields.NOT_PROVIDED) self.assertIsNone(instance._meta.fields[1].get_default()) # to_python() self.assertRaisesMessage(exceptions.ValidationError, '["\'foo\' value must be an integer."]', instance._meta.fields[1].to_python, 'foo') # Custom flatchoices self.assertEqual(instance._meta.fields[1].flatchoices, [(ETestIntChoices.FIELD1, 'Label 1'), (ETestIntChoices.FIELD2, 'Label 2')]) instance.delete()
def test_create_instance(self): instance = TestEChoiceFieldEFloatChoicesModel.objects.create(choice=ETestFloatChoices.FIELD1) choice = instance.choice self.assertIsInstance(choice, ETestFloatChoices) self.assertIs(choice, ETestFloatChoices.FIELD1) self.assertEqual(choice.value, 1.0) self.assertEqual(choice.label, 'Label 1') if StrictVersion(django_version()) < StrictVersion('1.9.0'): self.assertEqual(instance._meta.fields[1].__class__.__name__, 'EChoiceField') else: self.assertEqual(instance._meta.fields[1].__class__.__name__, 'ETestFloatChoicesField') self.assertEqual(instance._meta.fields[1].choices, ETestFloatChoices.choices()) # Default value self.assertIs(instance._meta.fields[1].default, models.fields.NOT_PROVIDED) self.assertIs(instance._meta.fields[1].get_default(), None) # to_python() self.assertRaisesMessage(exceptions.ValidationError, '["\'foo\' value must be a float."]', instance._meta.fields[1].to_python, 'foo') # Custom flatchoices self.assertEqual(instance._meta.fields[1].flatchoices, [(ETestFloatChoices.FIELD1, 'Label 1'), (ETestFloatChoices.FIELD2, 'Label 2')]) instance.delete()
def test_create_instance(self): instance = TestEChoiceFieldDefaultEBoolChoicesModel.objects.create(choice=ETestBoolChoices.FIELD1) choice = instance.choice self.assertIsInstance(choice, ETestBoolChoices) self.assertIs(choice, ETestBoolChoices.FIELD1) self.assertTrue(choice.value) self.assertEqual(choice.label, 'Label 1') if StrictVersion(django_version()) < StrictVersion('1.9.0'): self.assertEqual(instance._meta.fields[1].__class__.__name__, 'EChoiceField') else: self.assertEqual(instance._meta.fields[1].__class__.__name__, 'ETestBoolChoicesField') self.assertEqual(instance._meta.fields[1].choices, ETestBoolChoices.choices()) # Default value self.assertTrue(instance._meta.fields[1].default) self.assertIs(instance._meta.fields[1].get_default(), ETestBoolChoices.FIELD1) # to_python() self.assertTrue(instance._meta.fields[1].to_python('foo')) # Custom flatchoices self.assertEqual(instance._meta.fields[1].flatchoices, [(ETestBoolChoices.FIELD1, 'Label 1'), (ETestBoolChoices.FIELD2, 'Label 2')]) instance.delete()
def post_worker_init(worker): """Hook into Gunicorn to display message after launching. This mimics the behaviour of Django's stock runserver command. """ quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C' sys.stdout.write( "Django version {djangover}, Gunicorn version {gunicornver}, " "using settings {settings!r}\n" "Starting development server at {urls}\n" "Quit the server with {quit_command}.\n".format( djangover=django.get_version(), gunicornver=gunicorn.__version__, settings=os.environ.get('DJANGO_SETTINGS_MODULE'), urls=', '.join('http://{0}/'.format(b) for b in worker.cfg.bind), quit_command=quit_command, ), )
def get_searched_permissions(ctypes): """ Return all permissions that should exist for existing contenttypes """ # This will hold the permissions we're looking for as # (content_type, (codename, name)) def __get_all_permissions(options, ctype): # django 1.10 compatibility if StrictVersion(get_version()) < StrictVersion('1.10'): return _get_all_permissions(options, ctype) return _get_all_permissions(options) searched_perms = list() for ctype, klass in ctypes: for perm in __get_all_permissions(klass._meta, ctype): searched_perms.append((ctype, perm)) return searched_perms
def test_render_hidden_fields(self): test_form = TestForm() test_form.helper = FormHelper() test_form.helper.layout = Layout( 'email' ) test_form.helper.render_hidden_fields = True html = render_crispy_form(test_form) self.assertEqual(html.count('<input'), 1) # Now hide a couple of fields for field in ('password1', 'password2'): test_form.fields[field].widget = forms.HiddenInput() html = render_crispy_form(test_form) self.assertEqual(html.count('<input'), 3) self.assertEqual(html.count('hidden'), 2) if django.get_version() < '1.5': self.assertEqual(html.count('type="hidden" name="password1"'), 1) self.assertEqual(html.count('type="hidden" name="password2"'), 1) else: self.assertEqual(html.count('name="password1" type="hidden"'), 1) self.assertEqual(html.count('name="password2" type="hidden"'), 1)
def about(request): LOGGER.debug('About page accessed', request) server_version = connection.pg_version env = ( {'name': 'Python', 'version' : python_version()}, {'name': 'Django', 'version' : django_version()}, {'name': 'PostgreSQL', 'version' : '{:d}.{:d}.{:d}'.format( server_version // 10000, (server_version // 100) % 100, server_version % 100)}, {'name': 'Platforma', 'version' : '{0}-{2}'.format(*uname())}, ) return render( request, 'about.xhtml', {'page_title': 'O aplikaci', 'apps': getappinfo(), 'env': env})
def get_version(self): """ Return the Django version, which should be correct for all built-in Django commands. User-supplied commands can override this method to return their own version. """ return django.get_version()
def create_parser(self, prog_name, subcommand): """ Create and return the ``ArgumentParser`` which will be used to parse the arguments to this command. """ parser = CommandParser( self, prog="%s %s" % (os.path.basename(prog_name), subcommand), description=self.help or None, ) parser.add_argument('--version', action='version', version=self.get_version()) parser.add_argument( '-v', '--verbosity', action='store', dest='verbosity', default=1, type=int, choices=[0, 1, 2, 3], help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output', ) parser.add_argument( '--settings', help=( 'The Python path to a settings module, e.g. ' '"myproject.settings.main". If this isn\'t provided, the ' 'DJANGO_SETTINGS_MODULE environment variable will be used.' ), ) parser.add_argument( '--pythonpath', help='A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".', ) parser.add_argument('--traceback', action='store_true', help='Raise on CommandError exceptions') parser.add_argument( '--no-color', action='store_true', dest='no_color', default=False, help="Don't colorize the command output.", ) self.add_arguments(parser) return parser
def current_versions(request): """return a JSON dict of a selection of keys and their versions """ context = { 'versions': [] } with connection.cursor() as cursor: cursor.execute('select version()') row = cursor.fetchone() value, = row context['versions'].append({ 'key': 'PostgreSQL', 'value': value.split(' on ')[0].replace('PostgreSQL', '').strip() }) context['versions'].append({ 'key': 'Tecken', 'value': dockerflow_get_version(settings.BASE_DIR) }) context['versions'].append({ 'key': 'Django', 'value': get_version(), }) redis_store_info = get_redis_connection('store').info() context['versions'].append({ 'key': 'Redis Store', 'value': redis_store_info['redis_version'] }) try: redis_cache_info = get_redis_connection('default').info() except NotImplementedError: redis_cache_info = {'redis_version': 'fakeredis'} context['versions'].append({ 'key': 'Redis Cache', 'value': redis_cache_info['redis_version'] }) context['versions'].sort(key=lambda x: x['key']) return http.JsonResponse(context)
def get_version(): from pootle import __version__ from translate import __version__ as tt_version from django import get_version as django_version return ('Zing %s (Django %s, Translate Toolkit %s)' % (__version__, django_version(), tt_version.sver))
def test_create_instance_named(self): instance = TestNamedEChoiceFieldEStrChoicesModel.objects.create(choice=ETestStrChoices.FIELD1) choice = instance.choice self.assertIsInstance(choice, ETestStrChoices) self.assertIs(choice, ETestStrChoices.FIELD1) self.assertEqual(choice.value, 'value1') self.assertEqual(choice.label, 'Label 1') if StrictVersion(django_version()) < StrictVersion('1.9.0'): self.assertEqual(instance._meta.fields[1].__class__.__name__, 'EChoiceField') else: self.assertEqual(instance._meta.fields[1].__class__.__name__, 'MyEnumFieldName') self.assertEqual(instance._meta.fields[1].choices, ETestStrChoices.choices()) self.assertIs(instance._meta.fields[1].default, models.fields.NOT_PROVIDED) self.assertEqual(instance._meta.fields[1].get_default(), '') instance.delete()
def test_create_instance_default(self): instance = TestEChoiceFieldDefaultEStrChoicesModel.objects.create(choice=ETestStrChoices.FIELD1) choice = instance.choice self.assertIsInstance(choice, ETestStrChoices) self.assertIs(choice, ETestStrChoices.FIELD1) self.assertEqual(choice.value, 'value1') self.assertEqual(choice.label, 'Label 1') if StrictVersion(django_version()) < StrictVersion('1.9.0'): self.assertEqual(instance._meta.fields[1].__class__.__name__, 'EChoiceField') else: self.assertEqual(instance._meta.fields[1].__class__.__name__, 'ETestStrChoicesField') self.assertEqual(instance._meta.fields[1].choices, ETestStrChoices.choices()) self.assertIs(instance._meta.fields[1].default, ETestStrChoices.FIELD1.value) self.assertIs(instance._meta.fields[1].get_default(), ETestStrChoices.FIELD1) instance.delete()
def test_create_instance_default(self): instance = TestEChoiceFieldDefaultEFloatChoicesModel.objects.create(choice=ETestFloatChoices.FIELD1) choice = instance.choice self.assertIsInstance(choice, ETestFloatChoices) self.assertIs(choice, ETestFloatChoices.FIELD1) self.assertEqual(choice.value, 1.0) self.assertEqual(choice.label, 'Label 1') if StrictVersion(django_version()) < StrictVersion('1.9.0'): self.assertEqual(instance._meta.fields[1].__class__.__name__, 'EChoiceField') else: self.assertEqual(instance._meta.fields[1].__class__.__name__, 'ETestFloatChoicesField') self.assertEqual(instance._meta.fields[1].choices, ETestFloatChoices.choices()) self.assertIs(instance._meta.fields[1].default, ETestFloatChoices.FIELD1.value) self.assertIs(instance._meta.fields[1].get_default(), ETestFloatChoices.FIELD1) instance.delete()
def test_create_instance(self): instance = TestEChoiceCharFieldEStrOrderedChoicesModel.objects.create(choice=ETestStrOrderedChoices.FIELD1) choice = instance.choice self.assertIs(choice, ETestStrOrderedChoices.FIELD1) self.assertEqual(choice.value, 'value3') self.assertEqual(choice.label, 'Label 1') if StrictVersion(django_version()) < StrictVersion('1.9.0'): self.assertEqual(instance._meta.fields[1].__class__.__name__, 'EChoiceField') else: self.assertEqual(instance._meta.fields[1].__class__.__name__, 'ETestStrOrderedChoicesField') self.assertEqual(instance._meta.fields[1].choices, ETestStrOrderedChoices.choices()) self.assertIs(instance._meta.fields[1].default, ETestStrOrderedChoices.FIELD1.value) self.assertIs(instance._meta.fields[1].get_default(), ETestStrOrderedChoices.FIELD1) instance.delete()
def __init__(self, get_response=None): super(ViaHeaderMiddleware, self).__init__(get_response) self.proxies = self.via_proxies or getattr( settings, 'VIA_PROXIES', [] ) or ['Django/%s' % get_version()]
def versions(request): """Add to context the version numbers of relevant apps.""" values = ( ('Python', platform.python_version()), ('Django', django.get_version()), ('Endless Pagination', endless_pagination.get_version()), ) return {'versions': values}
def versions(): return ''' === VERSIONS ====================== Python = {python} Django = {django} =================================== '''.format( python=sys.version.replace('\n', ' '), django=get_version(), )
def __init__(self, config=None, **defaults): if config is None: config = getattr(django_settings, 'ELASTIC_APM', {}) if 'framework_name' not in defaults: defaults['framework_name'] = 'django' defaults['framework_version'] = django.get_version() super(DjangoClient, self).__init__(config, **defaults)
def test_output_can_change(self): creator = IndividualCreatorFactory(pk=5) perms = ['spectator.can_edit_creator',] result = change_object_link_card(creator, perms) self.assertTrue(result['display_link']) if get_version() < StrictVersion('1.9.0'): self.assertEqual(result['change_url'], '/admin/spectator_core/creator/5/') else: self.assertEqual(result['change_url'], '/admin/spectator_core/creator/5/change/')
def JsonResponse(responseData): import django if float(django.get_version()) >= 1.7: from django.http import JsonResponse return JsonResponse(responseData) else: return HttpResponse(json.dumps(responseData), content_type="application/json")
def user_is_authenticated(user): if StrictVersion(django.get_version()) < StrictVersion('1.10'): return user.is_authenticated() return user.is_authenticated
def user_is_anonymous(user): if StrictVersion(django.get_version()) < StrictVersion('1.10'): return user.is_anonymous() return user.is_anonymous
def get_version(self): """ Return the Django version, which should be correct for all built-in Django commands. User-supplied commands should override this method. """ return django.get_version()
def check_if_related_object(model_field): if LooseVersion(get_version()) >= LooseVersion("1.9"): return any(isinstance(model_field, x) for x in (related_descriptors.ForwardManyToOneDescriptor, related_descriptors.ReverseOneToOneDescriptor)) else: return any(isinstance(model_field, x) for x in (related_descriptors.SingleRelatedObjectDescriptor, related_descriptors.ReverseSingleRelatedObjectDescriptor))
def check_if_prefetch_object(model_field): if LooseVersion(get_version()) >= LooseVersion("1.9"): return any(isinstance(model_field, x) for x in (related_descriptors.ManyToManyDescriptor, related_descriptors.ReverseManyToOneDescriptor)) else: return any(isinstance(model_field, x) for x in (related_descriptors.ManyRelatedObjectsDescriptor, related_descriptors.ForeignRelatedObjectsDescriptor, related_descriptors.ReverseManyRelatedObjectsDescriptor))
def get_response_data(self, response): import django from distutils.version import LooseVersion self.assertEqual(200, response.status_code) if LooseVersion(django.get_version()) >= LooseVersion('1.9'): return response.json() return response.data
def django_version(): if django.get_version().startswith('1.8'): return DjangoVersion.DJANGO_18 elif django.get_version().startswith('1.9'): return DjangoVersion.DJANGO_19 elif django.get_version().startswith('1.10'): return DjangoVersion.DJANGO_110 elif django.get_version().startswith('1.11'): return DjangoVersion.DJANGO_111