Python django.VERSION Examples
The following are 30
code examples of django.VERSION().
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
, or try the search function
.
Example #1
Source File: version.py From bioforum with MIT License | 6 votes |
def get_version(version=None): """Return a PEP 440-compliant version number from VERSION.""" version = get_complete_version(version) # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|rc}N - for alpha, beta, and rc releases main = get_main_version(version) sub = '' if version[3] == 'alpha' and version[4] == 0: git_changeset = get_git_changeset() if git_changeset: sub = '.dev%s' % git_changeset elif version[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'rc'} sub = mapping[version[3]] + str(version[4]) return main + sub
Example #2
Source File: activity_tags.py From stream-django with BSD 3-Clause "New" or "Revised" License | 6 votes |
def render_activity(context, activity, template_prefix='', missing_data_policy=LOG): if hasattr(activity, 'enriched') and not activity.enriched: handle_not_enriched_data(activity, missing_data_policy) return '' if template_prefix != '': template_prefix = '%s_' % template_prefix if 'activities' in activity: template_name = "activity/aggregated/%s%s.html" % (template_prefix, activity['verb']) else: template_name = "activity/%s%s.html" % (template_prefix, activity['verb']) tmpl = loader.get_template(template_name) context['activity'] = activity if django.VERSION < (1, 11): context = Context(context) elif isinstance(context, Context): context = context.flatten() return tmpl.render(context)
Example #3
Source File: creation.py From python-mysql-pool with MIT License | 6 votes |
def sql_table_creation_suffix(self): suffix = [] if django.VERSION < (1, 7): if self.connection.settings_dict['TEST_CHARSET']: suffix.append('CHARACTER SET {0}'.format( self.connection.settings_dict['TEST_CHARSET'])) if self.connection.settings_dict['TEST_COLLATION']: suffix.append('COLLATE {0}'.format( self.connection.settings_dict['TEST_COLLATION'])) else: test_settings = self.connection.settings_dict['TEST'] if test_settings['CHARSET']: suffix.append('CHARACTER SET %s' % test_settings['CHARSET']) if test_settings['COLLATION']: suffix.append('COLLATE %s' % test_settings['COLLATION']) return ' '.join(suffix)
Example #4
Source File: version.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def get_git_changeset(): """Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. """ repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=repo_dir, universal_newlines=True) timestamp = git_log.communicate()[0] try: timestamp = datetime.datetime.utcfromtimestamp(int(timestamp)) except ValueError: return None return timestamp.strftime('%Y%m%d%H%M%S')
Example #5
Source File: version.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
def get_version(version=None): "Returns a PEP 386-compliant version number from VERSION." version = get_complete_version(version) # Now build the two parts of the version number: # major = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha, beta and rc releases major = get_major_version(version) sub = '' if version[3] == 'alpha' and version[4] == 0: git_changeset = get_git_changeset() if git_changeset: sub = '.dev%s' % git_changeset elif version[3] != 'final': mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'} sub = mapping[version[3]] + str(version[4]) return str(major + sub)
Example #6
Source File: test_docstrings.py From sphinxcontrib-django with Apache License 2.0 | 6 votes |
def test_model_fields(self): lines = [] simple_model_path = 'sphinxcontrib_django.tests.test_docstrings.SimpleModel' if django.VERSION < (3, 0): obj = DeferredAttribute(field_name='dummy_field', model=simple_model_path) else: model = import_string(simple_model_path) obj = DeferredAttribute(field=model._meta.get_field('dummy_field')) docstrings._improve_attribute_docs(obj, '{}.dummy_field'.format(simple_model_path), lines) self.assertEqual( lines, [ "**Model field:** dummy field", ], )
Example #7
Source File: docstrings.py From sphinxcontrib-django with Apache License 2.0 | 6 votes |
def _get_field_type(field): if isinstance(field, models.ForeignKey): if django.VERSION >= (2, 0): to = field.remote_field.model if isinstance(to, str): to = _resolve_model(field, to) else: to = field.rel.to if isinstance(to, str): to = _resolve_model(field, to) return u":type %s: %s to :class:`~%s.%s`" % ( field.name, type(field).__name__, to.__module__, to.__name__, ) else: return u":type %s: %s" % (field.name, type(field).__name__)
Example #8
Source File: admin.py From django-model-publisher with BSD 3-Clause "New" or "Revised" License | 6 votes |
def publisher_publish(self, obj): template_name = 'publisher/change_list_publish.html' is_published = False if obj.publisher_linked and obj.is_draft: is_published = True t = loader.get_template(template_name) c = Context({ 'object': obj, 'is_published': is_published, 'has_publish_permission': self.has_publish_permission(self.request, obj), 'publish_url': reverse(self.publish_reverse, args=(obj.pk, )), 'unpublish_url': reverse(self.unpublish_reverse, args=(obj.pk, )), }) if django.VERSION >= (1, 10): return t.render(c.flatten()) else: return t.render(c)
Example #9
Source File: admin.py From django-model-publisher with BSD 3-Clause "New" or "Revised" License | 6 votes |
def publisher_status(self, obj): if not self.has_publish_permission(self.request, obj): return '' template_name = 'publisher/change_list_publish_status.html' publish_btn = None if obj.is_dirty: publish_btn = reverse(self.publish_reverse, args=(obj.pk, )) t = loader.get_template(template_name) c = Context({ 'publish_btn': publish_btn, }) if django.VERSION >= (1, 10): return t.render(c.flatten()) else: return t.render(c)
Example #10
Source File: tests.py From django_migration_testcase with MIT License | 6 votes |
def test_migration2(self): """Same test as test_migration, but this one passes.""" MyModel = self.get_model_before('test_app.MyModel') self.assertEqual(MyModel.__name__, 'MyModel') self.run_migration() ForeignModel = self.get_model_after('test_app.ForeignModel') self.assertEqual(ForeignModel.__name__, 'ForeignModel') # get_model_before/get_model_after seems to not get the same model as # this crazy thing. if django.VERSION >= (2, 0): MyModel = ForeignModel.my.field.related_model else: MyModel = ForeignModel.my.field.rel.to self.assertEqual(MyModel.__name__, 'MyModel') my = MyModel(name='test_my', number=1, double_number=3.14) my.save() ForeignModel(name='test_foreign', my=my)
Example #11
Source File: tests.py From django_migration_testcase with MIT License | 6 votes |
def test_migration2(self): """Same test as test_migration, but this one passes.""" MyModel = self.get_model_before('test_app.MyModel') self.assertEqual(MyModel.__name__, 'MyModel') self.run_migration() ForeignModel = self.get_model_after('test_app.ForeignModel') self.assertEqual(ForeignModel.__name__, 'ForeignModel') # get_model_before/get_model_after seems to not get the same model as # this crazy thing. if django.VERSION >= (2, 0): MyModel = ForeignModel.my.field.related_model else: MyModel = ForeignModel.my.field.rel.to self.assertEqual(MyModel.__name__, 'MyModel') my = MyModel(name='test_my', number=1, double_number=3.14) my.save() ForeignModel(name='test_foreign', my=my)
Example #12
Source File: test_compat.py From django-compat with MIT License | 6 votes |
def test_rollback__without_sid(self): """ Test of rollback without transaction savepoint """ @compat.commit_on_success def db_action(): m = UnimportantThing(pk=4, importance=4) m.save() return m @compat.commit_on_success def db_action_with_rollback(m): m.importance = 5 m.save() compat.rollback() if django.VERSION < (1, 8): # Rollback doesn't work after .save() if an exception isn't thrown return m = db_action() db_action_with_rollback(m) self.assertEqual(UnimportantThing.objects.get(pk=4).importance, 4)
Example #13
Source File: tests.py From django_migration_testcase with MIT License | 6 votes |
def test_migration2(self): """Same test as test_migration, but this one passes.""" MyModel = self.get_model_before('test_app.MyModel') self.assertEqual(MyModel.__name__, 'MyModel') self.run_migration() ForeignModel = self.get_model_after('test_app.ForeignModel') self.assertEqual(ForeignModel.__name__, 'ForeignModel') # get_model_before/get_model_after seems to not get the same model as # this crazy thing. if django.VERSION >= (2, 0): MyModel = ForeignModel.my.field.related_model else: MyModel = ForeignModel.my.field.rel.to self.assertEqual(MyModel.__name__, 'MyModel') my = MyModel(name='test_my', number=1, double_number=3.14) my.save() ForeignModel(name='test_foreign', my=my)
Example #14
Source File: test_compat.py From django-compat with MIT License | 6 votes |
def test_rollback__with_sid(self): """ Test of rollback with transaction savepoint """ @compat.commit_on_success def db_action(): m = UnimportantThing(pk=3, importance=3) m.save() return m @compat.commit_on_success def db_action_with_rollback(m): m.importance = 5 sid = django.db.transaction.savepoint() m.save() compat.rollback(None, sid) if django.VERSION < (1, 5): # Rollback doesn't work with SQLite return m = db_action() db_action_with_rollback(m) self.assertEqual(UnimportantThing.objects.get(pk=3).importance, 3)
Example #15
Source File: response.py From django-excel-response with Apache License 2.0 | 6 votes |
def content(self, value): workbook = None if not bool(value) or not len(value): # Short-circuit to protect against empty querysets/empty lists/None, etc self._container = [] return elif isinstance(value, list): workbook = self._serialize_list(value) elif isinstance(value, QuerySet): workbook = self._serialize_queryset(value) if django.VERSION < (1, 9): if isinstance(value, ValuesQuerySet): workbook = self._serialize_values_queryset(value) if workbook is None: raise ValueError('ExcelResponse accepts the following data types: list, dict, QuerySet, ValuesQuerySet') if self.force_csv: self['Content-Type'] = 'text/csv; charset=utf8' self['Content-Disposition'] = 'attachment;filename="{}.csv"'.format(self.output_filename) workbook.seek(0) workbook = self.make_bytes(workbook.getvalue()) else: self['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' self['Content-Disposition'] = 'attachment; filename="{}.xlsx"'.format(self.output_filename) workbook = save_virtual_workbook(workbook) self._container = [self.make_bytes(workbook)]
Example #16
Source File: version.py From bioforum with MIT License | 6 votes |
def get_git_changeset(): """Return a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. """ repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) git_log = subprocess.Popen( 'git log --pretty=format:%ct --quiet -1 HEAD', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, cwd=repo_dir, universal_newlines=True, ) timestamp = git_log.communicate()[0] try: timestamp = datetime.datetime.utcfromtimestamp(int(timestamp)) except ValueError: return None return timestamp.strftime('%Y%m%d%H%M%S')
Example #17
Source File: checks.py From django-webmention with MIT License | 5 votes |
def new_style_middleware_check(app_configs, **kwargs): errors = [] if django.VERSION[1] >= 10 or django.VERSION[0] > 1: installed_middlewares = getattr(settings, "MIDDLEWARE", []) or [] if "webmention.middleware.WebMentionMiddleware" in installed_middlewares: errors.append( Error( "You are attempting to use an old-style middleware class in the MIDDLEWARE setting", hint="Either use MIDDLEWARE_CLASSES or use webmention.middleware.webmention_middleware instead", id="webmention.E001", ) ) return errors
Example #18
Source File: test_queryset.py From django-livefield with MIT License | 5 votes |
def test_hard_delete(self): deleted = Person.all_objects.all().hard_delete() # Django 1.9+ returns number of deleted rows if django.VERSION >= (1, 9, 0): self.assertEqual(deleted, 5) else: # Older versions do not self.assertIsNone(deleted) self.assertEqual(Person.all_objects.all().count(), 0)
Example #19
Source File: test_compat.py From django-compat with MIT License | 5 votes |
def test_compat(self): compat = import_module('compat') for attribute in compat.__all__: if is_compatible(attribute, django.VERSION[:2]): self.assertTrue(hasattr(compat, attribute))
Example #20
Source File: compat.py From django-compat with MIT License | 5 votes |
def verbatim(parser, token): if django.VERSION >= (1, 5): from django.template.defaulttags import verbatim as verbatim_defaulttag return verbatim_defaulttag(parser, token) # 1.4; not available from django # Source: https://github.com/aljosa/django-verbatim class VerbatimNode(template.Node): def __init__(self, content): self.content = content def render(self, context): return self.content text = [] while 1: token = parser.tokens.pop(0) if token.contents == 'endverbatim': break if token.token_type == template.TOKEN_VAR: text.append('{{ ') elif token.token_type == template.TOKEN_BLOCK: text.append('{% ') text.append(token.contents) if token.token_type == template.TOKEN_VAR: text.append(' }}') elif token.token_type == template.TOKEN_BLOCK: text.append(' %}') return VerbatimNode(''.join(text))
Example #21
Source File: compat.py From django-compat with MIT License | 5 votes |
def url(parser, token): # Django 1.5 adds support of context variables for the url template tag if django.VERSION >= (1, 5): from django.template.defaulttags import url as url_defaulttag else: from django.templatetags.future import url as url_defaulttag return url_defaulttag(parser, token)
Example #22
Source File: tests.py From django-warrant with BSD 3-Clause "New" or "Revised" License | 5 votes |
def login(client, username, password): if DJANGO_VERSION[1] > 10: request = create_request() return client.login(request=request, username=username, password=password) else: return client.login(username=username, password=password)
Example #23
Source File: __init__.py From django-compat with MIT License | 5 votes |
def render_to_string(template_name, context=None, context_instance=_context_instance_undefined, dirs=_dirs_undefined, dictionary=_dictionary_undefined, request=None, using=None): if (context_instance is _context_instance_undefined and dirs is _dirs_undefined and dictionary is _dictionary_undefined): if django.VERSION >= (1, 8): # Call new render_to_string with new arguments return render_to_string_django(template_name, context, request, using) else: # Call legacy render_to_string with new arguments from django.template import RequestContext context_instance = RequestContext(request) if request else None return render_to_string_django(template_name, context, context_instance) else: if django.VERSION >= (1, 10): # Call new render_to_string with legacy arguments raise NotImplementedError('Django compat does not support calling post-1.8 render_to_string with pre-1.8 ' 'keyword arguments') else: # Call legacy render_to_string with legacy arguments if dictionary is _dictionary_undefined: dictionary = {} if context_instance is _context_instance_undefined: context_instance = None return render_to_string_django(template_name, dictionary, context_instance) ### Undocumented ###
Example #24
Source File: __init__.py From django-compat with MIT License | 5 votes |
def create_permissions(*args, **kwargs): # create_permission API changed: skip the create_models (second # positional argument) if we have django 1.7+ and 2+ positional # arguments with the second one being a list/tuple from django.contrib.auth.management import create_permissions as original_create_permissions if django.VERSION < (1, 7) and len(args) > 1 and isinstance(args[1], (list, tuple)): args = args[:1] + args[2:] return original_create_permissions(*args, **kwargs) # Requires django < 1.5 or python >= 2.6
Example #25
Source File: filter.py From django-admin-rangefilter with MIT License | 5 votes |
def get_template(self): if django.VERSION[:2] <= (1, 8): return 'rangefilter/date_filter_1_8.html' else: if csp: return 'rangefilter/date_filter_csp.html' return 'rangefilter/date_filter.html'
Example #26
Source File: version.py From bioforum with MIT License | 5 votes |
def get_docs_version(version=None): version = get_complete_version(version) if version[3] != 'final': return 'dev' else: return '%d.%d' % version[:2]
Example #27
Source File: version.py From bioforum with MIT License | 5 votes |
def get_complete_version(version=None): """ Return a tuple of the django version. If version argument is non-empty, check for correctness of the tuple provided. """ if version is None: from django import VERSION as version else: assert len(version) == 5 assert version[3] in ('alpha', 'beta', 'rc', 'final') return version
Example #28
Source File: version.py From bioforum with MIT License | 5 votes |
def get_main_version(version=None): """Return main version (X.Y[.Z]) from VERSION.""" version = get_complete_version(version) parts = 2 if version[2] == 0 else 3 return '.'.join(str(x) for x in version[:parts])
Example #29
Source File: resources.py From xblock-utils with GNU Affero General Public License v3.0 | 5 votes |
def render_django_template(self, template_path, context=None, i18n_service=None): """ Evaluate a django template by resource path, applying the provided context. """ context = context or {} context['_i18n_service'] = i18n_service libraries = { 'i18n': 'xblockutils.templatetags.i18n', } # For django 1.8, we have to load the libraries manually, and restore them once the template is rendered. _libraries = None if django.VERSION[0] == 1 and django.VERSION[1] == 8: _libraries = TemplateBase.libraries.copy() for library_name in libraries: library = TemplateBase.import_library(libraries[library_name]) # pylint: disable=no-member if library: TemplateBase.libraries[library_name] = library engine = Engine() else: # Django>1.8 Engine can load the extra templatetag libraries itself # but we have to override the default installed libraries. from django.template.backends.django import get_installed_libraries installed_libraries = get_installed_libraries() installed_libraries.update(libraries) engine = Engine(libraries=installed_libraries) template_str = self.load_unicode(template_path) template = Template(template_str, engine=engine) rendered = template.render(Context(context)) # Restore the original TemplateBase.libraries if _libraries is not None: TemplateBase.libraries = _libraries return rendered
Example #30
Source File: fields.py From django-private-storage with Apache License 2.0 | 5 votes |
def generate_filename(self, instance, filename): path_parts = [] if self.upload_to: # Support the upload_to callable that Django provides if callable(self.upload_to): dirname, filename = os.path.split(self.upload_to(instance, filename)) path_parts.append(dirname) else: dirname = force_text(datetime.datetime.now().strftime(force_str(self.upload_to))) path_parts.append(dirname) # Add our custom subdir function. upload_subfolder = self.upload_subfolder if upload_subfolder: # Should return a list, so joining can be done in a storage-specific manner. extra_dirs = upload_subfolder(instance) # Avoid mistakes by developers, no "s/u/b/p/a/t/h/" if isinstance(extra_dirs, string_types): warnings.warn("{}.{}.upload_subfolder should return a list" " to avoid path-separator issues.".format( instance.__class__.__name__, self.name), UserWarning) extra_dirs = os.path.split(extra_dirs) path_parts.extend([self.storage.get_valid_name(dir) for dir in extra_dirs]) path_parts.append(self._get_clean_filename(filename)) if django.VERSION >= (1, 10): filename = posixpath.join(*path_parts) return self.storage.generate_filename(filename) else: return os.path.join(*path_parts)