A modified duplicate from Django's built in backend
    retriever.

        slugify = get_module('django.template.defaultfilters.slugify')
17887
def get_module(path):
    
    try:
        from importlib import import_module
    except ImportError as e:
        from django.utils.importlib import import_module

    try:
        mod_name, func_name = path.rsplit('.', 1)
        mod = import_module(mod_name)
    except ImportError as e:
        raise ImportError(
            'Error importing alert function {0}: "{1}"'.format(mod_name, e))

    try:
        func = getattr(mod, func_name)
    except AttributeError:
        raise ImportError(
            ('Module "{0}" does not define a "{1}" function'
                            ).format(mod_name, func_name))

    return func
982823
def unique_slug_required(form, slug):
    """"""

    if hasattr(form, 'instance') and form.instance.id:
        if Content.objects.exclude(page=form.instance).filter(
            body=slug, type="slug").count():
            raise forms.ValidationError(error_dict['another_page_error'])
    elif Content.objects.filter(body=slug, type="slug").count():
        raise forms.ValidationError(error_dict['another_page_error'])
    return slug
443388
def _check_backend():
    
    # Django 1.10 does not allow
    # both settings to be set
    middleware = set(
        getattr(settings, 'MIDDLEWARE', None) or
        getattr(settings, 'MIDDLEWARE_CLASSES', None) or
        [])

    # Deprecated alias
    if "djconfig.middleware.DjConfigLocMemMiddleware" in middleware:
        return

    if "djconfig.middleware.DjConfigMiddleware" in middleware:
        return

    raise ValueError(
        "djconfig.middleware.DjConfigMiddleware "
        "is required but it was not found in "
        "MIDDLEWARE_CLASSES nor in MIDDLEWARE")
909298
def save(self, *args, **kwargs):
        
        self.slug = slugify(self.name)[:50]
        return super(Tag, self).save(*args, **kwargs)
1018577
def clean_slug(self):
        
        slug = self.cleaned_data.get('slug', None)
        if slug is None or len(slug) == 0 and 'title' in self.cleaned_data:
            slug = slugify(self.cleaned_data['title'])
        return slug
750395
def copy(self):
        '''
            
        '''
        ret = QueryBuilder()
        ret.filters = copy.copy(self.filters)
        return ret
1261047
def clean_slug(self):
        
        self.instance._old_slug = self.instance.slug
        new_slug = self.cleaned_data['slug']
        if not isinstance(self.instance, Link) and new_slug != "/":
            new_slug = clean_slashes(self.cleaned_data['slug'])
        return new_slug
402236
def slug_from_dict(d, max_len=128, delim='-'):
    
    return slug_from_iter(list(d.values()), max_len=max_len, delim=delim)
1294359
def filter(self, **kwargs):
        
        readFilter = ReadFilter(**kwargs)
        self._filters.append(readFilter.filter)
        return self
512969
def filtered_dir(module_name, *, additions={}, **kwargs):
    
    module = importlib.import_module(module_name)

    def __dir__():
        attr_names = set(filtered_attrs(module, **kwargs))
        attr_names.update(additions)
        return sorted(attr_names)

    return __dir__
1092434
def slugify_filename(filename):
    
    name, ext = os.path.splitext(filename)
    slugified = get_slugified_name(name)
    return slugified + ext
1062684
def slug(cls):
        
        slug = cls.__name__.lower()
        if slug.endswith('view'):
            slug = slug[:-4]
        return slug
994196
def get_object(self):
        

        if not self.force_add and self.kwargs.get(self.slug_url_kwarg, None):
            return super(FormView, self).get_object()
        else:
            self.queryset = self.get_queryset()

        return None
109835
def similar_objects(self, num=None, **filters):
        
        tags = self.tags
        if not tags:
            return []

        content_type = ContentType.objects.get_for_model(self.__class__)
        filters['content_type'] = content_type

        # can't filter, see
        # - https://github.com/alex/django-taggit/issues/32
        # - https://django-taggit.readthedocs.io/en/latest/api.html#TaggableManager.similar_objects
        #
        # Otherwise this would be possible:
        # return tags.similar_objects(**filters)

        lookup_kwargs = tags._lookup_kwargs()
        lookup_keys = sorted(lookup_kwargs)
        subq = tags.all()
        qs = (tags.through.objects
              .values(*lookup_kwargs.keys())
              .annotate(n=models.Count('pk'))
              .exclude(**lookup_kwargs)
              .filter(tag__in=list(subq))
              .order_by('-n'))

        # from https://github.com/alex/django-taggit/issues/32#issuecomment-1002491
        if filters is not None:
            qs = qs.filter(**filters)

        if num is not None:
            qs = qs[:num]

        # Normal taggit code continues

        # TODO: This all feels like a bit of a hack.
        items = {}
        if len(lookup_keys) == 1:
            # Can we do this without a second query by using a select_related()
            # somehow?
            f = tags.through._meta.get_field_by_name(lookup_keys[0])[0]
            objs = f.rel.to._default_manager.filter(**{
                "%s__in" % f.rel.field_name: [r["content_object"] for r in qs]
            })
            for obj in objs:
                items[(getattr(obj, f.rel.field_name),)] = obj
        else:
            preload = {}
            for result in qs:
                preload.setdefault(result['content_type'], set())
                preload[result["content_type"]].add(result["object_id"])

            for ct, obj_ids in preload.items():
                ct = ContentType.objects.get_for_id(ct)
                for obj in ct.model_class()._default_manager.filter(pk__in=obj_ids):
                    items[(ct.pk, obj.pk)] = obj

        results = []
        for result in qs:
            obj = items[
                tuple(result[k] for k in lookup_keys)
            ]
            obj.similar_tags = result["n"]
            results.append(obj)
        return results
332515
def get_object(self, name, *argv, **kwargs):
        
        regexp = name
        options = self.opts(regexp)
        options.update(kwargs)
        args = options.pop('view_args', argv)
        csrf_enable = self.get_backend_data(regexp).get('CSRF_ENABLE', True)
        if regexp in self.settings_urls:
            regexp = r'^{}'.format(self.get_django_settings(regexp)[1:])
        view = self[name].as_view()
        if not csrf_enable:
            view = csrf_exempt(view)
        return url(regexp, view, *args, **options)
85171
def get_object(self, **kwargs) ->Model:
        
        queryset = self.filter_queryset(
            queryset=self.get_queryset(**kwargs),
            **kwargs
        )

        # Perform the lookup filtering.
        lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

        assert lookup_url_kwarg in kwargs, (
                'Expected view %s to be called with a URL keyword argument '
                'named "%s". Fix your URL conf, or set the `.lookup_field` '
                'attribute on the view correctly.' %
                (self.__class__.__name__, lookup_url_kwarg)
        )

        filter_kwargs = {self.lookup_field: kwargs[lookup_url_kwarg]}

        obj = get_object_or_404(queryset, **filter_kwargs)
        # TODO check_object_permissions

        return obj
436735
def slugify(value):
    
    if six.PY3:
        value = str(value)
    else:
        value = unicode(value)

    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
    value = to_remove.sub('', value).strip().lower()
    return remove_dup.sub('-', value)