Python django 模块,VERSION 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用django.VERSION

项目:django-performance-testing    作者:PaesslerAG    | 项目源码 | 文件源码
def ready(self):
        if django.VERSION[:2] == (1, 9):
            import warnings
            msg = "You are using an unsupported Django version. DJPT support" \
                  " might be dropped in any following release. See " \
                  "https://www.djangoproject.com/download/#supported-versions"
            warnings.warn(msg)

        from django_performance_testing.registry import \
            SettingsOrDefaultBasedRegistry
        from django_performance_testing import core
        core.limits_registry = SettingsOrDefaultBasedRegistry()
        from .test_client import integrate_into_test_client
        integrate_into_test_client()
        from .test_runner import integrate_into_django_test_runner
        integrate_into_django_test_runner()
        from .queries import setup_sending_before_clearing_queries_log_signal
        setup_sending_before_clearing_queries_log_signal()
        from .templates import integrate_into_django_templates
        integrate_into_django_templates()
项目:django-heartbeat    作者:pbs    | 项目源码 | 文件源码
def test_db_version(self):
        import django
        if django.VERSION >= (1, 7):
            cursor = 'django.db.backends.utils.CursorWrapper'
        else:
            cursor = 'django.db.backends.util.CursorWrapper'
        with mock.patch(cursor) as mock_cursor:
            mock_cursor.return_value.fetchone.return_value = ['1.0.0']
            dbs = {
                'default': {
                    'ENGINE': 'django.db.backends.sqlite3',
                    'NAME': 'foo'
                }
            }
            setattr(settings, 'DATABASES', dbs)
            dbs = databases.check(request=None)
        assert len(dbs) == 1
        assert dbs[0]['version'] == '1.0.0'
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def test_delete_cgroup(self):
        cgroups = self.cinder_consistencygroups.list()
        cgroup = self.cinder_consistencygroups.first()

        cinder.volume_cgroup_list_with_vol_type_names(IsA(http.HttpRequest)).\
            AndReturn(cgroups)
        cinder.volume_cgroup_delete(IsA(http.HttpRequest), cgroup.id,
                                    force=False)
        if django.VERSION < (1, 9):
            cinder.volume_cgroup_list_with_vol_type_names(
                IsA(http.HttpRequest)).AndReturn(cgroups)

        self.mox.ReplayAll()

        formData = {'action': 'volume_cgroups__deletecg__%s' % cgroup.id}
        res = self.client.post(VOLUME_CGROUPS_TAB_URL, formData, follow=True)
        self.assertIn("Scheduled deletion of Consistency Group: cg_1",
                      [m.message for m in res.context['messages']])
项目:mos-horizon    作者:Mirantis    | 项目源码 | 文件源码
def test_ssl_redirect_by_proxy(self):
        dogs = horizon.get_dashboard("dogs")
        puppies = dogs.get_panel("puppies")
        url = puppies.get_absolute_url()
        redirect_url = "?".join([settings.LOGIN_URL,
                                 "next=%s" % url])

        self.client.logout()
        resp = self.client.get(url)
        if django.VERSION >= (1, 9):
            self.assertRedirects(resp, settings.TESTSERVER + redirect_url)
        else:
            self.assertRedirects(resp, redirect_url)

        # Set SSL settings for test server
        settings.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL',
                                            'https')

        resp = self.client.get(url, HTTP_X_FORWARDED_PROTOCOL="https")
        self.assertEqual(302, resp.status_code)
        self.assertEqual('https://testserver:80%s' % redirect_url,
                         resp['location'])

        # Restore settings
        settings.SECURE_PROXY_SSL_HEADER = None
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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:
    # main = X.Y[.Z]
    # sub = .devN - for pre-alpha releases
    #     | {a|b|c}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': 'c'}
        sub = mapping[version[3]] + str(version[4])

    return str(main + sub)
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
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')
项目:django-happenings    作者:natgeosociety    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        if attrs is None:
            attrs = {}
        # it's called "original" because it will be replaced by a copy
        attrs['class'] = 'hstore-original-textarea'

        # get default HTML from AdminTextareaWidget
        html = super(BaseAdminHStoreWidget, self).render(name, value, attrs)

        # prepare template context
        template_context = Context({
            'field_name': name,
            'STATIC_URL': settings.STATIC_URL,
            'use_svg': django.VERSION >= (1, 9),  # use svg icons if django >= 1.9
        })
        # get template object
        template = get_template('happenings/hstore_%s_widget.html' % self.admin_style)
        # render additional html
        additional_html = template.render(template_context)

        # append additional HTML and mark as safe
        html = html + additional_html
        html = mark_safe(html)

        return html
