Python django.utils.six.string_types() Examples

The following are 30 code examples of django.utils.six.string_types(). 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.utils.six , or try the search function .
Example #1
Source File: layermapping.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def check_srs(self, source_srs):
        "Checks the compatibility of the given spatial reference object."

        if isinstance(source_srs, SpatialReference):
            sr = source_srs
        elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()):
            sr = source_srs.srs
        elif isinstance(source_srs, (int, six.string_types)):
            sr = SpatialReference(source_srs)
        else:
            # Otherwise just pulling the SpatialReference from the layer
            sr = self.layer.srs

        if not sr:
            raise LayerMapError('No source reference system defined.')
        else:
            return sr 
Example #2
Source File: debug.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, request, exc_type, exc_value, tb, is_email=False):
        self.request = request
        self.filter = get_exception_reporter_filter(self.request)
        self.exc_type = exc_type
        self.exc_value = exc_value
        self.tb = tb
        self.is_email = is_email

        self.template_info = None
        self.template_does_not_exist = False
        self.loader_debug_info = None

        # Handle deprecated string exceptions
        if isinstance(self.exc_type, six.string_types):
            self.exc_value = Exception('Deprecated String Exception: %r' % self.exc_type)
            self.exc_type = type(self.exc_value) 
Example #3
Source File: i18n.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def get_formats():
    """
    Returns all formats strings required for i18n to work
    """
    FORMAT_SETTINGS = (
        'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
        'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
        'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
        'THOUSAND_SEPARATOR', 'NUMBER_GROUPING',
        'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS'
    )
    result = {}
    for module in [settings] + get_format_modules(reverse=True):
        for attr in FORMAT_SETTINGS:
            result[attr] = get_format(attr)
    formats = {}
    for k, v in result.items():
        if isinstance(v, (six.string_types, int)):
            formats[k] = smart_text(v)
        elif isinstance(v, (tuple, list)):
            formats[k] = [smart_text(value) for value in v]
    return formats 
Example #4
Source File: archive.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _archive_cls(file):
        cls = None
        if isinstance(file, six.string_types):
            filename = file
        else:
            try:
                filename = file.name
            except AttributeError:
                raise UnrecognizedArchiveFormat(
                    "File object not a recognized archive format.")
        base, tail_ext = os.path.splitext(filename.lower())
        cls = extension_map.get(tail_ext)
        if not cls:
            base, ext = os.path.splitext(base)
            cls = extension_map.get(ext)
        if not cls:
            raise UnrecognizedArchiveFormat(
                "Path not a recognized archive format: %s" % filename)
        return cls 
Example #5
Source File: formats.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def sanitize_separators(value):
    """
    Sanitizes a value according to the current decimal and
    thousand separator setting. Used with form field input.
    """
    if settings.USE_L10N and isinstance(value, six.string_types):
        parts = []
        decimal_separator = get_format('DECIMAL_SEPARATOR')
        if decimal_separator in value:
            value, decimals = value.split(decimal_separator, 1)
            parts.append(decimals)
        if settings.USE_THOUSAND_SEPARATOR:
            thousand_sep = get_format('THOUSAND_SEPARATOR')
            if thousand_sep == '.' and value.count('.') == 1 and len(value.split('.')[-1]) != 3:
                # Special case where we suspect a dot meant decimal separator (see #22171)
                pass
            else:
                for replacement in {
                        thousand_sep, unicodedata.normalize('NFKD', thousand_sep)}:
                    value = value.replace(replacement, '')
        parts.append(value)
        value = '.'.join(reversed(parts))
    return value 
Example #6
Source File: fields.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def database_forwards(self, app_label, schema_editor, from_state, to_state):
        to_model = to_state.apps.get_model(app_label, self.model_name)
        if self.allow_migrate_model(schema_editor.connection.alias, to_model):
            from_model = from_state.apps.get_model(app_label, self.model_name)
            from_field = from_model._meta.get_field(self.name)
            to_field = to_model._meta.get_field(self.name)
            # If the field is a relatedfield with an unresolved rel.to, just
            # set it equal to the other field side. Bandaid fix for AlterField
            # migrations that are part of a RenameModel change.
            if from_field.rel and from_field.rel.to:
                if isinstance(from_field.rel.to, six.string_types):
                    from_field.rel.to = to_field.rel.to
                elif to_field.rel and isinstance(to_field.rel.to, six.string_types):
                    to_field.rel.to = from_field.rel.to
            if not self.preserve_default:
                to_field.default = self.field.default
            schema_editor.alter_field(from_model, from_field, to_field)
            if not self.preserve_default:
                to_field.default = NOT_PROVIDED 
