def ready(self):
        import autocomplete_light.shortcuts as autocomplete_light

        class AppConfigWithoutRegistryAutocomplete(autocomplete_light.AutocompleteListBase):

            choices = ["a", "b"]

        autocomplete_light.register(AppConfigWithoutRegistryAutocomplete)
Example #2
0
    def ready(self):
        import autocomplete_light.shortcuts as autocomplete_light

        class AppConfigWithoutRegistryAutocomplete(
                autocomplete_light.AutocompleteListBase):

            choices = ['a', 'b']

        autocomplete_light.register(AppConfigWithoutRegistryAutocomplete)
Example #3
0
    def ready(self):
        import autocomplete_light.shortcuts as al
        from powerdns.models.powerdns import Domain, Record
        from django.contrib.auth.models import User

        class AutocompleteAuthItems(al.AutocompleteGenericBase):
            choices = (
                Domain.objects.all(),
                Record.objects.all(),
            )
            search_fields = (('name', ), ('name', ))

        al.register(AutocompleteAuthItems)
        # We register the default django User class. If someone wants to use
        # an alternative user model, she needs to register it herself. We can't
        # do it, as we don't know what fields are used there.
        al.register(User,
                    search_fields=['username', 'first_name', 'last_name'])
    def test_meta_autocomplete_names(self):
        SpecialAutocomplete = self.get_new_autocomplete_class()
        autocomplete_light.register(SpecialAutocomplete)

        class ModelForm(autocomplete_light.ModelForm):
            class Meta(DjangoCompatMeta):
                model = self.model_class
                autocomplete_names = {'relation': 'SpecialAutocomplete'}

        self.form = ModelForm()

        self.assertInForm('name')
        self.assertIsAutocomplete('relation')
        self.assertIsAutocomplete('noise')

        self.assertTrue(
            issubclass(self.form.fields['relation'].autocomplete,
                       SpecialAutocomplete))
        autocomplete_light.registry.unregister('SpecialAutocomplete')
    def test_meta_autocomplete_names(self):
        SpecialAutocomplete = self.get_new_autocomplete_class()
        autocomplete_light.register(SpecialAutocomplete)

        class ModelForm(autocomplete_light.ModelForm):
            class Meta(DjangoCompatMeta):
                model = self.model_class
                autocomplete_names = {
                    'relation': 'SpecialAutocomplete'
                }

        self.form = ModelForm()

        self.assertInForm('name')
        self.assertIsAutocomplete('relation')
        self.assertIsAutocomplete('noise')

        self.assertTrue(issubclass(self.form.fields['relation'].autocomplete,
                                   SpecialAutocomplete))
        autocomplete_light.registry.unregister('SpecialAutocomplete')
Example #6
0
    def ready(self):
        import autocomplete_light.shortcuts as al
        from powerdns.models.powerdns import Domain, Record
        from django.contrib.auth.models import User

        class AutocompleteAuthItems(al.AutocompleteGenericBase):
            choices = (
                Domain.objects.all(),
                Record.objects.all(),
            )
            search_fields = (
                ('name',),
                ('name',)
            )

        al.register(AutocompleteAuthItems)
        # We register the default django User class. If someone wants to use
        # an alternative user model, she needs to register it herself. We can't
        # do it, as we don't know what fields are used there.
        al.register(
            User,
            search_fields=['username', 'first_name', 'last_name']
        )
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Cyphon Engine. If not, see <http://www.gnu.org/licenses/>.
"""
Defines Autocomplete models for use in admin pages for the MailCondensers app.
"""

# third party
import autocomplete_light.shortcuts as autocomplete_light

# local
from sifter.condensers.autocomplete import (
    FilterTargetFieldsByBottle,
    FilterTargetFieldsByCondenser,
)
from .models import MailCondenser


class FilterTargetFieldsByMailCondenser(FilterTargetFieldsByCondenser):
    """
    Defines autocomplete rules for target_field on the MailFitting admin page.
    """
    model = MailCondenser


autocomplete_light.register(FilterTargetFieldsByBottle)
autocomplete_light.register(FilterTargetFieldsByMailCondenser)

from autocomplete_light import shortcuts as autocomplete_light
from .models import Contact

# This will generate a ContactAutocomplete class
autocomplete_light.register(Contact,
    search_fields=['name'],
)
from __future__ import absolute_import, unicode_literals

import autocomplete_light.shortcuts as autocomplete_light

from .models import Client, Budget

# This will generate a ShowAutocomplete class
autocomplete_light.register(
    Client,
    # Just like in ModelAdmin.search_fields
    search_fields=['name'],
    # This will actually html attribute data-placeholder which will set
    # javascript attribute widget.autocomplete.placeholder.
    attrs={
        'data-autocomplete-minimum-characters': 0,
        'placeholder': 'Client search',
    },
)