项目:python-mysql-pool    作者:LuciferJack    | 项目源码 | 文件源码
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)
项目:DCRM    作者:82Flex    | 项目源码 | 文件源码
def test_good_data(self):
        """Upload a zip with a single file it it: 'sample.jpg'.
        It gets assigned to a newly created gallery 'Test'."""

        test_data = copy.copy(self.sample_form_data)
        response = self.client.post('/admin/photologue/photo/upload_zip/', test_data)
        # The redirect Location has changed in Django 1.9 - it used to be an absolute URI, now it returns
        # a relative one.
        if VERSION[0] == 1 and VERSION[1] <= 8:
            location = 'http://testserver/admin/photologue/photo/'
        else:
            location = '..'

        self.assertEqual(response['Location'], location)

        self.assertQuerysetEqual(Gallery.objects.all(),
                                 ['<Gallery: This is a test title>'])
        self.assertQuerysetEqual(Photo.objects.all(),
                                 ['<Photo: This is a test title 1>'])

        # The photo is attached to the gallery.
        gallery = Gallery.objects.get(title='This is a test title')
        self.assertQuerysetEqual(gallery.photos.all(),
                                 ['<Photo: This is a test title 1>'])
项目:django-hijack-admin    作者:arteria    | 项目源码 | 文件源码
def hijack_field(self, obj):
        hijack_attributes = hijack_settings.HIJACK_URL_ALLOWED_ATTRIBUTES

        if 'user_id' in hijack_attributes:
            hijack_url = reverse('hijack:login_with_id', args=(obj.pk, ))
        elif 'email' in hijack_attributes:
            hijack_url = reverse('hijack:login_with_email', args=(obj.email, ))
        else:
            hijack_url = reverse('hijack:login_with_username', args=(obj.username, ))

        button_template = get_template(hijack_admin_settings.HIJACK_BUTTON_TEMPLATE)
        button_context = {
            'hijack_url': hijack_url,
            'username': str(obj),
        }
        if VERSION < (1, 8):
            button_context = Context(button_context)

        return button_template.render(button_context)
项目:django-admin-shell    作者:djk2    | 项目源码 | 文件源码
def dispatch(self, request, *args, **kwargs):
        """Override to check settings"""
        if django.VERSION < (1, 10):
            is_auth = request.user.is_authenticated()
        else:
            is_auth = request.user.is_authenticated

        if not ADMIN_SHELL_ENABLE:
            return HttpResponseNotFound("Not found: Django admin shell is not enabled")
        elif is_auth is False or request.user.is_staff is False:
            return HttpResponseForbidden("Forbidden: To access Django admin shell you must have access the admin site")
        elif ADMIN_SHELL_ONLY_DEBUG_MODE and settings.DEBUG is False:
            return HttpResponseForbidden("Forbidden :Django admin shell require DEBUG mode")
        elif ADMIN_SHELL_ONLY_FOR_SUPERUSER and request.user.is_superuser is False:
            return HttpResponseForbidden("Forbidden: To access Django admin shell you must be superuser")
        return super(Shell, self).dispatch(request, *args, **kwargs)
项目:django-admin-shell    作者:djk2    | 项目源码 | 文件源码
def dispatch(self, request, *args, **kwargs):
        """Override to check settings"""
        if django.VERSION < (1, 10):
            is_auth = request.user.is_authenticated()
        else:
            is_auth = request.user.is_authenticated

        if not ADMIN_SHELL_ENABLE:
            return HttpResponseNotFound("Not found: Django admin shell is not enabled")
        elif is_auth is False or request.user.is_staff is False:
            return HttpResponseForbidden("Forbidden: To access Django admin shell you must have access the admin site")
        elif ADMIN_SHELL_ONLY_DEBUG_MODE and settings.DEBUG is False:
            return HttpResponseForbidden("Forbidden :Django admin shell require DEBUG mode")
        elif ADMIN_SHELL_ONLY_FOR_SUPERUSER and request.user.is_superuser is False:
            return HttpResponseForbidden("Forbidden: To access Django admin shell you must be superuser")
        return super(Shell, self).dispatch(request, *args, **kwargs)