Example #7
Source File: models.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def references_model(self, name, app_label=None):
        strings_to_check = [self.name]
        # Check we didn't inherit from the model
        for base in self.bases:
            if isinstance(base, six.string_types):
                strings_to_check.append(base.split(".")[-1])
        # Check we have no FKs/M2Ms with it
        for fname, field in self.fields:
            if field.rel:
                if isinstance(field.rel.to, six.string_types):
                    strings_to_check.append(field.rel.to.split(".")[-1])
        # Now go over all the strings and compare them
        for string in strings_to_check:
            if string.lower() == name.lower():
                return True
        return False 
Example #8
Source File: signals.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
        if isinstance(sender, six.string_types):
            try:
                app_label, model_name = sender.split('.')
            except ValueError:
                raise ValueError(
                    "Specified sender must either be a model or a "
                    "model name of the 'app_label.ModelName' form."
                )
            try:
                sender = apps.get_registered_model(app_label, model_name)
            except LookupError:
                ref = (app_label, model_name)
                refs = self.unresolved_references.setdefault(ref, [])
                refs.append((receiver, weak, dispatch_uid))
                return
        super(ModelSignal, self).connect(
            receiver, sender=sender, weak=weak, dispatch_uid=dispatch_uid
        ) 
Example #9
Source File: related.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _check_referencing_to_swapped_model(self):
        if (self.rel.to not in apps.get_models() and
                not isinstance(self.rel.to, six.string_types) and
                self.rel.to._meta.swapped):
            model = "%s.%s" % (
                self.rel.to._meta.app_label,
                self.rel.to._meta.object_name
            )
            return [
                checks.Error(
                    ("Field defines a relation with the model '%s', "
                     "which has been swapped out.") % model,
                    hint="Update the relation to point at 'settings.%s'." % self.rel.to._meta.swappable,
                    obj=self,
                    id='fields.E301',
                )
            ]
        return [] 
Example #10
Source File: urlparser.py    From py2swagger with MIT License 6 votes vote down vote up
def get_apis(self, url_patterns=None, urlconf=None, filter_path=None, exclude_namespaces=None):
        """
        Returns all the DRF APIViews found in the project URLs
        patterns -- supply list of patterns (optional)
        exclude_namespaces -- list of namespaces to ignore (optional)
        """

        if not url_patterns and urlconf:
            if isinstance(urlconf, six.string_types):
                urls = import_module(urlconf)
            else:
                urls = urlconf
            url_patterns = urls.urlpatterns
        elif not url_patterns and not urlconf:
            urls = import_module(settings.ROOT_URLCONF)
            url_patterns = urls.urlpatterns

        formatted_apis = self.format_api_patterns(
            url_patterns,
            filter_path=filter_path,
            exclude_namespaces=exclude_namespaces,
        )

        return formatted_apis 
Example #11
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def enable(self):
        self.options = {}
        for name, operations in self.operations:
            try:
                # When called from SimpleTestCase.setUpClass, values may be
                # overridden several times; cumulate changes.
                value = self.options[name]
            except KeyError:
                value = list(getattr(settings, name, []))
            for action, items in operations.items():
                # items my be a single value or an iterable.
                if isinstance(items, six.string_types):
                    items = [items]
                if action == 'append':
                    value = value + [item for item in items if item not in value]
                elif action == 'prepend':
                    value = [item for item in items if item not in value] + value
                elif action == 'remove':
                    value = [item for item in value if item not in items]
                else:
                    raise ValueError("Unsupported action: %s" % action)
            self.options[name] = value
        super(modify_settings, self).enable() 
