Here are the examples of the python api django.VERSION taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
182 Examples
5
Example 1
def test_lookup_error(self):
try:
User.objects.filter(username__error="u%r%")
raise AssertionError("The before query should have failed")
except TypeError as e:
if django.VERSION[0] == 1 and django.VERSION[1] >= 7:
raise e
except FieldError as e:
if django.VERSION[0] == 1 and django.VERSION[1] < 7:
raise e
3
Example 2
Project: django-nose-selenium Source File: plugins.py
def _patch_static_handler(handler):
"""Patch in support for static files serving if supported and enabled.
"""
if django.VERSION[:2] < (1, 3):
return
from django.contrib.staticfiles.handlers import StaticFilesHandler
return StaticFilesHandler(handler)
3
Example 3
Project: django-webtest Source File: tests.py
def test_reusing_custom_user(self):
if django.VERSION >= (1, 5):
from django_webtest_tests.testapp_tests.models import MyCustomUser
with self.settings(AUTH_USER_MODEL = 'testapp_tests.MyCustomUser'):
custom_user = MyCustomUser.objects.create(
email="[email protected]")
custom_user.set_password("123")
custom_user.save()
# Let the middleware logs the user in
self.app.get('/template/index.html', user=custom_user)
# Middleware authentication check shouldn't crash
response = self.app.get('/template/index.html',
user=custom_user)
user = response.context['user']
assert user.is_authenticated()
self.assertEqual(user, custom_user)
3
Example 4
Project: whitenoise Source File: test_django_whitenoise.py
@classmethod
def init_application(cls):
if django.VERSION >= (1, 10):
setting_name = 'MIDDLEWARE'
else:
setting_name = 'MIDDLEWARE_CLASSES'
middleware = list(getattr(settings, setting_name) or [])
middleware.insert(0, 'whitenoise.middleware.WhiteNoiseMiddleware')
setattr(settings, setting_name, middleware)
return get_wsgi_application()
3
Example 5
Project: django-encrypted-fields Source File: tests.py
@unittest.skipIf(django.VERSION < (1, 7), "Issue exists in django 1.7+")
@unittest.skipIf(not IS_POSTGRES, "Issue exists for postgresql")
def test_integerfield_validation_in_django_1_7_passes_successfully(self):
plainint = 1111
obj = TestModel()
obj.integer = plainint
# see https://github.com/defrex/django-encrypted-fields/issues/7
obj.full_clean()
obj.save()
ciphertext = self.get_db_value('integer', obj.id)
self.assertNotEqual(plainint, ciphertext)
self.assertNotEqual(plainint, str(ciphertext))
fresh_model = TestModel.objects.get(id=obj.id)
self.assertEqual(fresh_model.integer, plainint)
3
Example 6
def render_tag(self, context, **kwargs):
template_filename = self.get_template(context, **kwargs)
if 'request' not in context:
warnings.warn('No request object in context. '
'Are you sure you have django.core.context_processors.request enabled?')
if context['request'].COOKIES.get('cookielaw_accepted', False):
return ''
data = self.get_context(context, **kwargs)
if django.VERSION[:2] < (1, 10):
return render_to_string(template_filename, data, context_instance=context)
else:
return render_to_string(template_filename, data, context.request)
3
Example 7
Project: django-template-analyzer Source File: djangoanalyzer.py
def _is_variable_extends(extend_node):
"""
Check whether an ``{% extends variable %}`` is used in the template.
:type extend_node: ExtendsNode
"""
if django.VERSION < (1, 4):
return extend_node.parent_name_expr # Django 1.3
else:
# The FilterExpression.var can be either a string, or Variable object.
return not isinstance(extend_node.parent_name.var, six.string_types) # Django 1.4
3
Example 8
def main():
TestRunner = get_runner(settings)
test_runner = TestRunner()
module_name = 'rest_utils.tests'
if django.VERSION[0] == 1 and django.VERSION[1] < 6:
module_name = 'rest_utils'
failures = test_runner.run_tests([module_name])
sys.exit(failures)
3
Example 9
@method_decorator(api_authentication_required)
@csrf_exempt
def route(self, request, **kwargs):
method = request.method
if method in self.allowed_methods:
if hasattr(self, method.lower()):
if method == 'PUT':
request.PUT = QueryDict(request.body if django.VERSION >= (1, 4) else request.raw_post_data).copy()
return getattr(self, method.lower())(request, **kwargs)
return HttpResponseNotImplemented()
return HttpResponseNotAllowed(self.allowed_methods)
3
Example 10
def main():
TestRunner = get_runner(settings)
test_runner = TestRunner()
if len(sys.argv) == 2:
test_case = sys.argv[1]
elif len(sys.argv) == 1:
test_case = 'tests'
else:
print(usage())
sys.exit(1)
test_module_name = 'drf_to_s3.'
if django.VERSION[0] == 1 and django.VERSION[1] < 6:
test_module_name = ''
failures = test_runner.run_tests([test_module_name + test_case])
sys.exit(failures)
3
Example 11
def __new__(cls, name, bases, dct):
if django.VERSION >= (1, 5):
for custom_user in ['auth.CustomUser', 'auth.ExtensionUser']:
suffix = custom_user.lower().replace('.', '_')
for key, fn in list(dct.items()):
if key.startswith('test') and '_CUSTOM_' not in key:
name = '{0}_CUSTOM_{1}'.format(key, suffix)
dct[name] = override_settings(
AUTH_USER_MODEL=custom_user)(fn)
return super(CustomUserVariants, cls).__new__(cls, name, bases, dct)
3
Example 12
Project: huey Source File: run_huey.py
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
if django.VERSION < (1, 8):
self.option_list = BaseCommand.option_list
parser = CompatParser(self)
self.add_arguments(parser)
3
Example 13
Project: django-rest-framework Source File: compat.py
def get_names_and_managers(options):
if django.VERSION >= (1, 10):
# Django 1.10 onwards provides a `.managers` property on the Options.
return [
(manager.name, manager)
for manager
in options.managers
]
# For Django 1.8 and 1.9, use the three-tuple information provided
# by .concrete_managers and .abstract_managers
return [
(manager_info[1], manager_info[2])
for manager_info
in (options.concrete_managers + options.abstract_managers)
]
3
Example 14
Project: django-ldapdb Source File: tests.py
def _build_lookup(self, field_name, lookup, value, field=CharField):
fake_field = field()
fake_field.set_attributes_from_name(field_name)
if django.VERSION[:2] <= (1, 7):
lhs = datastructures.Col('faketable', fake_field, fake_field)
else:
lhs = expressions.Col('faketable', fake_field, fake_field)
lookup = lhs.get_lookup(lookup)
return lookup(lhs, value)
3
Example 15
@pytest.mark.skipif(django.VERSION[:2] < (1, 7),
reason="Skip if django< 1.7")
@pytest.mark.django_db
def test_check(obj, monkeypatch):
from django.core.checks import Warning
monkeypatch.setattr(obj._concurrencymeta.field, '_trigger_name', 'test')
assert isinstance(obj._concurrencymeta.field.check()[0], Warning)
3
Example 16
Project: django-pgjson Source File: tests.py
def test_uuid_not_supported_by_default_json_encoder(self):
if django.VERSION < (1, 8):
with self.assertRaises(TypeError):
self.model_class.objects.create(data=uuid.uuid4())
else:
uid = uuid.uuid4()
obj = self.model_class.objects.create(data=uid)
obj = self.model_class.objects.get(pk=obj.pk)
self.assertEqual(obj.data, str(uid))
3
Example 17
def get_user_model():
if django.VERSION >= (1, 5):
from django.contrib.auth import get_user_model as _get_user_model
User = _get_user_model()
else:
from django.contrib.auth.models import User
return User
3
Example 18
Project: ella Source File: test_templatetags.py
def test_proper_template_gets_rendered_via_kwargs(self):
if django.VERSION[:2] < (1, 4):
raise SkipTest()
template_loader.templates['inclusion_tags/paginator_special.html'] = 'special'
t = template.Template('{% load pagination %}{% paginator template_name="special" %}')
tools.assert_equals('special', t.render(template.Context()))
3
Example 19
Project: django-babel Source File: test_extract.py
@pytest.mark.skipif(django.VERSION < (1, 7),
reason='Trimmed whitespace is a Django >= 1.7 feature')
def test_blocktrans_with_whitespace_trimmed(self):
test_tmpl = (
b'{% blocktrans trimmed %}\n\tfoo\n\tbar\n{% endblocktrans %}'
)
buf = BytesIO(test_tmpl)
messages = list(extract_django(buf, default_keys, [], {}))
self.assertEqual([(4, None, u'foo bar', [])], messages)
3
Example 20
def assertInHTML(self, needle, haystack, count=None, msg_prefix=''):
import django
if django.VERSION < (1, 5):
real_count = haystack.count(needle)
return self.assertEqual(real_count, count)
else:
return super(TestStoredMessagesTags, self).assertInHTML(
needle, haystack, count, msg_prefix)
3
Example 21
Project: easy-thumbnails Source File: utils.py
@skipUnless(django.VERSION < (1, 7), "test only applies to 1.6 and below")
def test_import_migrations_module(self):
try:
from easy_thumbnails.migrations import __doc__ # noqa
except ImproperlyConfigured as e:
exception = e
self.assertIn("SOUTH_MIGRATION_MODULES", exception.args[0])
3
Example 22
Project: django-user-sessions Source File: tests.py
def test_login(self):
if django.VERSION < (1, 7):
admin_login_url = '/admin/'
else:
admin_login_url = reverse('admin:login')
user = User.objects.create_superuser('bouke', '', 'secret')
response = self.client.post(admin_login_url,
data={
'username': 'bouke',
'password': 'secret',
'this_is_the_login_form': '1',
'next': '/admin/'},
HTTP_USER_AGENT='Python/2.7')
self.assertRedirects(response, '/admin/')
session = Session.objects.get(
pk=self.client.cookies[settings.SESSION_COOKIE_NAME].value
)
self.assertEqual(user, session.user)
3
Example 23
def get_installed_apps():
"""
Return list of all installed apps
"""
if django.VERSION >= (1, 7):
from django.apps import apps
return [a.models_module for a in apps.get_app_configs()
if a.models_module is not None]
else:
from django.db import models
return models.get_apps()
3
Example 24
def get_ordering(self):
# The ORDER BY clause is invalid in views, inline functions,
# derived tables, subqueries, and common table expressions,
# unless TOP or FOR XML is also specified.
if getattr(self.query, '_mssql_ordering_not_allowed', False):
if django.VERSION[1] == 1 and django.VERSION[2] < 6:
return (None, [])
return (None, [], [])
return super(SQLCompiler, self).get_ordering()
3
Example 25
def runtests():
if django.VERSION > (1, 7):
# http://django.readthedocs.org/en/latest/releases/1.7.html#standalone-scripts
django.setup()
from django.test.utils import get_runner
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['bandit', ])
sys.exit(failures)
3
Example 26
def runtests():
if django.VERSION > (1, 7):
# http://django.readthedocs.org/en/latest/releases/1.7.html#standalone-scripts
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
failures = test_runner.run_tests(['treenav', ])
sys.exit(failures)
3
Example 27
Project: tower Source File: test_l10n.py
def test_activate_with_override_settings_and_django_14():
# Django 1.4 includes a handy override_settings helper. When you
# use that, it must not include SETTINGS_MODULE in the settings.
# This tests that activating a locale doesn't throw an
# AssertionError because there's no SETTINGS_MODULE in settings.
if django.VERSION >= (1, 4):
from django.test.utils import override_settings
with override_settings():
tower.deactivate_all()
tower.activate('xx')
# String is the same because it couldn't find
# SETTINGS_MODULE and thus didn't pick up the right .mo
# files.
eq_(_('this is a test'), 'this is a test')
tower.deactivate_all()
3
Example 28
def test_command_error():
if django.VERSION[1] > 4:
with pytest.raises(CommandError):
management.call_command("create_token", "noop")
with pytest.raises(CommandError):
management.call_command("create_token", "noop", "noop", "noop")
3
Example 29
Project: mock-django Source File: tests.py
@skipIf(django.VERSION >= (1, 9), "MergeDict and REQUEST removed in Django 1.9")
def test__get_request(self):
from django.utils.datastructures import MergeDict
wsgi_r = WsgiHttpRequest()
expected_items = MergeDict({}, {}).items()
wsgi_r.GET = {}
wsgi_r.POST = {}
self.assertListEqual(sorted(expected_items),
sorted(wsgi_r._get_request().items()))
3
Example 30
Project: django-dirtyfields Source File: test_save_fields.py
@unittest.skipIf(django.VERSION < (1, 5), "Django 1.4 doesn't support update_fields param on save()")
@pytest.mark.django_db
def test_save_only_specific_fields_should_let_other_fields_dirty():
tm = TestModel.objects.create(boolean=True, characters='dummy')
tm.boolean = False
tm.characters = 'new_dummy'
tm.save(update_fields=['boolean'])
# 'characters' field should still be dirty, update_fields was only saving the 'boolean' field in the db
assert tm.get_dirty_fields() == {'characters': 'dummy'}
3
Example 31
def __init__(self, *args, **kwargs):
self.option_list = self.base_option_list + self.option_list
if django.VERSION < (1, 10):
options = tuple([optparse_make_option(*_args, **_kwargs)
for _args, _kwargs in self.option_list])
self.option_list = options + BaseCommand.option_list
super(BaseDbBackupCommand, self).__init__(*args, **kwargs)
3
Example 32
Project: django-celery-rpc Source File: base.py
def atomic_commit_on_success():
""" Select context manager for atomic database operations depending on
Django version.
"""
ver = django.VERSION
if ver[0] == 1 and ver[1] < 6:
return transaction.commit_on_success
elif ver[0] == 1 and ver[1] >= 6:
return transaction.atomic
else:
raise RuntimeError('Invalid Django version: {}'.format(ver))
3
Example 33
def validate(self, value, model_instance):
arr_choices = self.get_choices_selected(self.get_choices_default())
for opt_select in value:
if (opt_select not in arr_choices):
if django.VERSION[0] == 1 and django.VERSION[1] >= 6:
raise exceptions.ValidationError(
self.error_messages['invalid_choice'] % {"value": value})
else:
raise exceptions.ValidationError(
self.error_messages['invalid_choice'] % value)
3
Example 34
Project: django_migration_testcase Source File: django_migrations.py
Function: get_apps_for_migration
Function: get_apps_for_migration
def _get_apps_for_migration(self, migration_states):
loader = MigrationLoader(connection)
full_names = []
for app_name, migration_name in migration_states:
if migration_name != 'zero':
migration_name = loader.get_migration_by_prefix(app_name, migration_name).name
full_names.append((app_name, migration_name))
state = loader.project_state(full_names)
if django.VERSION < (1, 8):
state.render()
return state.apps
3
Example 35
def test(self):
if django.VERSION < (1, 10):
self.assertEqual('admin/js/jquery.min.js', get_jquery_min_js())
else:
self.assertEqual(
'admin/js/vendor/jquery/jquery.min.js', get_jquery_min_js()
)
3
Example 36
def __init__(self, stdout=None, stderr=None, no_color=False):
"""
Changes the option_list to use the options from the wrapped migrate command.
"""
if django.VERSION <= (1, 10, 0):
self.option_list += MigrateCommand.option_list
super(Command, self).__init__(stdout, stderr, no_color)
3
Example 37
def _get_parser():
import django
parser = Parser([])
if django.VERSION >= (1, 9):
import django.template.defaultfilters
parser.add_library(django.template.defaultfilters.register)
return parser
3
Example 38
Project: django-softdelete Source File: models.py
def _get_base_queryset(self):
'''
Convenience method for grabbing the base query set. Accounts for the
deprecation of get_query_set in Django 18.
'''
if django.VERSION >= (1, 8, 0, 'final', 0):
return super(SoftDeleteManager, self).get_queryset()
else:
return super(SoftDeleteManager, self).get_query_set()
3
Example 39
Project: django-global-permissions Source File: test_models.py
def test_content_type_name(self):
gp = GlobalPermission(codename='some_codename')
gp.save()
self.assertEquals('global_permissions', gp.content_type.app_label)
lookup = Q(model='globalpermission', app_label='global_permissions')
if django.VERSION < (1, 8):
lookup &= Q(name='global_permission')
self.assertEquals(gp.content_type, ContentType.objects.get(lookup))
3
Example 40
def _clone(self, klass=None, setup=False, **kwargs):
kwargs.update({
'_prefetched_translations_cache': self._prefetched_translations_cache,
'_prefetch_translations_done': self._prefetch_translations_done,
})
if django.VERSION < (1, 9):
kwargs.update({
'klass': klass,
'setup': setup,
})
return super(QuerySetMixin, self)._clone(**kwargs)
3
Example 41
Project: drf-nested-routers Source File: runtests.py
def main():
TestRunner = get_runner(settings)
import ipdb;ipdb.set_trace()
test_runner = TestRunner()
if len(sys.argv) == 2:
test_case = '.' + sys.argv[1]
elif len(sys.argv) == 1:
test_case = ''
else:
print(usage())
sys.exit(1)
test_module_name = 'rest_framework_nested.tests'
if django.VERSION[0] == 1 and django.VERSION[1] < 6:
test_module_name = 'tests'
failures = test_runner.run_tests([test_module_name + test_case])
sys.exit(failures)
3
Example 42
Project: django-mailer Source File: tests.py
def call_command_with_cron_arg(command, cron_value):
# for old django versions, `call_command` doesn't parse arguments
if django.VERSION < (1, 8):
return call_command(command, cron=cron_value)
# newer django; test parsing by passing argument as string
return call_command(command, '--cron={}'.format(cron_value))
3
Example 43
Project: django-oauth-toolkit Source File: test_models.py
def test_related_objects(self):
"""
If a custom application model is installed, it should be present in
the related objects and not the swapped out one.
See issue #90 (https://github.com/evonove/django-oauth-toolkit/issues/90)
"""
# Django internals caches the related objects.
if django.VERSION < (1, 8):
del UserModel._meta._related_objects_cache
related_object_names = [ro.name for ro in UserModel._meta.get_all_related_objects()]
self.assertNotIn('oauth2_provider:application', related_object_names)
self.assertIn('tests%stestapplication' % (':' if django.VERSION < (1, 8) else '_'),
related_object_names)
3
Example 44
def wantDirectory(self, dirname):
log.debug('Do we want dir: %s' % dirname)
if 'wizard' in dirname and django.VERSION[0] <= 1 and django.VERSION[1] < 4:
return False
return super(TestDiscoverySelector, self).wantDirectory(dirname)
3
Example 45
def _get_form_str(self, form_str):
if django.VERSION >= (1, 3):
form_str %= {
"help_start": '<span class="helptext">',
"help_stop": "</span>"
}
else:
form_str %= {
"help_start": "",
"help_stop": ""
}
return form_str
3
Example 46
Project: django-allauth Source File: tests.py
def setUp(self):
if django.VERSION < (1, 8,):
engine = import_module(settings.SESSION_ENGINE)
s = engine.SessionStore()
s.save()
self.client.cookies[
settings.SESSION_COOKIE_NAME] = s.session_key
3
Example 47
Project: django-user-accounts Source File: test_password.py
def middleware_kwarg(value):
if django.VERSION >= (1, 10):
kwarg = "MIDDLEWARE"
else:
kwarg = "MIDDLEWARE_CLASSES"
return {kwarg: value}
3
Example 48
Project: django-modelclone Source File: test_admin.py
def test_clone_should_keep_file_path_from_original_object(self):
response = self.app.get(self.multimedia_url, user='admin')
image = select_element(response, '.field-image p.file-upload a')
docuement = select_element(response, '.field-docuement p.file-upload a')
if django.VERSION[1] == 10:
assert '/media/images/tests/files/img.jpg' == image.get('href')
assert '/media/docuements/tests/files/file.txt' == docuement.get('href')
else:
assert '/media/images/img.jpg' == image.get('href')
assert '/media/docuements/file.txt' == docuement.get('href')
3
Example 49
Project: djoser Source File: tests.py
@unittest2.skipIf(django.VERSION < (1, 10),
"in these versions authenticate() succeedes if user is inactive")
def test_post_should_not_login_if_user_is_not_active(self):
user = create_user()
data = {
'username': user.username,
'password': user.raw_password,
}
user.is_active = False
user.save()
user_logged_in.connect(self.signal_receiver)
request = self.factory.post(data=data)
response = self.view(request)
self.assert_status_equal(response, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['non_field_errors'], [djoser.constants.INVALID_CREDENTIALS_ERROR])
self.assertFalse(self.signal_sent)
3
Example 50
Project: django-wagtail-feeds Source File: runtests.py
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, parent)
if django.VERSION < (1, 8):
from django.test.simple import DjangoTestSuiteRunner
failures = DjangoTestSuiteRunner(
verbosity=1, interactive=True, failfast=False).run_tests(['tests'])
sys.exit(failures)
else:
from django.test.runner import DiscoverRunner
failures = DiscoverRunner(
verbosity=1, interactive=True, failfast=False).run_tests(test_args)
sys.exit(failures)