项目:django-username-email    作者:tmm    | 项目源码 | 文件源码
def clean(self):
        email = self.cleaned_data.get('email')
        password = self.cleaned_data.get('password')

        if email and password:
            if django.VERSION >= (1, 11):
                self.user_cache = authenticate(self.request, email=email, password=password)
            else:
                self.user_cache = authenticate(email=email, password=password)
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data
项目:django-requestlogging    作者:tarkatronic    | 项目源码 | 文件源码
def filter(self, record):
        """
        Adds information from the request to the logging *record*.

        If certain information cannot be extracted from ``self.request``,
        a hyphen ``'-'`` is substituted as a placeholder.
        """
        request = self.request
        # Basic
        record.request_method = getattr(request, 'method', '-')
        record.path_info = getattr(request, 'path_info', '-')
        # User
        user = getattr(request, 'user', None)
        if django.VERSION < (1, 10) and user and not user.is_anonymous():
            record.username = user.username
        elif django.VERSION > (1, 10) and user and not user.is_anonymous:
            record.username = user.username
        else:
            record.username = '-'
        # Headers
        META = getattr(request, 'META', {})  # NOQA: N806
        record.remote_addr = META.get('REMOTE_ADDR', '-')
        record.server_protocol = META.get('SERVER_PROTOCOL', '-')
        record.http_user_agent = META.get('HTTP_USER_AGENT', '-')
        return True
项目:baya    作者:counsyl    | 项目源码 | 文件源码
def _build_mock_request(self, user=None, get=None, post=None):
        request = MagicMock()
        if user:
            request.user = user
            if django.VERSION[:2] >= (1, 10):
                # Django 1.10 made `User.is_authenticated` into a property for
                # some reason.
                request.user.is_authenticated.__get__ = MagicMock(return_value=True)  # nopep8
            else:
                request.user.is_authenticated = MagicMock(return_value=True)
        else:
            request.user = AnonymousUser()
        request.GET = {}
        request.POST = {}
        request.resolver_match.kwargs = {}
        if get is not None:
            request.GET.update(get)
        if post is not None:
            request.POST.update(post)
        return request
项目:baya    作者:counsyl    | 项目源码 | 文件源码
def _build_mock_request(self, user=None, get=None, post=None):
        request = MagicMock()
        if user:
            request.user = user
            if django.VERSION[:2] >= (1, 10):
                # Django 1.10 made `User.is_authenticated` into a property for
                # some reason.
                request.user.is_authenticated.__get__ = MagicMock(return_value=True)  # nopep8
            else:
                request.user.is_authenticated = MagicMock(return_value=True)
        else:
            request.user = AnonymousUser()
        request.GET = {}
        request.POST = {}
        request.resolver_match.kwargs = {}
        if get is not None:
            request.GET.update(get)
        if post is not None:
            request.POST.update(post)
        return request
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
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)
    ]


# field.rel is deprecated from 1.9 onwards
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def _test(request, form_class):
    passed = False
    if request.POST:
        form = form_class(request.POST)
        if form.is_valid():
            passed = True
    else:
        form = form_class()

    t = _get_template(TEST_TEMPLATE)

    if django.VERSION >= (1, 9):
        return HttpResponse(
            t.render(context=dict(passed=passed, form=form), request=request))
    else:
        return HttpResponse(
            t.render(RequestContext(request, dict(passed=passed, form=form))))
项目:importacsv    作者:rasertux    | 项目源码 | 文件源码
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)
项目:silica    作者:zagaran    | 项目源码 | 文件源码
def test_angular_input_field(self):
        my_form = SampleForm()
        template = u'{% angular_input_field my_form.name model_name params %}'
        context = {'my_form': my_form,
                   'model_name': 'yourname',
                   'params': {}}
        # Django 1.10 changes the rendering of boolean attributes
        if VERSION[1] > 9:
            output = (u'<input class="form-control" id="id_name" '
                      u'maxlength="100" name="name" ng-model='
                      u'"yourname.fields.name" type="text" required />')
        else:
            output = (u'<input class="form-control" id="id_name" '
                      u'maxlength="100" name="name" ng-model='
                      u'"yourname.fields.name" required="true" type="text" />')
        self.tag_test(template, context, output)
        # repeat test, with bound form
        my_form = SampleForm({'name': 'Joe Bloggs'})
        self.tag_test(template, context, output)