Example #12
Source File: testcases.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def assertJSONEqual(self, raw, expected_data, msg=None):
        """
        Asserts that the JSON fragments raw and expected_data are equal.
        Usual JSON non-significant whitespace rules apply as the heavyweight
        is delegated to the json library.
        """
        try:
            data = json.loads(raw)
        except ValueError:
            self.fail("First argument is not valid JSON: %r" % raw)
        if isinstance(expected_data, six.string_types):
            try:
                expected_data = json.loads(expected_data)
            except ValueError:
                self.fail("Second argument is not valid JSON: %r" % expected_data)
        self.assertEqual(data, expected_data, msg=msg) 
Example #13
Source File: testcases.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def assertJSONNotEqual(self, raw, expected_data, msg=None):
        """
        Asserts that the JSON fragments raw and expected_data are not equal.
        Usual JSON non-significant whitespace rules apply as the heavyweight
        is delegated to the json library.
        """
        try:
            data = json.loads(raw)
        except ValueError:
            self.fail("First argument is not valid JSON: %r" % raw)
        if isinstance(expected_data, six.string_types):
            try:
                expected_data = json.loads(expected_data)
            except ValueError:
                self.fail("Second argument is not valid JSON: %r" % expected_data)
        self.assertNotEqual(data, expected_data, msg=msg) 
Example #14
Source File: html.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def finalize(self):
        def rstrip_last_element(children):
            if children:
                if isinstance(children[-1], six.string_types):
                    children[-1] = children[-1].rstrip()
                    if not children[-1]:
                        children.pop()
                        children = rstrip_last_element(children)
            return children

        rstrip_last_element(self.children)
        for i, child in enumerate(self.children):
            if isinstance(child, six.string_types):
                self.children[i] = child.strip()
            elif hasattr(child, 'finalize'):
                child.finalize() 
Example #15
Source File: html.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _count(self, element, count=True):
        if not isinstance(element, six.string_types):
            if self == element:
                return 1
        i = 0
        for child in self.children:
            # child is text content and element is also text content, then
            # make a simple "text" in "text"
            if isinstance(child, six.string_types):
                if isinstance(element, six.string_types):
                    if count:
                        i += child.count(element)
                    elif element in child:
                        return 1
            else:
                i += child._count(element, count=count)
                if not count and i:
                    return i
        return i 
Example #16
Source File: html.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def parse_html(html):
    """
    Takes a string that contains *valid* HTML and turns it into a Python object
    structure that can be easily compared against other HTML on semantic
    equivalence. Syntactical differences like which quotation is used on
    arguments will be ignored.

    """
    parser = Parser()
    parser.feed(html)
    parser.close()
    document = parser.root
    document.finalize()
    # Removing ROOT element if it's not necessary
    if len(document.children) == 1:
        if not isinstance(document.children[0], six.string_types):
            document = document.children[0]
    return document 
Example #17
Source File: factory.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def fromfile(file_h):
    """
    Given a string file name, returns a GEOSGeometry. The file may contain WKB,
    WKT, or HEX.
    """
    # If given a file name, get a real handle.
    if isinstance(file_h, six.string_types):
        with open(file_h, 'rb') as file_h:
            buf = file_h.read()
    else:
        buf = file_h.read()

    # If we get WKB need to wrap in memoryview(), so run through regexes.
    if isinstance(buf, bytes):
        try:
            decoded = buf.decode()
            if wkt_regex.match(decoded) or hex_regex.match(decoded):
                return GEOSGeometry(decoded)
        except UnicodeDecodeError:
            pass
    else:
        return GEOSGeometry(buf)

    return GEOSGeometry(six.memoryview(buf)) 
Example #18
Source File: related.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def contribute_to_class(self, cls, name, virtual_only=False):
        sup = super(RelatedField, self)

        # Store the opts for related_query_name()
        self.opts = cls._meta

        if hasattr(sup, 'contribute_to_class'):
            sup.contribute_to_class(cls, name, virtual_only=virtual_only)

        if not cls._meta.abstract and self.rel.related_name:
            related_name = force_text(self.rel.related_name) % {
                'class': cls.__name__.lower(),
                'app_label': cls._meta.app_label.lower()
            }
            self.rel.related_name = related_name
        other = self.rel.to
        if isinstance(other, six.string_types) or other._meta.pk is None:
            def resolve_related_class(field, model, cls):
                field.rel.to = model
                field.do_related_class(model, cls)
            add_lazy_relation(cls, self, other, resolve_related_class)
        else:
            self.do_related_class(other, cls) 