# This will generate a ShowAutocomplete class
autocomplete_light.register(
    Budget,
    # Just like in ModelAdmin.search_fields
    search_fields=['name', 'client__name'],
    # This will actually html attribute data-placeholder which will set
    # javascript attribute widget.autocomplete.placeholder.
    attrs={
        'data-autocomplete-minimum-characters': 0,
        'placeholder': 'Budget search',
    },
    add_another_url_name='clients:budget_create'
Example #10
0
class OrganizationAutocomplete(UserAutocomplete):
    """Adds organization-specific filtering for users"""
    def choices_for_request(self):
        # get filters
        query = self.request.GET.get('q', '')
        exclude = self.request.GET.getlist('exclude', '')
        org_id = self.request.GET.get('orgId', '')
        # get all choices
        choices = self.choices.all()
        # exclude choices based on filters
        if query:
            choices = choices.filter(username__icontains=query)
        for user_id in exclude:
            choices = choices.exclude(pk=int(user_id))
        if org_id:  # exclude owner and members from choices
            organization = get_object_or_404(Organization, pk=org_id)
            owner = organization.owner
            profiles = organization.members.all()
            exclude_pks = [owner.pk
                           ] + [profile.user.pk for profile in profiles]
            choices = choices.exclude(pk__in=exclude_pks)
        # return final list of choices
        return self.order_choices(choices)[0:self.limit_choices]


autocomplete_light.register(User, UserAutocomplete)
autocomplete_light.register(User, OrganizationAutocomplete)
autocomplete_light.register(User, RequestSharingAutocomplete)
autocomplete_light.register(User, AuthorAutocomplete)
autocomplete_light.register(User, UserTaskAutocomplete)
    """
    Defines autocomplete rules for CharFields/TextFields for an inline
    Taste on the Container admin page.
    """
    field_types = TEXT_FIELDS


class FilterDateTimeFieldsByBottleAndLabel(FilterFieldsByBottleAndLabel):
    """
    Defines autocomplete rules for DataTimeFields for an inline
    Taste on the Container admin page.
    """
    field_types = DATE_FIELDS


class FilterLocationFieldsByBottleAndLabel(FilterFieldsByBottleAndLabel):
    """
    Defines autocomplete rules for LocationFields for an inline
    Taste on the Container admin page.
    """
    field_types = LOCATION_FIELDS


autocomplete_light.register(FilterCharFieldsByContainer)
autocomplete_light.register(FilterDateTimeFieldsByContainer)
autocomplete_light.register(FilterLocationFieldsByContainer)
autocomplete_light.register(FilterCharFieldsByBottleAndLabel)
autocomplete_light.register(FilterDateTimeFieldsByBottleAndLabel)
autocomplete_light.register(FilterLocationFieldsByBottleAndLabel)

Example #12
0
import autocomplete_light.shortcuts as autocomplete_light
from django import http

from .models import OnTheFly


class OnTheFlyAutocomplete(autocomplete_light.AutocompleteModelBase):
    choices = OnTheFly.objects.all()

    def autocomplete_html(self):
        html = super(OnTheFlyAutocomplete, self).autocomplete_html()

        q = self.request.REQUEST.get('q')
        if q and not self.choices.filter(name=q).exists():
            html += '<span data-value="create">Create "{}"</span>'.format(q)
        return html

    def post(self, request, *args, **kwargs):
        return http.HttpResponse(
            OnTheFly.objects.create(name=request.POST['name']).pk
        )
autocomplete_light.register(OnTheFly, OnTheFlyAutocomplete)
Example #13
0
            x for x in self.values
            if not isinstance(x, basestring) or re.match(r'[0-9]+', x)
        ])


class AgencyAdminAutocomplete(AgencyAutocomplete):
    """Autocomplete for Agencies for FOIA admin page"""
    attrs = {'placeholder': 'Agency?'}


class AgencyAppealAdminAutocomplete(AgencyAdminAutocomplete):
    """Autocomplete for Appeal Agencies - allows local agencies to pick
    state agencies as their appeal agency"""
    def _filter_by_jurisdiction(self, choices, jurisdiction_id):
        """Filter the agency choices given a jurisdiction"""
        jurisdiction = Jurisdiction.objects.get(pk=jurisdiction_id)
        if jurisdiction.level == 'l':
            # For local jurisdictions, appeal agencies may come from the
            # parent level
            return choices.filter(jurisdiction__in=(jurisdiction,
                                                    jurisdiction.parent))
        else:
            return choices.filter(jurisdiction=jurisdiction)


autocomplete_light.register(Agency, AgencyAutocomplete)
autocomplete_light.register(Agency, AgencyEasySearchAutocomplete)
autocomplete_light.register(Agency, AgencyComposerAutocomplete)
autocomplete_light.register(Agency, AgencyAdminAutocomplete)
autocomplete_light.register(Agency, AgencyAppealAdminAutocomplete)
from autocomplete_light import shortcuts as autocomplete_light

from curriculum.models import Titolo


class TitoloAutocompletamento(autocomplete_light.AutocompleteModelBase):
    search_fields = ['nome',]
    model = Titolo

    def choices_for_request(self):
        try:
            if 'titoli_tipo' in self.request.session and 'curriculum' in self.request.META.get('HTTP_REFERER', ''):
                self.choices = self.choices.filter(inseribile_in_autonomia=True, tipo=self.request.session['titoli_tipo'])
        except:
            pass
        self.choices = self.choices.filter(inseribile_in_autonomia=True)
        return super(TitoloAutocompletamento, self).choices_for_request()

autocomplete_light.register(TitoloAutocompletamento)
Example #15
0
"""
Autocomplete registry for Portal
"""

# Third Party
from autocomplete_light import shortcuts as autocomplete_light

# MuckRock
from muckrock.portal.models import Portal