项目:apm-agent-python    作者:elastic    | 项目源码 | 文件源码
def test_template_rendering(should_collect, django_elasticapm_client, client):
    should_collect.return_value = False
    with override_settings(**middleware_setting(django.VERSION,
                                            ['elasticapm.contrib.django.middleware.TracingMiddleware'])):
        client.get(reverse('render-heavy-template'))
        client.get(reverse('render-heavy-template'))
        client.get(reverse('render-heavy-template'))

    transactions = django_elasticapm_client.instrumentation_store.get_all()

    assert len(transactions) == 3
    spans = transactions[0]['spans']
    assert len(spans) == 2, [t['name'] for t in spans]

    kinds = ['code', 'template.django']
    assert set([t['type'] for t in spans]) == set(kinds)

    assert spans[0]['type'] == 'code'
    assert spans[0]['name'] == 'something_expensive'
    assert spans[0]['parent'] == 0

    assert spans[1]['type'] == 'template.django'
    assert spans[1]['name'] == 'list_users.html'
    assert spans[1]['parent'] is None
项目:apm-agent-python    作者:elastic    | 项目源码 | 文件源码
def test_template_rendering_django18_jinja2(should_collect, django_elasticapm_client, client):
    should_collect.return_value = False
    with override_settings(
            TEMPLATES=TEMPLATES,
            **middleware_setting(django.VERSION,
                                 ['elasticapm.contrib.django.middleware.TracingMiddleware'])
        ):
        client.get(reverse('render-jinja2-template'))
        client.get(reverse('render-jinja2-template'))
        client.get(reverse('render-jinja2-template'))

    transactions = django_elasticapm_client.instrumentation_store.get_all()

    assert len(transactions) == 3
    spans = transactions[0]['spans']
    assert len(spans) == 1, [t['name'] for t in spans]

    kinds = ['template.jinja2']
    assert set([t['type'] for t in spans]) == set(kinds)

    assert spans[0]['type'] == 'template.jinja2'
    assert spans[0]['name'] == 'jinja2_template.html'
    assert spans[0]['parent'] is None
项目:python-ibmdb-django    作者:ibmdb    | 项目源码 | 文件源码
def value_to_db_datetime( self, value ):
        if value is None:
            return None

        if( djangoVersion[0:2] <= ( 1, 3 ) ):
            #DB2 doesn't support time zone aware datetime
            if ( value.tzinfo is not None ):
                raise ValueError( "Timezone aware datetime not supported" )
            else:
                return value
        else:
            if is_aware(value):
                if settings.USE_TZ:
                    value = value.astimezone( utc ).replace( tzinfo=None )
                else:
                    raise ValueError( "Timezone aware datetime not supported" )
            return unicode( value )
项目:python-ibmdb-django    作者:ibmdb    | 项目源码 | 文件源码
def get_table_description( self, cursor, table_name ):
        qn = self.connection.ops.quote_name
        description = []
        table_type = 'T'
        if not _IS_JYTHON:
            dbms_name='dbms_name'
            schema = cursor.connection.get_current_schema()
            if getattr(cursor.connection, dbms_name) != 'DB2':
                sql = "SELECT TYPE FROM SYSCAT.TABLES WHERE TABSCHEMA='%(schema)s' AND TABNAME='%(table)s'" % {'schema': schema.upper(), 'table': table_name.upper()}
            else:
                sql = "SELECT TYPE FROM SYSIBM.SYSTABLES WHERE CREATOR='%(schema)s' AND NAME='%(table)s'" % {'schema': schema.upper(), 'table': table_name.upper()}
            cursor.execute(sql)
            table_type = cursor.fetchone()[0]

        if table_type != 'X':
            cursor.execute( "SELECT * FROM %s FETCH FIRST 1 ROWS ONLY" % qn( table_name ) )
            if djangoVersion < (1, 6):
                for desc in cursor.description:
                    description.append( [ desc[0].lower(), ] + desc[1:] )
            else:
                for desc in cursor.description:
                    description.append(FieldInfo(*[desc[0].lower(), ] + desc[1:]))

        return description