Example #19
Source File: related.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def swappable_setting(self):
        """
        Gets the setting that this is powered from for swapping, or None
        if it's not swapped in / marked with swappable=False.
        """
        if self.swappable:
            # Work out string form of "to"
            if isinstance(self.rel.to, six.string_types):
                to_string = self.rel.to
            else:
                to_string = "%s.%s" % (
                    self.rel.to._meta.app_label,
                    self.rel.to._meta.object_name,
                )
            # See if anything swapped/swappable matches
            for model in apps.get_models(include_swapped=True):
                if model._meta.swapped:
                    if model._meta.swapped == to_string:
                        return model._meta.swappable
                if ("%s.%s" % (model._meta.app_label, model._meta.object_name)) == to_string and model._meta.swappable:
                    return model._meta.swappable
        return None 
Example #20
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _check_choices(self):
        if self.choices:
            if (isinstance(self.choices, six.string_types) or
                    not is_iterable(self.choices)):
                return [
                    checks.Error(
                        "'choices' must be an iterable (e.g., a list or tuple).",
                        hint=None,
                        obj=self,
                        id='fields.E004',
                    )
                ]
            elif any(isinstance(choice, six.string_types) or
                     not is_iterable(choice) or len(choice) != 2
                     for choice in self.choices):
                return [
                    checks.Error(
                        ("'choices' must be an iterable containing "
                         "(actual value, human readable name) tuples."),
                        hint=None,
                        obj=self,
                        id='fields.E005',
                    )
                ]
            else:
                return []
        else:
            return [] 
Example #21
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def _format(self, value):
        if isinstance(value, six.string_types):
            return value
        else:
            return self.format_number(value) 
Example #22
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def to_python(self, value):
        if isinstance(value, six.string_types) or value is None:
            return value
        return smart_text(value) 
Example #23
Source File: __init__.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_prep_value(self, value):
        value = super(TextField, self).get_prep_value(value)
        if isinstance(value, six.string_types) or value is None:
            return value
        return smart_text(value) 
Example #24
Source File: utils.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def __getitem__(self, key):
        if isinstance(key, six.string_types):
            for subcontext in self:
                if key in subcontext:
                    return subcontext[key]
            raise KeyError(key)
        else:
            return super(ContextList, self).__getitem__(key) 
Example #25
Source File: widgets.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def value_from_datadict(self, data, files, name):
        if name not in data:
            # A missing value means False because HTML form submission does not
            # send results for unselected checkboxes.
            return False
        value = data.get(name)
        # Translate true and false strings to boolean values.
        values = {'true': True, 'false': False}
        if isinstance(value, six.string_types):
            value = values.get(value.lower(), value)
        return bool(value) 
Example #26
Source File: related.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def contribute_to_class(self, cls, name, **kwargs):
        # To support multiple relations to self, it's useful to have a non-None
        # related name on symmetrical relations for internal reasons. The
        # concept doesn't make a lot of sense externally ("you want me to
        # specify *what* on my non-reversible relation?!"), so we set it up
        # automatically. The funky name reduces the chance of an accidental
        # clash.
        if self.rel.symmetrical and (self.rel.to == "self" or self.rel.to == cls._meta.object_name):
            self.rel.related_name = "%s_rel_+" % name

        super(ManyToManyField, self).contribute_to_class(cls, name, **kwargs)

        # The intermediate m2m model is not auto created if:
        #  1) There is a manually specified intermediate, or
        #  2) The class owning the m2m field is abstract.
        #  3) The class owning the m2m field has been swapped out.
        if not self.rel.through and not cls._meta.abstract and not cls._meta.swapped:
            self.rel.through = create_many_to_many_intermediary_model(self, cls)

        # Add the descriptor for the m2m relation
        setattr(cls, self.name, ReverseManyRelatedObjectsDescriptor(self))

        # Set up the accessor for the m2m table name for the relation
        self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta)

        # Populate some necessary rel arguments so that cross-app relations
        # work correctly.
        if isinstance(self.rel.through, six.string_types):
            def resolve_through_model(field, model, cls):
                field.rel.through = model
            add_lazy_relation(cls, self, self.rel.through, resolve_through_model) 