autocomplete_light.register(Portal,
                            name='PortalAutocomplete',
                            choices=Portal.objects.all(),
                            search_fields=('name', 'url'),
                            attrs={
                                'placeholder': 'Search for a portal',
                                'data-autocomplete-minimum-characters': 1,
                            })
Example #16
0
Autocomplete registry for crowdsources
"""

# Third Party
from autocomplete_light import shortcuts as autocomplete_light

# MuckRock
from muckrock.crowdsource.models import Crowdsource


class CrowdsourceDraftAutocomplete(autocomplete_light.AutocompleteModelBase):
    """Creates an autocomplete for picking crowdsources"""
    search_fields = ['title', 'description']
    attrs = {
        'placeholder': 'Choose an unstarted crowdsource',
        'data-autocomplete-minimum-characters': 1
    }

    def choices_for_request(self):
        """
        Only show crowdsources owned by the user
        """
        self.choices = Crowdsource.objects.filter(
            status='draft',
            user=self.request.user,
        )
        return super(CrowdsourceDraftAutocomplete, self).choices_for_request()


autocomplete_light.register(Crowdsource, CrowdsourceDraftAutocomplete)
Example #17
0
    attrs = {'placeholder':' Search for phenotype by name ...',
             'data-autocomplete-minimum-characters':1}

    widget_attrs={'data-widget-maximum-values':10,
                  'data-widget-minimum-values':2,
                  'class':'','style':'width:100%;'}

    #Individual Choice Render Format
    choice_html_format = u"<span class='block' data-value='%s'>%s</span>"

    #Render Choide
    def choice_html(self,choice):
        #return self.choice_html_format % (self.choice_value(choice),self.choice_label(choice))
        return self.choice_html_format % (self.choice_value(choice),choice.name + " (Study: " + choice.study.name + ")")

autocomplete_light.register(PhenotypeCorrelationAutocomplete)

class PhenotypeTransformationAutocomplete(autocomplete_light.AutocompleteModelBase):
    model = Phenotype
    search_fields = ['name']

    attrs = {'placeholder':' Search for phenotype by name ...',
             'data-autocomplete-minimum-characters':1}

    widget_attrs={'data-widget-maximum-values':1,
                  'data-widget-minimum-values':1,
                  'class':'','style':'width:100%;'}

    #Individual Choice Render Format
    choice_html_format = u"<span class='block' data-value='%s'>%s</span>"
        )
        return super(ComitatoAutocompletamento, self).choices_for_request()


class SedeTrasferimentoAutocompletamento(AutocompletamentoBase):
    search_fields = ['nome', 'genitore__nome', ]
    model = Sede

    def choices_for_request(self):
        self.choices = self.choices.filter(
            tipo=Sede.COMITATO,
            estensione__in=[PROVINCIALE, LOCALE, TERRITORIALE],
        )
        return super(SedeTrasferimentoAutocompletamento, self).choices_for_request()


class SedeNuovoCorsoAutocompletamento(SedeAutocompletamento):
    def choices_for_request(self):
        return self.persona.oggetti_permesso(GESTIONE_CORSI_SEDE)


autocomplete_light.register(PersonaAutocompletamento)
autocomplete_light.register(PresidenteAutocompletamento)
autocomplete_light.register(SostenitoreAutocompletamento)
autocomplete_light.register(VolontarioSedeAutocompletamento)
autocomplete_light.register(IscrivibiliCorsiAutocompletamento)
autocomplete_light.register(SedeAutocompletamento)
autocomplete_light.register(ComitatoAutocompletamento)
autocomplete_light.register(SedeTrasferimentoAutocompletamento)
autocomplete_light.register(SedeNuovoCorsoAutocompletamento)
import autocomplete_light.shortcuts as al
from geodata.models import Country, Region

al.register(
    Country,
    search_fields=['code', 'name'],
    attrs={
        'placeholder': 'Search country',
        'class': 'narrative_activity_field',
        'data-autocomplete-minimum-characters': 1
    },
    widget_attrs={
        'data-widget-maximum-values': 4,
        'class': 'modern-style narrative_activity_field'
    },
)

al.register(
    Region,
    search_fields=['code', 'name'],
    attrs={
        'placeholder': 'Search region',
        'class': 'narrative_activity_field',
        'data-autocomplete-minimum-characters': 1
    },
    widget_attrs={
        'data-widget-maximum-values': 4,
        'class': 'modern-style narrative_activity_field'
    },
)
import autocomplete_light.shortcuts as al
from diets.models import Meal

al.register(
    Meal,
    search_fields=["food_group", "food"],
    attrs={"placeholder": "Food group or food", "data-autocomplete-minimum-characters": 1},
    widget_attrs={"data-widget-maximum-values": 4, "class": "modern-style"},
)
    def choices_for_request(self):
        self.choices = self.choices.filter(
            attiva=True
        )
        return super(SedeAutocompletamento, self).choices_for_request()


class ComitatoAutocompletamento(AutocompletamentoBase):
    search_fields = ['nome', 'genitore__nome', ]
    model = Sede

    def choices_for_request(self):
        self.choices = self.choices.filter(
            tipo=Sede.COMITATO,
            estensione__in=[NAZIONALE, REGIONALE, PROVINCIALE, LOCALE],
        )
        return super(ComitatoAutocompletamento, self).choices_for_request()


class SedeNuovoCorsoAutocompletamento(SedeAutocompletamento):
    def choices_for_request(self):
        return self.persona.oggetti_permesso(GESTIONE_CORSI_SEDE)


autocomplete_light.register(PersonaAutocompletamento)
autocomplete_light.register(PresidenteAutocompletamento)
autocomplete_light.register(SostenitoreAutocompletamento)
autocomplete_light.register(SedeAutocompletamento)
autocomplete_light.register(ComitatoAutocompletamento)
autocomplete_light.register(SedeNuovoCorsoAutocompletamento)
import autocomplete_light.shortcuts as autocomplete_light

from .models import Category, Tag

autocomplete_light.register(Category, search_fields=['name'] )
autocomplete_light.register(Tag,      search_fields=['name'] )
Example #23
0
from autocomplete_light import shortcuts as al
from vocabularies.models import ProfessionType, Title

from entities.models import Person, Place, Institution, Event, Work

class TitleAutocomplete(al.AutocompleteModelBase):
	search_fields=['name', 'abbreviation']
	model = Title
	attrs = {
        'data-autocomplete-minimum-characters': 2,
        'placeholder': 'Start typing to get suggestions',
    }

al.register(Title, TitleAutocomplete)


class ProfessionTypeAutocomplete(al.AutocompleteModelBase):
	search_fields=['name']
	model = ProfessionType
	attrs = {
        'data-autocomplete-minimum-characters': 2,
        'placeholder': 'Start typing to get suggestions',
    }

al.register(ProfessionType, ProfessionTypeAutocomplete)


class DB_PersonAutocomplete(al.AutocompleteModelBase):
    search_fields = ['name', 'first_name']
    model = Person
    attrs = {
import autocomplete_light.shortcuts as al
from models import AAAData

# # This will generate a PersonAutocomplete class
# ----------------------- Working Autocomplete -------------------------------
al.register(AAAData,
            search_fields=['location'],
            name='AAADataAutocomplete',
            choices=AAAData.objects.all(),
            attrs={
                    'placeholder': 'Type to search location`',
                    'data-autocomplete-minimum-characters': 1,
                    }
            )
# ----------------------------------------------------------------------------


# ------------------------------------------------------
# al.register(AAAData,
#     # Just like in ModelAdmin.search_fields
#     search_fields=['location'],
#     attrs={
#         # This will set the input placeholder attribute:
#         # 'placeholder': 'Other model name ?',
#         # This will set the yourlabs.Autocomplete.minimumCharacters
#         # options, the naming conversion is handled by jQuery
#         'data-autocomplete-minimum-characters': 3,
#     },
#     # This will set the data-widget-maximum-values attribute on the
#     # widget container element, and will be set to
#     # yourlabs.Widget.maximumValues (jQuery handles the naming
from wfppresencedjango.models import WFPRegionalBureau, WFPCountry

class WFPRegionalBureauAutocomplete(autocomplete_light.AutocompleteGenericBase):
    search_fields=['^name']
    model=WFPRegionalBureau
    attrs={
        'placeholder': 'Other model name ?',
        'data-autocomplete-minimum-characters': 1
    }
    widget_attrs={
        'data-widget-maximum-values': 4,
        'class': 'modern-style'
    }


class WFPCountryAutocomplete(autocomplete_light.AutocompleteGenericBase):
    search_fields=['^name']
    model=WFPCountry
    attrs={
        'placeholder': 'Other model name ?',
        'data-autocomplete-minimum-characters': 1
    }
    widget_attrs={
        'data-widget-maximum-values': 4,
        'class': 'modern-style'
    }


autocomplete_light.register(WFPRegionalBureauAutocomplete)
autocomplete_light.register(WFPCountryAutocomplete)
        """
        self.choices = Project.objects.get_visible(self.request.user)
        return super(ProjectAutocomplete, self).choices_for_request()