项目:python-ibmdb-django    作者:ibmdb    | 项目源码 | 文件源码
def __init__( self, *args ):
        super( DatabaseWrapper, self ).__init__( *args )
        self.ops = DatabaseOperations( self )
        if( djangoVersion[0:2] <= ( 1, 0 ) ):
            self.client = DatabaseClient()
        else:
            self.client = DatabaseClient( self )
        if( djangoVersion[0:2] <= ( 1, 2 ) ):
            self.features = DatabaseFeatures()
        else:
            self.features = DatabaseFeatures( self )
        self.creation = DatabaseCreation( self )

        if( djangoVersion[0:2] >= ( 1, 8 ) ): 
            self.data_types=self.creation.data_types
            self.data_type_check_constraints=self.creation.data_type_check_constraints

        self.introspection = DatabaseIntrospection( self )
        if( djangoVersion[0:2] <= ( 1, 1 ) ):
            self.validation = DatabaseValidation()
        else:
            self.validation = DatabaseValidation( self )
        self.databaseWrapper = Base.DatabaseWrapper()

    # Method to check if connection is live or not.
项目:graphene-jwt-auth    作者:darwin4031    | 项目源码 | 文件源码
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)
    ]


# field.rel is deprecated from 1.9 onwards
项目:xadmin-markdown-editor    作者:bluenknight    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        if value is None:
            value = ""
        if VERSION < (1, 11):
            final_attrs = self.build_attrs(attrs, name=name)
        else:
            final_attrs = self.build_attrs(attrs, {'name': name})

        if "class" not in final_attrs:
            final_attrs["class"] = ""
        final_attrs["class"] += " wmd-input"
        template = loader.get_template(self.template)

        # Compatibility fix:
        # see https://github.com/timmyomahony/django-pagedown/issues/42
        context = {
            "attrs": flatatt(final_attrs),
            "body": conditional_escape(force_unicode(value)),
            "id": final_attrs["id"],
            "show_preview": self.show_preview,
        }
        context = Context(context) if VERSION < (1, 9) else context
        return template.render(context)
项目:jianshu-api    作者:strugglingyouth    | 项目源码 | 文件源码
def template_render(template, context=None, request=None):
    """
    Passing Context or RequestContext to Template.render is deprecated in 1.9+,
    see https://github.com/django/django/pull/3883 and
    https://github.com/django/django/blob/1.9rc1/django/template/backends/django.py#L82-L84

    :param template: Template instance
    :param context: dict
    :param request: Request instance
    :return: rendered template as SafeText instance
    """
    if django.VERSION < (1, 8) or isinstance(template, Template):
        if request:
            context = RequestContext(request, context)
        else:
            context = Context(context)
        return template.render(context)
    # backends template, e.g. django.template.backends.django.Template
    else:
        return template.render(context, request=request)
项目:django-twilio-tfa    作者:rtindru    | 项目源码 | 文件源码
def assertRedirects(self, response, expected_url,
                        fetch_redirect_response=True,
                        **kwargs):
        if django.VERSION >= (1, 7,):
            super(TestCase, self).assertRedirects(
                response,
                expected_url,
                fetch_redirect_response=fetch_redirect_response,
                **kwargs)

        elif fetch_redirect_response:
            super(TestCase, self).assertRedirects(
                response,
                expected_url,
                **kwargs)
        else:
            self.assertEqual(302, response.status_code)
            actual_url = response['location']
            if expected_url[0] == '/':
                parts = list(urlparse(actual_url))
                parts[0] = parts[1] = ''
                actual_url = urlunparse(parts)
            self.assertEqual(expected_url, actual_url)
项目:cetusshop    作者:icetusorg    | 项目源码 | 文件源码
def _test(request, form_class):
    passed = False
    if request.POST:
        form = form_class(request.POST)
        if form.is_valid():
            passed = True
    else:
        form = form_class()

    t = _get_template(TEST_TEMPLATE)

    if django.VERSION >= (1, 9):
        return HttpResponse(
            t.render(context=dict(passed=passed, form=form), request=request))
    else:
        return HttpResponse(
            t.render(RequestContext(request, dict(passed=passed, form=form))))
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def get_version(version=None):
    "Returns 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 str(main + sub)
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
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')
项目:pyup-django    作者:pyupio    | 项目源码 | 文件源码
def registration_status_view(self, request):
        request.current_app = self.admin_site.name

        version = "{}.{}.{}".format(VERSION[0], VERSION[1], VERSION[2])

        insecure = self.is_insecure(version)

        data = {
            "django_version": version,
            "insecure": insecure,
        }

        template = "".join(render_to_string("insecure.html", data).splitlines())

        data["template"] = template
        data["run_again_at"] = time.time() + 60 * 60 * 24
        request.session["pyup_django"] = data
        return HttpResponse(json.dumps(data), content_type="application/json")
