Python django.get_version() Examples

The following are 30 code examples for showing how to use django.get_version(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django , or try the search function .

Example 1
def test_cookie_samesite_django30(self):
        # Raise DeprecationWarning for newer versions of Django
        with patch('django.get_version', return_value=DJANGO_SUPPORTED_VERSION):
            with self.assertRaises(DeprecationWarning) as exc:
                self.client.get('/cookies-test/')

            self.assertEqual(exc.exception.args[0], (
                'Your version of Django supports SameSite flag in the cookies mechanism. '
                'You should remove django-cookies-samesite from your project.'
            ))

        with patch('django_cookies_samesite.middleware.django.get_version', return_value=DJANGO_SUPPORTED_VERSION):
            with self.assertRaises(DeprecationWarning) as exc:
                self.client.get('/cookies-test/')

            self.assertEqual(exc.exception.args[0], (
                'Your version of Django supports SameSite flag in the cookies mechanism. '
                'You should remove django-cookies-samesite from your project.'
            )) 
Example 2
Project: yournextrepresentative   Author: mysociety   File: api.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get(self, request, *args, **kwargs):
        result = {
            'python_version': sys.version,
            'django_version': django.get_version(),
            'interesting_user_actions': extra_models.LoggedAction.objects \
                .exclude(action_type='set-candidate-not-elected') \
                .count(),
            'users_who_have_edited': User.objects \
                .annotate(edit_count=Count('loggedaction')) \
                .filter(edit_count__gt=0).count()
        }
        # Try to get the object name of HEAD from git:
        try:
            git_version = subprocess.check_output(
                ['git', 'rev-parse', '--verify', 'HEAD'],
                cwd=dirname(__file__),
                universal_newlines=True
            ).strip()
            result['git_version'] = git_version
        except (OSError, subprocess.CalledProcessError):
            pass
        return HttpResponse(
            json.dumps(result), content_type='application/json'
        ) 
Example 3
Project: algoliasearch-django   Author: algolia   File: registration.py    License: MIT License 6 votes vote down vote up
def __init__(self, settings=SETTINGS):
        """Initializes the Algolia engine."""

        try:
            app_id = settings['APPLICATION_ID']
            api_key = settings['API_KEY']
        except KeyError:
            raise AlgoliaEngineError(
                'APPLICATION_ID and API_KEY must be defined.')

        self.__auto_indexing = settings.get('AUTO_INDEXING', True)
        self.__settings = settings

        self.__registered_models = {}
        self.client = algoliasearch.Client(app_id, api_key)
        self.client.set_extra_header('User-Agent',
                                     'Algolia for Python (%s); Python (%s); Algolia for Django (%s); Django (%s)'
                                     % (CLIENT_VERSION, python_version(), VERSION, django_version)) 
Example 4
Project: django-sqlserver   Author: denisenkom   File: test_writer.py    License: MIT License 6 votes vote down vote up
def test_migration_file_header_comments(self):
        """
        Test comments at top of file.
        """
        migration = type(str("Migration"), (migrations.Migration,), {
            "operations": []
        })
        dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=utc)
        with mock.patch('django.db.migrations.writer.now', lambda: dt):
            writer = MigrationWriter(migration)
            output = writer.as_string()

        self.assertTrue(
            output.startswith(
                "# -*- coding: utf-8 -*-\n"
                "# Generated by Django %(version)s on 2015-07-31 04:40\n" % {
                    'version': get_version(),
                }
            )
        ) 
Example 5
Project: djongo   Author: nesdis   File: test_writer.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_migration_file_header_comments(self):
        """
        Test comments at top of file.
        """
        migration = type("Migration", (migrations.Migration,), {
            "operations": []
        })
        dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=utc)
        with mock.patch('django.db.migrations.writer.now', lambda: dt):
            writer = MigrationWriter(migration)
            output = writer.as_string()

        self.assertTrue(
            output.startswith(
                "# Generated by Django %(version)s on 2015-07-31 04:40\n" % {
                    'version': get_version(),
                }
            )
        ) 
Example 6
Project: djongo   Author: nesdis   File: test_writer.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_migration_file_header_comments(self):
        """
        Test comments at top of file.
        """
        migration = type("Migration", (migrations.Migration,), {
            "operations": []
        })
        dt = datetime.datetime(2015, 7, 31, 4, 40, 0, 0, tzinfo=utc)
        with mock.patch('django.db.migrations.writer.now', lambda: dt):
            for include_header in (True, False):
                with self.subTest(include_header=include_header):
                    writer = MigrationWriter(migration, include_header)
                    output = writer.as_string()

                    self.assertEqual(
                        include_header,
                        output.startswith(
                            "# Generated by Django %s on 2015-07-31 04:40\n\n" % get_version()
                        )
                    )
                    if not include_header:
                        # Make sure the output starts with something that's not
                        # a comment or indentation or blank line
                        self.assertRegex(output.splitlines(keepends=True)[0], r"^[^#\s]+") 