class ProjectManagerAutocomplete(autocomplete_light.AutocompleteModelBase):
    """Creates an autocomplete registry for project manager components"""
    choice_template = 'autocomplete/project.html'
    search_fields = ['title', 'summary']
    attrs = {
        'data-autocomplete-minimum-characters': 0,
        'placeholder': 'Search your projects'
    }

    def choices_for_request(self):
        """
        When showing possible requests to add, only show projects the user is a contributor to.
        If the user is unauthenticated, only return public choices.
        However, if the user is staff, then show them all the available projects.
        """
        user = self.request.user
        if not user.is_authenticated():
            self.choices = self.choices.get_public()
        elif not user.is_staff:
            self.choices = self.choices.filter(contributors=user)
        return super(ProjectManagerAutocomplete, self).choices_for_request()


autocomplete_light.register(Project, ProjectAutocomplete)
autocomplete_light.register(Project, ProjectManagerAutocomplete)
Example #27
0
logger = logging.getLogger(__name__)


# Sets up Autocomplete functionality for Institution Field on Participant
# Account Profile
class InstitutionAutocomplete(autocomplete_light.AutocompleteModelBase):
    search_fields = ['name', 'acronym']
    autocomplete_js_attributes = {
        # This will data-autocomplete-minimum-characters which
        # will set widget.autocomplete.minimumCharacters.
        'minimum_characters': 1,
        'placeholder': 'Institution Name',
    }