项目:django-ios-notifications    作者:nnsnodnb    | 项目源码 | 文件源码
def run_tests(base_dir=None, apps=None, verbosity=1, interavtive=False):
    base_dir = base_dir or os.path.dirname(__file__)
    os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
    sys.path.insert(0, os.path.join(base_dir, 'src'))
    sys.path.insert(0, os.path.join(base_dir, 'tests'))

    import django
    if django.VERSION >= (1,7):
        django.setup()

    from django.conf import settings
    from django.test.utils import get_runner
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=verbosity,
                             interavtive=interavtive,
                             failfast=False)
    if apps:
        app_tests = [x.strip() for x in apps if x]
    else:
        app_tests = [
            'notification'
        ]
    failures = test_runner.run_tests(app_tests)
    sys.exit(bool(failures))
项目:django-autocomplete-light-selectize    作者:litchfield    | 项目源码 | 文件源码
def render_options(self, *args):
        """
        Variation to DAL default, which adds selected_choices to choices
        """
        selected_choices_arg = 1 if VERSION < (1, 10) else 0

        # Filter out None values, not needed for autocomplete
        selected_choices = [c for c in args[selected_choices_arg] if c]

        if self.url:
            all_choices = copy.copy(self.choices)
            self.choices += [ (c, c) for c in selected_choices ]
            self.filter_choices_to_render(selected_choices)

        html = super(WidgetMixin, self).render_options(*args)

        if self.url:
            self.choices = all_choices

        return html
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def get_version(version=None):
    "Returns 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 str(main + sub)
项目:liberator    作者:libscie    | 项目源码 | 文件源码
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')
项目:the-contract-site    作者:shadytradesman    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        if value is None:
            value = ""
        if VERSION < (1, 11):
            final_attrs = self.build_attrs(attrs, name=name)
        else:
            final_attrs = self.build_attrs(attrs, {'name': name})
        final_attrs = self.build_attrs(final_attrs, self.attrs)
        if "class" not in final_attrs:
            final_attrs["class"] = ""
        final_attrs["class"] += " wmd-input"
        template = loader.get_template(self.template)

        # Compatibility fix:
        # see https://github.com/timmyomahony/django-pagedown/issues/42
        context = {
            "attrs": flatatt(final_attrs),
            "body": conditional_escape(force_unicode(value)),
            "id": final_attrs["id"],
            "show_preview": self.show_preview,
        }
        context = Context(context) if VERSION < (1, 9) else context
        return template.render(context)
项目:django-groupadmin-users    作者:Microdisseny    | 项目源码 | 文件源码
def test_form_edit(self):
        if VERSION <= (1, 9):
            url = '/admin/auth/group/1/'
        else:
            url = '/admin/auth/group/1/change/'

        # GET the import form
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)

        data = {
            'name': 'admins',
            'permissions': ('1', '2'),
            'users': ('1',),
        }
        response = self.client.post(url, data, follow=True)
        self.assertEqual(response.status_code, 200)

        group = Group.objects.all().last()
        self.assertTrue(group.name == 'admins')
        self.assertTrue(group.permissions.all().count() == 2)
        self.assertTrue(group.user_set.first() == self.admin)
项目:mozilla-django-oidc    作者:mozilla    | 项目源码 | 文件源码
def get_next_url(request, redirect_field_name):
    """Retrieves next url from request

    Note: This verifies that the url is safe before returning it. If the url
    is not safe, this returns None.

    :arg HttpRequest request: the http request
    :arg str redirect_field_name: the name of the field holding the next url

    :returns: safe url or None

    """
    next_url = request.GET.get(redirect_field_name)
    if next_url:
        kwargs = {
            'url': next_url,
            'host': request.get_host()
        }
        # NOTE(willkg): Django 1.11+ allows us to require https, too.
        if django.VERSION >= (1, 11):
            kwargs['require_https'] = request.is_secure()
        is_safe = is_safe_url(**kwargs)
        if is_safe:
            return next_url
    return None