Example 7
Project: Tautulli   Author: Tautulli   File: __init__.py    License: GNU General Public License v3.0 6 votes vote down vote up
def import_django_settings():
    try:
        from django.core.exceptions import ImproperlyConfigured

        try:
            from django.conf import settings as _django_settings

            # We can get a situation when Django module is installed in the system, but not initialized,
            # which means we are running not in a Django process.
            # In this case the following line throws ImproperlyConfigured exception
            if 'cloudinary' in _django_settings.INSTALLED_APPS:
                from django import get_version as _get_django_version
                global USER_PLATFORM
                USER_PLATFORM = "Django/{django_version}".format(django_version=_get_django_version())

            if 'CLOUDINARY' in dir(_django_settings):
                return _django_settings.CLOUDINARY
            else:
                return None

        except ImproperlyConfigured:
            return None

    except ImportError:
        return None 
Example 8
Project: django-click   Author: GaretJax   File: test_adapter.py    License: MIT License 5 votes vote down vote up
def test_django_version(manage):
    django_version = django.get_version().encode("ascii") + b"\n"
    assert manage("testcmd", "--version") == django_version
    assert manage("versioncmd", "--version") == b"20.0\n" 
Example 9
Project: django-click   Author: GaretJax   File: adapter.py    License: MIT License 5 votes vote down vote up
def __init__(self, **kwargs):
        self.kwargs = kwargs
        self.version = self.kwargs.pop("version", get_version())

        context_settings = kwargs.setdefault("context_settings", {})
        context_settings["help_option_names"] = ["-h", "--help"] 
Example 10
Project: GTDWeb   Author: lanbing510   File: base.py    License: GNU General Public License v2.0 5 votes vote down vote up
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() 
Example 11
def process_response(self, request, response):
        # same-site = None introduced for Chrome 80 breaks for Chrome 51-66
        # Refer (https://www.chromium.org/updates/same-site/incompatible-clients)
        http_user_agent = request.META.get("HTTP_USER_AGENT") or " "
        user_agent_checker = UserAgentChecker(http_user_agent)

        if user_agent_checker.do_not_send_same_site_policy:
            return response

        if LooseVersion(django.get_version()) >= LooseVersion(DJANGO_SUPPORTED_VERSION):
            raise DeprecationWarning(
                "Your version of Django supports SameSite flag in the cookies mechanism. "
                "You should remove django-cookies-samesite from your project."
            )

        if not self.samesite_flag:
            return response

        # TODO: capitalize those values
        if self.samesite_flag not in {"Lax", "None", "Strict"}:
            raise ValueError('samesite must be "Lax", "None", or "Strict".')

        if self.samesite_force_all:
            for cookie in response.cookies:
                self.update_cookie(cookie, request, response)
        else:
            for cookie in self.protected_cookies:
                if cookie in response.cookies:
                    self.update_cookie(cookie, request, response)

        return response 
Example 12
def test_settings_default_values(self):
        """Check if middleware reads default values as expected"""
        with self.settings():
            middleware = CookiesSameSite()
            self.assertEqual(middleware.samesite_force_all, None)
            self.assertEqual(middleware.protected_cookies, {'sessionid', 'csrftoken'})

            if LooseVersion(django.get_version()) >= LooseVersion('3.0'):
                self.assertEqual(middleware.samesite_flag, 'Lax')
            else:
                self.assertEqual(middleware.samesite_flag, '') 
Example 13
Project: django-admin-view-permission   Author: ctxis   File: utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
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
    elif django.get_version().startswith('2.0'):
        return DjangoVersion.DJANGO_20
    elif django.get_version().startswith('2.1'):
        return DjangoVersion.DJANGO_21 
Example 14
Project: PyDev.Debugger   Author: fabioz   File: debugger_fixtures.py    License: Eclipse Public License 1.0 5 votes vote down vote up
def case_setup_django(debugger_runner_simple):

    class WriterThread(AbstractWriterThreadCaseDjango):
        pass

    class CaseSetup(object):

        @contextmanager
        def test_file(self, **kwargs):
            import django
            version = [int(x) for x in django.get_version().split('.')][:2]
            if version == [1, 7]:
                django_folder = 'my_django_proj_17'
            elif version in ([2, 1], [2, 2], [3, 0]):
                django_folder = 'my_django_proj_21'
            else:
                raise AssertionError('Can only check django 1.7, 2.1, 2.2 and 3.0 right now. Found: %s' % (version,))

            WriterThread.DJANGO_FOLDER = django_folder
            for key, value in kwargs.items():
                assert hasattr(WriterThread, key)
                setattr(WriterThread, key, value)

            with debugger_runner_simple.check_case(WriterThread) as writer:
                yield writer

    return CaseSetup() 
Example 15
Project: python-percy-client   Author: percy   File: user_agent.py    License: MIT License 5 votes vote down vote up
def _django_version(self):
        try:
            import django
            return "django/%s" % django.get_version()
        except ImportError:
            return None 