autocomplete_light.register(Institution, InstitutionAutocomplete)


# Sets up autocomplete functionality for institution field on participant
# account profile
class ParticipantMajorAutocomplete(autocomplete_light.AutocompleteListBase):
    participants = Participant.objects.order_by('major').distinct(
        'major').values('major')
    choices = participants.values_list('major', flat=True)
    search_fields = []
    autocomplete_js_attributes = {
        # This will data-autocomplete-minimum-characters which
        # will set widget.autocomplete.minimumCharacters.
        'minimum_characters': 1,
        'placeholder': ' ',
    }
Example #28
0
import autocomplete_light.shortcuts as autocomplete_light
from .models import Story
from django.utils.translation import ugettext_lazy as _

autocomplete_light.register(
    Story,
    search_fields=['title', 'lede', ],
    order_by=['-publication_date'],
    attrs={
        # This will set the input placeholder attribute:
        'placeholder': _('Story headline or lede.'),
        # This will set the yourlabs.Autocomplete.minimumCharacters
        # options, the naming conversion is handled by jQuery
        'data-autocomplete-minimum-characters': 2,
    },
    # This will set the data-widget-maximum-values attribute on the
    # widget container element, and will be set to
    # yourlabs.Widget.maximumValues (jQuery handles the naming
    # conversion).
    widget_attrs={
        'data-widget-maximum-values': 10,
        # Enable modern-style widget !
        'class': 'modern-style',
    },
)
Example #29
0
import autocomplete_light.shortcuts as autocomplete_light

from .models import *

models = [OtoModel, FkModel, MtmModel, GfkModel]

try:
    import genericm2m
except ImportError:
    pass
else:
    models.append(GmtmModel)

for model in models:
    autocomplete_light.register(model)


class A(autocomplete_light.AutocompleteGenericBase):
    choices=[m.objects.all() for m in models]
    search_fields=[['name']] * len(models)


autocomplete_light.register(A)


# The autocomplete for class B is used to set up the test case for
# autocomplete_light.tests.widgets.TextWidgetTestCase.test_widget_attrs_copy.
# This bug is triggered only when the autocomplete is registered with a
# widget_attrs dictionary.
class B(autocomplete_light.AutocompleteGenericBase):
    choices=[m.objects.all() for m in models]
__author__ = 'jcranwellward'

from autocomplete_light import shortcuts as autocomplete_light

from .models import (Grant)

autocomplete_light.register(
    Grant,
    # Just like in ModelAdmin.search_fields
    search_fields=['^name', '^donor__name'],
    # This will actually html attribute data-placeholder which will set
    # javascript attribute widget.autocomplete.placeholder.
    autocomplete_js_attributes={
        'placeholder': 'Type donor name or grant',
    },
)
    autocomplete_js_attributes = {
        'minimum_characters': 2,
    }

    widget_js_attributes = {
        'max_values': 1,
        'choice_selector': '[data-url]?pos=noun'

    }

    def choices_for_request(self):
        """
        Return choices for a particular request.
        """
        assert self.choices is not None, 'choices should be a queryset'
        assert self.search_fields, 'autocomplete.search_fields must be set'
        q = self.request.GET.get('q', '')
        exclude = self.request.GET.getlist('exclude')

        conditions = self._choices_for_request_conditions(q, self.search_fields)

        pos = self.request.GET.get('pos', None)
        queryset = self.choices.filter(conditions).exclude(pk__in=exclude)
        if pos:
            print pos
            queryset = queryset.filter(pos=pos)

        return self.order_choices(queryset)[0:self.limit_choices]

al.register(Concept, ConceptAutocomplete)
import autocomplete_light.shortcuts as autocomplete_light

from poradnia.users.utils import AutocompletePermissionMixin

from .models import Case


class CaseAutocomplete(AutocompletePermissionMixin, autocomplete_light.AutocompleteModelBase):
    search_fields = ['name']
    model = Case

autocomplete_light.register(Case, CaseAutocomplete)
from __future__ import unicode_literals

import autocomplete_light.shortcuts as autocomplete_light

from poradnia.users.utils import AutocompletePermissionMixin

from .models import User


class UserAutocomplete(AutocompletePermissionMixin, autocomplete_light.AutocompleteModelBase):
    search_fields = ['first_name', 'last_name', 'username']
    model = User

    def choice_label(self, choice):
        return "{name} ({email})".format(name=choice.get_nicename(), email=choice.email)
autocomplete_light.register(User, UserAutocomplete)
import autocomplete_light.shortcuts as al
from reference.models import GlossaryTerm


al.register(
    GlossaryTerm,
    search_fields=['word_lower', ]
)
from django.db.models import Count

from autocomplete_light import shortcuts as autocomplete_light

from muckrock.tags.models import Tag


class TagAutocomplete(autocomplete_light.AutocompleteModelBase):
    """Creates an autocomplete field for picking tags"""
    choices = (Tag.objects
            .annotate(num=Count('tags_taggeditembase_items'))
            .exclude(num=0))
    search_fields = ['name']
    attrs = {
        'data-autocomplete-minimum-characters': 1,
        'placeholder': 'Search tags',
    }


class TagSlugAutocomplete(TagAutocomplete):
    """Tag autocomplete that uses the slug as the value"""

    def choice_value(self, choice):
        """Return the slug as the value"""
        return choice.slug