Example #27
Source File: list.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_queryset(self):
        """
        Return the list of items for this view.

        The return value must be an iterable and may be an instance of
        `QuerySet` in which case `QuerySet` specific behavior will be enabled.
        """
        if self.queryset is not None:
            queryset = self.queryset
            if isinstance(queryset, QuerySet):
                queryset = queryset.all()
        elif self.model is not None:
            queryset = self.model._default_manager.all()
        else:
            raise ImproperlyConfigured(
                "%(cls)s is missing a QuerySet. Define "
                "%(cls)s.model, %(cls)s.queryset, or override "
                "%(cls)s.get_queryset()." % {
                    'cls': self.__class__.__name__
                }
            )
        ordering = self.get_ordering()
        if ordering:
            if isinstance(ordering, six.string_types):
                ordering = (ordering,)
            queryset = queryset.order_by(*ordering)

        return queryset 
Example #28
Source File: i18n.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def javascript_catalog(request, domain='djangojs', packages=None):
    """
    Returns the selected language catalog as a javascript library.

    Receives the list of packages to check for translations in the
    packages parameter either from an infodict or as a +-delimited
    string from the request. Default is 'django.conf'.

    Additionally you can override the gettext domain for this view,
    but usually you don't want to do that, as JavaScript messages
    go to the djangojs domain. But this might be needed if you
    deliver your JavaScript source from Django templates.
    """
    locale = to_locale(get_language())

    if request.GET and 'language' in request.GET:
        if check_for_language(request.GET['language']):
            locale = to_locale(request.GET['language'])

    if packages is None:
        packages = ['django.conf']
    if isinstance(packages, six.string_types):
        packages = packages.split('+')

    catalog, plural = get_javascript_catalog(locale, domain, packages)
    return render_javascript_catalog(catalog, plural) 
Example #29
Source File: encoding.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def force_bytes(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Similar to smart_bytes, except that lazy instances are resolved to
    strings, rather than kept as lazy objects.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    # Handle the common case first for performance reasons.
    if isinstance(s, bytes):
        if encoding == 'utf-8':
            return s
        else:
            return s.decode('utf-8', errors).encode(encoding, errors)
    if strings_only and is_protected_type(s):
        return s
    if isinstance(s, six.memoryview):
        return bytes(s)
    if isinstance(s, Promise):
        return six.text_type(s).encode(encoding, errors)
    if not isinstance(s, six.string_types):
        try:
            if six.PY3:
                return six.text_type(s).encode(encoding)
            else:
                return bytes(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                # An Exception subclass containing non-ASCII data that doesn't
                # know how to print itself properly. We shouldn't raise a
                # further exception.
                return b' '.join(force_bytes(arg, encoding, strings_only, errors)
                                 for arg in s)
            return six.text_type(s).encode(encoding, errors)
    else:
        return s.encode(encoding, errors) 
Example #30
Source File: engine.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def find_template_loader(self, loader):
        if isinstance(loader, (tuple, list)):
            args = list(loader[1:])
            loader = loader[0]
        else:
            args = []

        if isinstance(loader, six.string_types):
            loader_class = import_string(loader)

            if getattr(loader_class, '_accepts_engine_in_init', False):
                args.insert(0, self)
            else:
                warnings.warn(
                    "%s inherits from django.template.loader.BaseLoader "
                    "instead of django.template.loaders.base.Loader. " %
                    loader, RemovedInDjango110Warning, stacklevel=2)

            loader_instance = loader_class(*args)

            if not loader_instance.is_usable:
                warnings.warn(
                    "Your template loaders configuration includes %r, but "
                    "your Python installation doesn't support that type of "
                    "template loading. Consider removing that line from "
                    "your settings." % loader)
                return None
            else:
                return loader_instance

        else:
            raise ImproperlyConfigured(
                "Invalid value in template loaders configuration: %r" % loader)