Example 16
Project: drf_tweaks   Author: HealthByRo   File: optimizator.py    License: MIT License 5 votes vote down vote up
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)) 
Example 17
Project: drf_tweaks   Author: HealthByRo   File: optimizator.py    License: MIT License 5 votes vote down vote up
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)) 
Example 18
Project: django-q   Author: Koed00   File: models.py    License: MIT License 5 votes vote down vote up
def decode_results(values):
    if get_version().split(".")[1] == "7":
        # decode values in 1.7
        return [dbsafe_decode(v) for v in values]
    return values 
Example 19
Project: django-db-mailer   Author: LPgenerator   File: mail.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _insert_mailer_identification_head(self):
        if not ADD_HEADER:
            return
        headers = self._kwargs.pop('headers', {})
        headers.update(
            {'X-Mailer-Wrapper': 'django-db-mailer ver %s' % get_version()})
        self._kwargs['headers'] = headers 
Example 20
Project: django-db-mailer   Author: LPgenerator   File: mail.py    License: GNU General Public License v2.0 5 votes vote down vote up
def _get_context_module_name(context):
        from distutils.version import StrictVersion
        import django

        current_version = django.get_version()

        if StrictVersion(current_version) < StrictVersion('1.8'):
            return context._meta.module_name
        return context._meta.model_name 
Example 21
Project: InvenTree   Author: inventree   File: version.py    License: MIT License 5 votes vote down vote up
def inventreeDjangoVersion():
    """ Return the version of Django library """
    return django.get_version() 
Example 22
Project: ishare   Author: jeeyshe   File: simpletags.py    License: MIT License 5 votes vote down vote up
def get_version():
    return simpleui.get_version() 
Example 23
Project: ishare   Author: jeeyshe   File: simpletags.py    License: MIT License 5 votes vote down vote up
def get_app_info():
    dict = {
        'version': simpleui.get_version()
    }

    return format_table(dict) 
Example 24
Project: ishare   Author: jeeyshe   File: simpletags.py    License: MIT License 5 votes vote down vote up
def load_analysis(context):
    try:
        if get_analysis_config() == False:
            return ''

        # 理论上值一天只上报一次
        key = 'simpleui_' + time.strftime('%Y%m%d', time.localtime())

        if key in context.request.session:
            return ''

        b64 = ""
        j = {
            "n": platform.node(),
            "o": platform.platform(),
            "p": platform.python_version(),
            "d": django.get_version(),
            "s": simpleui.get_version(),
        }
        if 'theme_name' in context.request.COOKIES:
            j['t'] = context.request.COOKIES['theme_name']
        else:
            j['t'] = 'Default'

        b64 = base64.b64encode(str(j).encode('utf-8'))

        url = '//simpleui.88cto.com/analysis'
        b64 = b64.decode('utf-8')
        html = '<script async type="text/javascript" src="{}/{}"></script>'.format(url, b64);
        context.request.session[key] = True

        return mark_safe(html)
    except:
        return '' 
Example 25
Project: ishare   Author: jeeyshe   File: simpletags.py    License: MIT License 5 votes vote down vote up
def simple_version():
    return simpleui.get_version() 
Example 26
Project: ishare   Author: jeeyshe   File: apps.py    License: MIT License 5 votes vote down vote up
def ready(self):
        # 如果是django3+ 就使用中间件,删除header中的X-Frame-Options

        try:
            import django
            version = django.get_version()
            if int(version.split('.')[0]) >= 3:
                from django.conf import settings
                mname = 'simpleui.middlewares.SimpleMiddleware'
                if mname not in settings.MIDDLEWARE:
                    settings.MIDDLEWARE.append(mname)
        except Exception as e:
            pass
        pass 
Example 27
Project: django-graphql-jwt   Author: flavors   File: decorators.py    License: MIT License 5 votes vote down vote up
def skipif_django_version(version):
    return pytest.mark.skipif(
        django.get_version() < version,
        reason='Django < {} is not supported'.format(version)) 
Example 28
Project: django-bootstrap-datepicker-plus   Author: monim67   File: context_processors.py    License: Apache License 2.0 5 votes vote down vote up
def demo_context(request):
    context = {
        'django_version': django_version,
        'django_version_string': get_django_version(),
        'url_section': '',
        'url_sub_section': '',
        'bootstrap_version': '',
        'bootstrap4_supported': django_version > (1, 11),
    }
    url_name_parts = request.resolver_match.url_name.split('.', 1)
    if len(url_name_parts) == 2 and url_name_parts[0][:-1] == 'bootstrap':
        context['url_section'] = url_name_parts[0]
        context['url_sub_section'] = url_name_parts[1]
        context['bootstrap_version'] = int(url_name_parts[0][-1])
    return context 
Example 29
Project: luscan-devel   Author: blackye   File: base.py    License: GNU General Public License v2.0 5 votes vote down vote up
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() 
Example 30
Project: luscan-devel   Author: blackye   File: base.py    License: GNU General Public License v2.0 5 votes vote down vote up
def create_parser(self, prog_name, subcommand):
        """
        Create and return the ``OptionParser`` which will be used to
        parse the arguments to this command.

        """
        return OptionParser(prog=prog_name,
                            usage=self.usage(subcommand),
                            version=self.get_version(),
                            option_list=self.option_list)