autocomplete_light.register(Tag, TagAutocomplete)
autocomplete_light.register(Tag, TagSlugAutocomplete)
__author__ = 'heddevanderheide'

import autocomplete_light.shortcuts as autocomplete_light

from .models import XModel


class XModelAutocomplete(autocomplete_light.AutocompleteModelBase):
    search_fields = ['x']

autocomplete_light.register(XModel, XModelAutocomplete, attrs={
    'placeholder': "Enter xmodel",
    'data-autocomplete-minimum-characters': 1
})
import autocomplete_light.shortcuts as al
from .models import Project

# This will generate a PersonAutocomplete class
al.register(
    Project,
    # Just like in ModelAdmin.search_fields
    search_fields=['^name', ],
    attrs={
        # This will set the input placeholder attribute:
        'placeholder': 'Project',
        # This will set the yourlabs.Autocomplete.minimumCharacters
        # options, the naming conversion is handled by jQuery
        'data-autocomplete-minimum-characters': 2,
    },
    # This will set the data-widget-maximum-values attribute on the
    # widget container element, and will be set to
    # yourlabs.Widget.maximumValues (jQuery handles the naming
    # conversion).
    widget_attrs={
        'data-widget-maximum-values': 1,
        # Enable modern-style widget !
        'class': 'modern-style',
    },
)
__author__ = 'jcranwellward'

from autocomplete_light import shortcuts as autocomplete_light

from .models import Location


class AutocompleteLocation(autocomplete_light.AutocompleteModelBase):
    search_fields = ['^name', 'gateway__name']
    placeholder = 'Enter location name or type'
    model = Location

autocomplete_light.register(Location, AutocompleteLocation)
import autocomplete_light.shortcuts as autocomplete_light

from lsibdjango.models import GeographicThesaurusEntry


class GeographicThesaurusAutocomplete(
        autocomplete_light.AutocompleteGenericBase):
    search_fields = ['^dos_short']
    model = GeographicThesaurusEntry
    attrs = {
        'placeholder': 'Other model name ?',
        'data-autocomplete-minimum-characters': 1
    }
    widget_attrs = {'data-widget-maximum-values': 4, 'class': 'modern-style'}


autocomplete_light.register(GeographicThesaurusAutocomplete)
Example #40
0
"""
Autocomplete registry for news articles
"""

from muckrock.news.models import Article

from autocomplete_light import shortcuts as autocomplete_light


class ArticleAutocomplete(autocomplete_light.AutocompleteModelTemplate):
    """Creates an autocomplete for picking articles"""
    choices = Article.objects.get_published()
    choice_template = 'autocomplete/article.html'
    search_fields = ['title']
    attrs = {
        'placeholder': 'Search for articles',
        'data-autocomplete-minimum-characters': 1
    }


autocomplete_light.register(Article, ArticleAutocomplete)
import autocomplete_light.shortcuts as al

from reviews.models import OnMapReview

# This will generate a OnMapReviewAutocomplete class
al.register(OnMapReview,
            search_fields=['^id', 'name'],
            attrs={'placeholder': 'Name or ID',
                   'data-autocomplete-minimum-characters': 1, },
            widget_attrs={'data-widget-maximum-values': 16, },
            )
import autocomplete_light.shortcuts as al
from autocomplete_light import AutocompleteModelBase
from django.contrib.auth.models import User

from project.ajapaik.models import Profile, Photo, Tour, Points, GeoTag, Album, Dating, DatingConfirmation, AlbumPhoto, \
    Video, PhotoComment, Source, Skip, Area, Licence, Device, Newsletter, TourGroup, TourRephoto

al.register(Profile,
            search_fields=['user__pk', 'first_name', 'last_name', 'user__email', 'fb_name', 'google_plus_name'],
            attrs={
                'data-autocomplete-minimum-characters': 2,
            },
            widget_attrs={
                'data-widget-maximum-values': 4,
                'class': 'modern-style',
            },
            )

al.register(User,
            search_fields=['pk', 'first_name', 'last_name', 'email'],
            attrs={
                'data-autocomplete-minimum-characters': 2,
            },
            widget_attrs={
                'data-widget-maximum-values': 4,
                'class': 'modern-style',
            },
            )