项目:mozilla-django-oidc    作者:mozilla    | 项目源码 | 文件源码
def test_https(self):
        # If the request is for HTTPS and the next url is HTTPS, then that
        # works with all Djangos.
        req = self.factory.get(
            '/',
            data={'next': 'https://testserver/foo'},
            secure=True,
        )
        self.assertEquals(req.is_secure(), True)
        next_url = views.get_next_url(req, 'next')
        self.assertEqual(next_url, 'https://testserver/foo')

        # For Django 1.11+, if the request is for HTTPS and the next url is
        # HTTP, then that fails.
        if django.VERSION >= (1, 11):
            req = self.factory.get(
                '/',
                data={'next': 'http://testserver/foo'},
                secure=True,
            )
            self.assertEquals(req.is_secure(), True)
            next_url = views.get_next_url(req, 'next')
            self.assertEqual(next_url, None)
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
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:
    # main = X.Y[.Z]
    # sub = .devN - for pre-alpha releases
    #     | {a|b|c}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': 'c'}
        sub = mapping[version[3]] + str(version[4])

    return str(main + sub)
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
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')
项目:wagtail-translation    作者:skirsdeda    | 项目源码 | 文件源码
def full_clean(self, *args, **kwargs):
    # autogenerate slugs for non-empty title translation
    for lang_code in mt_settings.AVAILABLE_LANGUAGES:
        title_field = build_localized_fieldname('title', lang_code)
        slug_field = build_localized_fieldname('slug', lang_code)

        title = getattr(self, title_field)
        slug = getattr(self, slug_field)
        if title and not slug:
            if DJANGO_VERSION >= (1, 9):
                base_slug = slugify(title, allow_unicode=True)
            else:
                base_slug = slugify(title)

            if base_slug:
                setattr(self, slug_field, self._get_autogenerated_lang_slug(base_slug, lang_code))

    super(Page, self).full_clean(*args, **kwargs)
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def DjangoVersion():
  """Discover the version of Django installed.

  Returns:
    A distutils.version.LooseVersion.
  """
  try:

    __import__('django.' + _DESIRED_DJANGO_VERSION)
  except ImportError:
    pass
  import django
  try:
    return distutils.version.LooseVersion('.'.join(map(str, django.VERSION)))
  except AttributeError:

    return LooseVersion(django.VERSION)
项目:django-excel-response    作者:tarkatronic    | 项目源码 | 文件源码
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)]
项目:django-performance-testing    作者:PaesslerAG    | 项目源码 | 文件源码
def __init__(self, nodelist, limit_name, **limit_kwargs):
        extra_kwargs = {}
        if django.VERSION[:2] > (1, 8):
            extra_kwargs['func'] = None
        super(DjptLimitNode, self).__init__(
            takes_context=False, args=[limit_name], kwargs=limit_kwargs,
            **extra_kwargs
        )
        self.nodelist = nodelist
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def force_no_ordering(self):
        """
        "ORDER BY NULL" prevents MySQL from implicitly ordering by grouped
        columns. If no ordering would otherwise be applied, we don't want any
        implicit sorting going on.
        """
        if django.VERSION >= (1, 8):
            return [(None, ("NULL", [], False))]
        else:
            return ["NULL"]
项目:MetaCI    作者:SalesforceFoundation    | 项目源码 | 文件源码
def get_context_data(self, **kwargs):
        context = super(AboutView, self).get_context_data(**kwargs)

        # django
        context['DJANGO_VERSION'] = '{}.{}.{}'.format(
            django.VERSION[0], # major
            django.VERSION[1], # minor
            django.VERSION[2], # micro
        )

        # python
        context['PYTHON_VERSION'] = '{}.{}.{}'.format(
            sys.version_info.major,
            sys.version_info.minor,
            sys.version_info.micro,
        )

        # Salesforce DX
        out = subprocess.check_output(['sfdx', '--version'])
        match = re.match(r'sfdx-cli/(\d+.\d+.\d+)-.+', out)
        if match:
            context['SFDX_CLI_VERSION'] = match.group(1)

        # cumulusci
        context['CUMULUSCI_VERSION'] = get_installed_version('cumulusci')

        # heroku
        heroku_env_vars = [
            'HEROKU_APP_ID',
            'HEROKU_APP_NAME',
            'HEROKU_DYNO_ID',
            'HEROKU_RELEASE_CREATED_AT',
            'HEROKU_RELEASE_VERSION',
            'HEROKU_SLUG_COMMIT',
            'HEROKU_SLUG_DESCRIPTION',
        ]
        for var in heroku_env_vars:
            context[var] = os.environ.get(var,
                'Heroku dyno metadata not found')

        return context