al.register(Photo,
            search_fields=['pk', 'description'],
from books.models import Binding, Publisher, Series

from autocomplete_light import shortcuts as autocomplete_light

autocomplete_light.register(Series,
	search_fields=['name'],
	attrs={
		'placeholder': 'Filter',
		'data-autocomplete-minimum-characters': 1,
	},
	widget_attrs={
		'data-widget-maximum-values': 6,
	},
)

autocomplete_light.register(Publisher,
	search_fields=['name'],
	attrs={
		'placeholder': 'Filter',
		'data-autocomplete-minimum-characters': 1,
	},
	widget_attrs={
		'data-widget-maximum-values': 6,
	},
)

autocomplete_light.register(Binding,
	search_fields=['name'],
	attrs={
		'placeholder': 'Filter',
		'data-autocomplete-minimum-characters': 1,
import autocomplete_light.shortcuts as autocomplete_light
from .models import ImageFile, ProfileImage
from django.utils.translation import ugettext_lazy as _

# This will generate a PersonAutocomplete class
kwargs = dict(
    search_fields=[
        'source_file',
    ],
    order_by='-modified',
    attrs={
        # This will set the input placeholder attribute:
        'placeholder': _('Filename'),
        # This will set the yourlabs.Autocomplete.minimumCharacters
        # options, the naming conversion is handled by jQuery
        'data-autocomplete-minimum-characters': 2,
    },
    # This will set the data-widget-maximum-values attribute on the
    # widget container element, and will be set to
    # yourlabs.Widget.maximumValues (jQuery handles the naming
    # conversion).
    widget_attrs={
        'data-widget-maximum-values': 10,
        # Enable modern-style widget !
        'class': 'modern-style',
    },
)

autocomplete_light.register(ImageFile, **kwargs)
autocomplete_light.register(ProfileImage, **kwargs)
from autocomplete_light import shortcuts as autocomplete_light
from .models import *


# Register autocomplete for 'autocomplete as you type'

autocomplete_light.register(
    VoyageGroupings, search_fields=("value",), autocomplete_js_attributes={"placeholder": "Grouping name..."}
)

autocomplete_light.register(
    VoyageCaptain, search_fields=("name",), autocomplete_js_attributes={"placeholder": "Captain name..."}
)

autocomplete_light.register(
    Nationality, search_fields=("label",), autocomplete_js_attributes={"placeholder": "Nationality of ship..."}
)

autocomplete_light.register(
    TonType, search_fields=("label",), autocomplete_js_attributes={"placeholder": "Ton type..."}
)

autocomplete_light.register(
    RigOfVessel, search_fields=("label",), autocomplete_js_attributes={"placeholder": "Rig of vessel..."}
)

autocomplete_light.register(Place, search_fields=("place",), autocomplete_js_attributes={"placeholder": "Place..."})

autocomplete_light.register(Region, search_fields=("region",), autocomplete_js_attributes={"placeholder": "Region..."})

autocomplete_light.register(
Example #46
0
        if choice.last_name:
            if choice.first_name:
                label += " "
            label += choice.last_name

        if choice.userprofile.organization:
            if choice.first_name or choice.last_name:
                label += ", "
            label += choice.userprofile.organization

        if choice.username:
            label += "".join([" (", choice.username, ")"])

        return label


autocomplete_light.register(User, UserAutocomplete)


class GroupAutocomplete(autocomplete_light.AutocompleteModelBase):
    search_fields = ['name']

    def choices_for_request(self):
        self.choices = self.choices.filter(gaccess__active=True).exclude(
            name='Hydroshare Author')
        return super(GroupAutocomplete, self).choices_for_request()


autocomplete_light.register(Group, GroupAutocomplete)
Example #47
0

def normalize(name):
    """Normalize tag name"""
    clean_name = re.sub(r'\s+', ' ', name)
    return clean_name.strip().lower()


class Tag(TaggitTag):
    """Custom Tag Class"""
    def save(self, *args, **kwargs):
        """Normalize name before saving"""
        self.name = normalize(self.name)
        super(Tag, self).save(*args, **kwargs)

    class Meta:
        # pylint: disable=too-few-public-methods
        ordering = ['name']


class TaggedItemBase(GenericTaggedItemBase):
    """Custom Tagged Item Base Class"""
    tag = models.ForeignKey(Tag, related_name="%(app_label)s_%(class)s_items")


autocomplete_light.register(Tag,
                            attrs={
                                'placeholder': 'Search tags',
                                'data-autocomplete-minimum-characters': 1
                            })
    def dependent_paths(self):
        yield reverse('artist-list')
        yield self.get_absolute_url()
        yield reverse('artist-resume', kwargs={'slug': self.slug})
        yield reverse('artist-press-list', kwargs={'slug': self.slug})
        yield reverse('artist-exhibition-list', kwargs={'slug': self.slug})
        for exhibition in self.exhibitions.all():
            yield exhibition.get_absolute_url()

    @property
    def link_if_visible(self):
        if self.visible:
            return format_html(
                '<a href="{}">{}</a>',
                self.get_absolute_url(),
                self,
            )
        return str(self)


class ArtistPhoto(ArtworkPhoto):
    content_object = models.ForeignKey(Artist, related_name='photos')


url_tracker.track_url_changes_for_model(Artist)
dumper.register(Artist)
dumper.register(ArtistPhoto)
simpleimages.trackers.track_model(ArtistPhoto)
register(Artist, search_fields=['first_name', 'last_name'])
import autocomplete_light.shortcuts as al
from WordApp.models import Noun, Adjective, WordRoot
from autocomplete_light import shortcuts

shortcuts.register(WordRoot)
shortcuts.register(Noun)
shortcuts.register(Adjective)

Example #50
0
import autocomplete_light.shortcuts as al
from models import Person

# This will generate a PersonAutocomplete class.
al.register(
    Hero,
    # Just like in ModelAdmin.search_fields.
    search_fields=['name'],
    attrs={
        # This will set the input placeholder attribute:
        'placeholder': 'Other model name ?',
        # This will set the yourlabs.Autocomplete.minimumCharacters
        # options, the naming conversion is handled by jQuery.
        'data-autocomplete-minimum-characters': 1,
    },
    # This will set the data-widget-maximum-values attribute on the
    # widget container element, and will be set to
    # yourlabs.Widget.maximumValues (jQuery handles the naming
    # conversion).
    widget_attrs={
        'data-widget-maximum-values': 4,
        # Enable modern-style widget !
        'class': 'modern-style',
    },
)
__author__ = 'jcranwellward'


from autocomplete_light import shortcuts as autocomplete_light

from .models import (
    Grant
)

autocomplete_light.register(
    Grant,
    # Just like in ModelAdmin.search_fields
    search_fields=['^name', '^donor__name'],
    # This will actually html attribute data-placeholder which will set
    # javascript attribute widget.autocomplete.placeholder.
    autocomplete_js_attributes={'placeholder': 'Type donor name or grant',},
)
from __future__ import absolute_import, unicode_literals

import autocomplete_light.shortcuts as autocomplete_light
from taggit.models import Tag

from .models import Show, Host

# Taggit integration
autocomplete_light.register(
    Tag,
    attrs={
        'placeholder': 'Start typing to search.'
    }
)
# This will generate and register a ShowAutocomplete class
autocomplete_light.register(
    Show,
    # Just like in ModelAdmin.search_fields
    search_fields=['name'],
    # This will actually html attribute data-placeholder which will set
    # javascript attribute widget.autocomplete.placeholder.
    attrs={
        'data-autocomplete-minimum-characters': 2,
        'placeholder': 'Show search',
    },
)

# This will generate and register a HostAutocomplete class
autocomplete_light.register(
    Host,
    search_fields=['name', 'email'],
Example #53
0
    def ready(self):
        from django.conf import settings
        import autocomplete_light.shortcuts as autocomplete_light
        from ..models import Comune, Provincia, Regione, CittaMetropolitana
        autocomplete_light.register(
            Comune,
            search_fields=['^name'],
            attrs={
                'placeholder': 'Nome della città',
                'data-autocomplete-minimum-characters': 2,
            },
            widget_attrs={
                'data-widget-maximum-values':
                getattr(settings, "COMUNI_ITALIANI_AUTOCOMPLETE_RESULTS", 10),
                'class':
                'modern-style',
            },
        )

        autocomplete_light.register(
            Provincia,
            search_fields=['^name'],
            attrs={
                'placeholder': 'Nome della provincia',
                'data-autocomplete-minimum-characters': 2,
            },
            widget_attrs={
                'data-widget-maximum-values':
                getattr(settings, "COMUNI_ITALIANI_AUTOCOMPLETE_RESULTS", 10),
                'class':
                'modern-style',
            },
        )

        autocomplete_light.register(
            Regione,
            search_fields=['^name'],
            attrs={
                'placeholder': 'Nome della regione',
                'data-autocomplete-minimum-characters': 2,
            },
            widget_attrs={
                'data-widget-maximum-values':
                getattr(settings, "COMUNI_ITALIANI_AUTOCOMPLETE_RESULTS", 10),
                'class':
                'modern-style',
            },
        )

        autocomplete_light.register(
            CittaMetropolitana,
            search_fields=['^name'],
            attrs={
                'placeholder': 'Nome della città metropolitana',
                'data-autocomplete-minimum-characters': 2,
            },
            widget_attrs={
                'data-widget-maximum-values':
                getattr(settings, "COMUNI_ITALIANI_AUTOCOMPLETE_RESULTS", 10),
                'class':
                'modern-style',
            },
        )
from autocomplete_light import shortcuts as autocomplete_light
from teryt_tree.autocomplete_light_registry import (JednostkaAdministracyjnaAutocomplete,
                                                    CommunityAutocomplete)

from .models import JST


autocomplete_light.register(JST, JednostkaAdministracyjnaAutocomplete)
autocomplete_light.register(JST, CommunityAutocomplete)
from autocomplete_light import shortcuts as autocomplete_light

from .models import Partner


class PartnerAutocomplete(autocomplete_light.AutocompleteModelBase):
    search_fields = ['company_name']
    model = Partner

    # Without this line, the autocomplete apparently supplies all Partners,
    # even the NOT_AVAILABLE ones excluded by the default queryset, which causes
    # form submission to fail with DoesNotExist when people filter for an
    # unavailable partner. As this autocomplete is presented in a context where
    # NOT_AVAILABLE partners aren't allowed, let's filter them out. If we need
    # an autocomplete over all possible partners, create and register a
    # separate one and use that in other contexts.
    choices = Partner.objects.all()


autocomplete_light.register(PartnerAutocomplete)
Example #56
0
import autocomplete_light.shortcuts as al
from iati_codelists.models import Currency, Language, Sector, FileFormat

# This will generate a PersonAutocomplete class.
al.register(
    Currency,
    # Just like in ModelAdmin.search_fields.
    search_fields=['code', 'name'],
    attrs={
        # This will set the input placeholder attribute:
        'placeholder': 'Search currency',
        # This will set the yourlabs.Autocomplete.minimumCharacters
        # options, the naming conversion is handled by jQuery.
        'data-autocomplete-minimum-characters': 1,
    },
    # This will set the data-widget-maximum-values attribute on the
    # widget container element, and will be set to
    # yourlabs.Widget.maximumValues (jQuery handles the naming
    # conversion).
    widget_attrs={
        'data-widget-maximum-values': 4,
        # Enable modern-style widget !
        'class': 'modern-style',
    },
)

al.register(
    Language,
    search_fields=['code', 'name'],
    attrs={
        'placeholder': 'Search language',