Beispiel #1
0
class VentureServiceFilterForm(forms.Form):
    venture = AutoCompleteField(
        ('ralph.ui.channels', 'VentureLookup'),
        required=False,
        label=_('Venture'),
        help_text='Filter by venture',
    )
    service = AutoCompleteField(
        ('ralph.ui.channels', 'ServiceCatalogLookup'),
        required=False,
        label=_('Service catalog'),
        help_text='Filter by service',
    )
Beispiel #2
0
class SearchForm(forms.Form):
    q = AutoCompleteField('cliche',
                          required=True,
                          help_text="Autocomplete will suggest clichés about cats, but "
                                    "you can enter anything you like.",
                          label="Favorite Cliché",
                          attrs={'size': 100})
def make_ajax_field(model,model_fieldname,channel,**kwargs):
    """ makes an ajax select / multiple select / autocomplete field
        copying the label and help text from the model's db field
    
        optional args:
            help_text - note that django's ManyToMany db field will append 
                'Hold down "Control", or "Command" on a Mac, to select more than one.'
                to your db field's help text.
                Therefore you are better off passing it in here
            label - default is db field's verbose name
            required - default's to db field's (not) blank
            """

    from ajax_select.fields import AutoCompleteField, \
                                   AutoCompleteSelectMultipleField, \
                                   AutoCompleteSelectField

    field = model._meta.get_field(model_fieldname)
    if kwargs.has_key('label'):
        label = kwargs.pop('label')
    else:
        label = _(capfirst(unicode(field.verbose_name)))
    if kwargs.has_key('help_text'):
        help_text = kwargs.pop('help_text')
    else:
        if isinstance(field.help_text,basestring):
            help_text = _(field.help_text)
        else:
            help_text = field.help_text
    if kwargs.has_key('required'):
        required = kwargs.pop('required')
    else:
        required = not field.blank

    if isinstance(field,ManyToManyField):
        f = AutoCompleteSelectMultipleField(
            channel,
            required=required,
            help_text=help_text,
            label=label,
            **kwargs
            )
    elif isinstance(field,ForeignKey):
        f = AutoCompleteSelectField(
            channel,
            required=required,
            help_text=help_text,
            label=label,
            **kwargs
            )
    else:
        f = AutoCompleteField(
            channel,
            required=required,
            help_text=help_text,
            label=label,
            **kwargs
            )
    return f
Beispiel #4
0
class ItemAutoSelectForm(forms.Form):
    company = AutoCompleteField('company',
                                label="公司",
                                attrs={"size": 50},
                                help_text='输入公司名查找',
                                show_help_text=False,
                                required=True)
    receiver = AutoCompleteField('user',
                                 label='签收人',
                                 required=True,
                                 show_help_text=False)
    received_at = forms.DateField(initial=now, label='签收时间')

    helper = FormHelper()
    helper.form_tag = False
    helper.label_class = 'col-lg-2'
    helper.field_class = 'col-lg-10'
Beispiel #5
0
class BorrowerAutoSelectForm(forms.Form):
    borrower = AutoCompleteField('user',
                                 label='借用者',
                                 required=True,
                                 show_help_text=False)

    reason = forms.ChoiceField(label="事由", choices=(('公事', '公事'), ))

    helper = FormHelper()
Beispiel #6
0
class AdditionalsForm(
        with_metaclass(remove_spaces('identifiedby'), forms.ModelForm)):
    class Meta:
        model = Additionals

    species = AutoCompleteSelectField('species', required=True, label=_("Вид"))
    identifiedby = AutoCompleteField('identifiedby',
                                     required=False,
                                     label=_("Определелил(и)"),
                                     attrs={'size': CS})
Beispiel #7
0
class BookForm(forms.ModelForm):

    publisher = AutoCompleteSelectField('publisher', required=True)
    authors = AutoCompleteSelectMultipleField('author', required=False)

    author_select = AutoCompleteField('author',
                                      required=False,
                                      label=_('Simple select field'))

    class Meta:
        model = Book
Beispiel #8
0
class DetHistoryForm(
        with_metaclass(remove_spaces('identifiedby'), forms.ModelForm)):
    class Meta:
        model = DetHistory

    species = AutoCompleteSelectField('species',
                                      required=False,
                                      label=_("Вид"))
    identifiedby = AutoCompleteField('identifiedby',
                                     required=False,
                                     label=_("Переопределелил(и)"),
                                     attrs={'size': CS})
Beispiel #9
0
class UserAjaxPermissionForm(UserPermissionForm):
    """
    A class for building a permission form using an ajax autocomplete field.

    This class mimics the functionality of UserPermissionForm in django
    authority application, but instead of a Charfield for user field, uses
    an AutoCompleteField as specified by ajax_select application. Usernames
    are retrieved asynchronously with ajax calls and filling of the input field
    occurs with an automatic way.
    """

    user = AutoCompleteField('users', required=True, label=_('User'),
        help_text=_('Search for a username'))
Beispiel #10
0
class TransactionForm(ModelForm):
    class Meta:
        model = Transaction
        fields = ["name", "amount", "category", "date", "notes"]

    category = AutoCompleteField("categories")
    date = forms.DateTimeField(
        input_formats=["%m/%d/%Y"], widget=forms.DateInput(attrs={"autocomplete": "off"}, format="%m/%d/%Y")
    )
    notes = forms.CharField(widget=forms.Textarea(attrs={"autocomplete": "off"}))
    widget = forms.DateInput(
        attrs={"class": "datepicker form-control", "placeholder": "Select a date"}, format="%m/%d/%Y"
    )
def make_ajax_field(model,
                    model_fieldname,
                    channel,
                    show_help_text=False,
                    **kwargs):
    """ Makes a single autocomplete field for use in a Form

        optional args:
            help_text - default is the model db field's help_text.
                None will disable all help text
            label     - default is the model db field's verbose name
            required  - default is the model db field's (not) blank

            show_help_text -
                Django will show help text below the widget, but not for ManyToMany inside of admin inlines
                This setting will show the help text inside the widget itself.
    """
    # will support previous arg name for several versions before deprecating
    if 'show_m2m_help' in kwargs:
        show_help_text = kwargs.pop('show_m2m_help')

    from ajax_select.fields import AutoCompleteField, \
        AutoCompleteSelectMultipleField, \
        AutoCompleteSelectField

    field = model._meta.get_field(model_fieldname)
    if not kwargs.has_key('label'):
        kwargs['label'] = _(capfirst(unicode(field.verbose_name)))

    if not kwargs.has_key('help_text') and field.help_text:
        kwargs['help_text'] = field.help_text
    if not kwargs.has_key('required'):
        kwargs['required'] = not field.blank

    kwargs['show_help_text'] = show_help_text
    if not hasattr(kwargs, 'plugin_options'):
        kwargs['plugin_options'] = {}
    kwargs['plugin_options'].update({
        'app_label': field.rel.to._meta.app_label,
        'channel': channel,
        'model': model._meta.object_name
    })

    if isinstance(field, ManyToManyField):
        f = AutoCompleteSelectMultipleField(channel, **kwargs)
    elif isinstance(field, ForeignKey):
        f = AutoCompleteSelectField(channel, **kwargs)
    else:
        f = AutoCompleteField(channel, **kwargs)
    return f
Beispiel #12
0
class SearchGamesForm(forms.Form):

    q = AutoCompleteField(
        'game',
        required=True,
        #help_text="Pesquise por jogos.",
        label="",
        show_help_text=False,
        attrs={
            'size': 50,
            'placeholder': 'Buscar por Jogos'
        })

    class Media:
        css = {'all': ('css/games/game_list.css', )}
Beispiel #13
0
def make_ajax_form(model, fieldlist, superclass=ModelForm):
    """ this will create a ModelForm subclass inserting
            AutoCompleteSelectMultipleField (many to many),
            AutoCompleteSelectField (foreign key)

        where specified in the fieldlist:

            dict(fieldname='channel',...)

        usage:
            class YourModelAdmin(Admin):
                ...
                form = make_ajax_form(YourModel,dict(contacts='contact',author='contact'))

            where 'contacts' is a many to many field, specifying to use the lookup channel 'contact'
            and
            where 'author' is a foreign key field, specifying here to also use the lookup channel 'contact'

    """
    from ajax_select.fields import AutoCompleteField, \
                                   AutoCompleteSelectMultipleField, \
                                   AutoCompleteSelectField

    class TheForm(superclass):
        class Meta:
            pass

        setattr(Meta, 'model', model)

    for model_fieldname, channel in fieldlist.iteritems():

        field = model._meta.get_field(model_fieldname)

        if isinstance(field, ManyToManyField):
            f = AutoCompleteSelectMultipleField(channel,
                                                required=not field.blank)
        elif isinstance(field, ForeignKey):
            f = AutoCompleteSelectField(channel, required=not field.blank)
        else:
            f = AutoCompleteField(channel, required=not field.blank)

        # django internals are very difficult to work with.
        # it requires too much knowledge and is thus breakable
        TheForm.declared_fields[model_fieldname] = f
        TheForm.base_fields[model_fieldname] = f
        setattr(TheForm, model_fieldname, f)

    return TheForm
Beispiel #14
0
def make_ajax_field(related_model, fieldname_on_model, channel, show_help_text=False, **kwargs):
    """Makes an AutoComplete field for use in a Form.

    Args:
        related_model (Model): model of the related object
        fieldname_on_model (str): field name on the model being edited
        channel (str): channel name of a registered LookupChannel
        show_help_text (bool): show or supress help text below the widget
            Django admin will show help text below the widget, but not for ManyToMany inside of admin inlines
            This setting will show the help text inside the widget itself.
        kwargs: optional args

            - help_text: default is the model db field's help_text.
                            None will disable all help text
            - label: default is the model db field's verbose name
            - required: default is the model db field's (not) blank

    Returns:
        (AutoCompleteField, AutoCompleteSelectField, AutoCompleteSelectMultipleField): field
    """
    from ajax_select.fields import AutoCompleteField, \
                                   AutoCompleteSelectMultipleField, \
                                   AutoCompleteSelectField

    field = related_model._meta.get_field(fieldname_on_model)
    if 'label' not in kwargs:
        kwargs['label'] = _(capfirst(force_text(field.verbose_name)))

    if ('help_text' not in kwargs) and field.help_text:
        kwargs['help_text'] = field.help_text
    if 'required' not in kwargs:
        kwargs['required'] = not field.blank

    kwargs['show_help_text'] = show_help_text
    if isinstance(field, ManyToManyField):
        f = AutoCompleteSelectMultipleField(
            channel,
            **kwargs)
    elif isinstance(field, ForeignKey):
        f = AutoCompleteSelectField(
            channel,
            **kwargs)
    else:
        f = AutoCompleteField(
            channel,
            **kwargs)
    return f
Beispiel #15
0
class MessageForm(forms.ModelForm):
    """
    The form a user fills in when creating a new message
    """
    user_to = AutoCompleteField("usernames",
                                required=False,
                                help_text=None,
                                label="To")

    class Meta:
        model = Message
        fields = ["title", "message"]

    def clean_user_to(self):
        try:
            data = self.cleaned_data["user_to"]
            return User.objects.get(username=data)
        except User.DoesNotExist:
            raise forms.ValidationError("Please enter an existing username")
Beispiel #16
0
class CourseForm(NiceErrorModelForm, DependentModelForm):
    """ A course form which adds a honeypot and autocompletes some fields. """
    # first argument is ajax channel name, defined in models as LookupChannel.
    # note this AJAX field returns a field value, not a course object.
    name = AutoCompleteField('course_name_by_name', help_text='',
        label=mark_safe('Course name <span class="required-field">(required)</span>'))

    def __init__(self, *args, **kwargs):
        """ Add a dynamically named field. """
        super(CourseForm, self).__init__(*args, **kwargs)
        # insert honeypot into a random order on the form.
        idx = random.randint(0, len(self.fields))
        self.fields.insert(idx, settings.HONEYPOT_FIELD_NAME,
            CharField(required=False, label=mark_safe(settings.HONEYPOT_LABEL))
        )

    class Meta:
        model = Course
        # order the fields
        fields = ('name', 'url')
        model_fields = {
            # pass department data onto DepartmentForm
            'department': DepartmentForm,
            # pass professor data onto ProfessorForm
            'professor': ProfessorForm,
        }

    def clean(self, *args, **kwargs):
        """ Honeypot validation. """

        # Call ModelFormMixin or whoever normally cleans house.
        cleaned_data = super(CourseForm, self).clean(*args, **kwargs)

        # Check the honeypot
        # parts of this code borrow from
        # https://github.com/sunlightlabs/django-honeypot
        hfn = settings.HONEYPOT_FIELD_NAME
        formhoneypot = cleaned_data.get(hfn, None)
        if formhoneypot and (formhoneypot != settings.HONEYPOT_VALUE):
            # Highlight the failure to follow instructions.
            self._errors[hfn] = [settings.HONEYPOT_ERROR]
            del cleaned_data[hfn]
        return cleaned_data
Beispiel #17
0
 def __init__(self, *args, **kwargs):
     instr = kwargs.pop("instr", None)
     # allow possibility to exclude fields from form
     exclude = kwargs.pop("exclude", None)
     super(InvitationForm, self).__init__(*args, **kwargs)
     # remove "-----" options from ForeignKey fields
     self.fields["group"].empty_label = None
     self.fields["group"].widget.choices = self.fields["group"].choices
     self.fields["invited_instrument"].empty_label = None
     self.fields["invited_instrument"].widget.choices = self.fields[
         "invited_instrument"].choices
     # need to add the invited_user field separately as an AutoCompleteField
     if instr:
         self.fields["invited_user"] = AutoCompleteField(
             "user_playing_" + instr,
             label="User to invite",
             help_text=None)
     for field_name in exclude:
         try:
             del self.fields[field_name]
         except KeyError:
             # can't delete the invited_user field if it wasn't created -
             # but can just ignore this error
             pass
Beispiel #18
0
def make_ajax_field(model,
                    model_fieldname,
                    channel,
                    show_help_text=False,
                    **kwargs):
    """ Makes a single autocomplete field for use in a Form

        optional args:
            help_text - default is the model db field's help_text. 
                None will disable all help text
            label     - default is the model db field's verbose name
            required  - default is the model db field's (not) blank
        
            show_help_text - 
                Django will show help text below the widget, but not for ManyToMany inside of admin inlines
                This setting will show the help text inside the widget itself.
    """
    # will support previous arg name for several versions before deprecating
    if 'show_m2m_help' in kwargs:
        show_help_text = kwargs.pop('show_m2m_help')

    from ajax_select.fields import AutoCompleteField, \
                                   AutoCompleteSelectMultipleField, \
                                   AutoCompleteSelectField

    field = model._meta.get_field(model_fieldname)
    if kwargs.has_key('label'):
        label = kwargs.pop('label')
    else:
        label = _(capfirst(unicode(field.verbose_name)))

    if kwargs.has_key('help_text'):
        help_text = kwargs.pop('help_text')
    else:
        if isinstance(field.help_text, basestring) and field.help_text:
            help_text = _(field.help_text)
        else:
            help_text = field.help_text
    if kwargs.has_key('required'):
        required = kwargs.pop('required')
    else:
        required = not field.blank

    kwargs['show_help_text'] = show_help_text
    if isinstance(field, ManyToManyField):
        f = AutoCompleteSelectMultipleField(channel,
                                            required=required,
                                            help_text=help_text,
                                            label=label,
                                            **kwargs)
    elif isinstance(field, ForeignKey):
        f = AutoCompleteSelectField(channel,
                                    required=required,
                                    help_text=help_text,
                                    label=label,
                                    **kwargs)
    else:
        f = AutoCompleteField(channel,
                              required=required,
                              help_text=help_text,
                              label=label,
                              **kwargs)
    return f
Beispiel #19
0
class UserAutoSelectForm(forms.Form):
    user = AutoCompleteField('user', label='用户', required=True)
Beispiel #20
0
class SearchAssetForm(Form):
    """returns search asset form for DC and BO.

    :param mode: one of `dc` for DataCenter or `bo` for Back Office
    :returns Form
    """
    model = AutoCompleteField(
        LOOKUPS['asset_model'],
        required=False,
        help_text=None,
    )
    manufacturer = AutoCompleteField(
        LOOKUPS['asset_manufacturer'],
        required=False,
        help_text=None,
    )
    invoice_no = CharField(required=False)
    order_no = CharField(required=False)
    provider = CharField(required=False, label='Provider')
    status = ChoiceField(required=False,
                         choices=[('', '----')] + AssetStatus(),
                         label='Status')
    part_info = ChoiceField(required=False,
                            choices=[('', '----'), ('device', 'Device'),
                                     ('part', 'Part')],
                            label='Asset type')
    category = TreeNodeChoiceField(
        required=False,
        queryset=AssetCategory.tree.all(),
        level_indicator='|---',
        empty_label="---",
    )
    source = ChoiceField(
        required=False,
        choices=[('', '----')] + AssetSource(),
    )
    niw = CharField(required=False, label='Niw')
    sn = CharField(required=False, label='SN')
    barcode = CharField(required=False, label='Barcode')
    ralph_device_id = IntegerField(
        required=False,
        label='Ralph device id',
    )
    request_date_from = DateField(
        required=False,
        widget=DateWidget(attrs={
            'placeholder': 'Start YYYY-MM-DD',
            'data-collapsed': True,
        }),
        label="Request date",
    )
    request_date_to = DateField(required=False,
                                widget=DateWidget(
                                    attrs={
                                        'class': 'end-date-field ',
                                        'placeholder': 'End YYYY-MM-DD',
                                        'data-collapsed': True,
                                    }),
                                label='')
    provider_order_date_from = DateField(
        required=False,
        widget=DateWidget(attrs={
            'placeholder': 'Start YYYY-MM-DD',
            'data-collapsed': True,
        }),
        label="Provider order date",
    )
    provider_order_date_to = DateField(required=False,
                                       widget=DateWidget(
                                           attrs={
                                               'class': 'end-date-field ',
                                               'placeholder': 'End YYYY-MM-DD',
                                               'data-collapsed': True,
                                           }),
                                       label='')
    delivery_date_from = DateField(
        required=False,
        widget=DateWidget(attrs={
            'placeholder': 'Start YYYY-MM-DD',
            'data-collapsed': True,
        }),
        label="Delivery date",
    )
    delivery_date_to = DateField(required=False,
                                 widget=DateWidget(
                                     attrs={
                                         'class': 'end-date-field ',
                                         'placeholder': 'End YYYY-MM-DD',
                                         'data-collapsed': True,
                                     }),
                                 label='')
    deprecation_rate = ChoiceField(required=False,
                                   choices=[
                                       ('', '----'),
                                       ('null', 'None'),
                                       ('48>', '48 <'),
                                       ('48', '24 < * <= 48'),
                                       ('24', '12 < * <= 24'),
                                       ('12', '6 < * <= 12'),
                                       ('6', '* <= 6'),
                                       ('deprecated', 'Deprecated'),
                                   ],
                                   label='Deprecation')
    invoice_date_from = DateField(
        required=False,
        widget=DateWidget(attrs={
            'placeholder': 'Start YYYY-MM-DD',
            'data-collapsed': True,
        }),
        label="Invoice date",
    )
    invoice_date_to = DateField(required=False,
                                widget=DateWidget(
                                    attrs={
                                        'class': 'end-date-field ',
                                        'placeholder': 'End YYYY-MM-DD',
                                        'data-collapsed': True,
                                    }),
                                label='')

    production_use_date_from = DateField(
        required=False,
        widget=DateWidget(attrs={
            'placeholder': 'Start YYYY-MM-DD',
            'data-collapsed': True,
        }),
        label="Production use date",
    )
    production_use_date_to = DateField(required=False,
                                       widget=DateWidget(
                                           attrs={
                                               'class': 'end-date-field ',
                                               'placeholder': 'End YYYY-MM-DD',
                                               'data-collapsed': True,
                                           }),
                                       label='')
    unlinked = BooleanField(required=False, label="Is unlinked")
    deleted = BooleanField(required=False, label="Include deleted")

    def __init__(self, *args, **kwargs):
        # Ajax sources are different for DC/BO, use mode for distinguish
        mode = kwargs.get('mode')
        if mode:
            del kwargs['mode']
        super(SearchAssetForm, self).__init__(*args, **kwargs)
        category = self.fields['category'].queryset
        if mode == 'dc':
            self.fields['category'].queryset = category.filter(
                type=AssetCategoryType.data_center)
        elif mode == 'back_office':
            self.fields['category'].queryset = category.filter(
                type=AssetCategoryType.back_office)
Beispiel #21
0
class HerbItemForm(
        with_metaclass(
            remove_spaces('collectedby', 'identifiedby', 'region', 'district'),
            forms.ModelForm)):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(HerbItemForm, self).__init__(*args, **kwargs)

    def clean_itemcode(self):
        data = self.cleaned_data['itemcode']
        data = data.strip()
        if data:
            mainquery = HerbItem.objects.filter(itemcode=data)
            if self.instance:
                mainquery = mainquery.exclude(id=self.instance.id)
            if self.request:
                query = HerbAcronym.objects.filter(
                    allowed_users__icontains=self.request.user.username)
            else:
                query = None
            if query:
                if mainquery.filter(acronym=query[0]).exists():
                    raise forms.ValidationError(
                        _("запись с таким кодом уже существует"))
            if not itemcode_pat.match(data):
                raise forms.ValidationError(
                    _("уникальный код должен либо отсутствовать, либо быть числовым"
                      ))
        return data

    def _verify_dates(self, data):
        if data:
            if data > (timezone.now() + timedelta(days=2)).date():
                raise forms.ValidationError(
                    _("Дата не может быть больше текущей календарной даты"))

            if data < date(year=1700, month=1, day=1):
                raise forms.ValidationError(
                    _("Не ошибка ли это? Слишком древний образец."))

    def clean_identified_s(self):
        data = self.cleaned_data['identified_s']
        self._verify_dates(data)
        return data

    def clean_identified_e(self):
        data = self.cleaned_data['identified_e']
        self._verify_dates(data)
        return data

    def clean_collected_s(self):
        data = self.cleaned_data['collected_s']
        self._verify_dates(data)
        return data

    def clean_collected_e(self):
        data = self.cleaned_data['collected_e']
        self._verify_dates(data)
        return data

    def clean(self):
        '''Checking consistency for dates '''
        formdata = self.cleaned_data
        d1 = formdata.get('identified_s')
        d2 = formdata.get('identified_e')
        if d1 and d2:
            if d2 < d1:
                self._errors.setdefault('identified_e', ErrorList())
                self._errors['identified_e'].append(
                    _('дата окончания определения должна быть не раньше даты начала'
                      ))

        dc1 = formdata.get('collected_s')
        dc2 = formdata.get('collected_e')
        if d1 and d2:
            if d2 < d1:
                self._errors.setdefault('collected_e', ErrorList())
                self._errors['collected_e'].append(
                    _('дата окончания определения должна быть не раньше даты начала'
                      ))
        if dc1 and d1:
            if d1 < dc1:
                self._errors.setdefault('identified_s', ErrorList())
                self._errors['identified_s'].append(
                    _('дата определения не может быть раньше даты сбора'))
        if dc1 and dc2:
            if dc2 < dc1:
                self._errors.setdefault('collected_e', ErrorList())
                self._errors['collected_e'].append(
                    _('дата окончания сбора должна быть не раньше даты начала')
                )
        ispub = formdata.get('public')
        icode = formdata.get('itemcode')
        sp = formdata.get('species')
        if icode:
            icode = icode.strip()
        if ispub:
            if not icode:
                forms.ValidationError(
                    _('публиковать можно только при непустом уникальном коде образца'
                      ))
            if sp:
                if sp.status not in ['A', 'P']:
                    raise forms.ValidationError(
                        _('вид не одобрен куратором; опубликовать можно только одобренные виды'
                          ))
        return formdata

    class Meta:
        model = HerbItem

    species = AutoCompleteSelectField('species',
                                      required=True,
                                      help_text=None,
                                      label=_("Вид"))
    if TinyMCE:
        note = forms.CharField(widget=TinyMCE(mce_attrs=tinymce_fieldset),
                               required=False,
                               label=_('Заметки'))
        detailed = forms.CharField(widget=TinyMCE(mce_attrs=tinymce_fieldset),
                                   required=False,
                                   label=_('Место сбора'))
    else:
        note = forms.CharField(widget=forms.Textarea,
                               required=False,
                               label=_('Заметки'))
        detailed = forms.CharField(widget=forms.Textarea,
                                   required=False,
                                   label=_('Место сбора'))
    detailed.help_text = _("локализация, экоусловия")
    country = AutoCompleteSelectField('country',
                                      required=False,
                                      help_text=None,
                                      label=_("Страна"))
    region = AutoCompleteField('region',
                               required=False,
                               help_text=None,
                               label=_("Регион"),
                               attrs={'size': CS})
    district = AutoCompleteField('district',
                                 required=False,
                                 help_text=None,
                                 label=_("Район"),
                                 attrs={'size': CS})
    collectedby = AutoCompleteField('collectedby',
                                    required=False,
                                    help_text=None,
                                    label=_("Собрали"),
                                    attrs={'size': CS})
    identifiedby = AutoCompleteField('identifiedby',
                                     required=False,
                                     help_text=None,
                                     label=_("Определили"),
                                     attrs={'size': CS})
Beispiel #22
0
class AutoCompanyForm(forms.Form):
    """公司搜索表单"""
    q = AutoCompleteField('company', show_help_text=False)
def make_ajax_field(model,
                    model_fieldname,
                    channel,
                    show_m2m_help=False,
                    **kwargs):
    """ Makes a single autocomplete field for use in a Form

        optional args:
            help_text - default is the model field's help_text 
            label     - default is the model field's verbose name
            required  - default is the model field's (not) blank
        
            show_m2m_help - 
                Django will show help text in the Admin for ManyToMany fields,
                in which case the help text should not be shown in side the widget itself
                or it appears twice.
                
                ForeignKey fields do not behave like this.
                ManyToMany inside of admin inlines do not do this. [so set show_m2m_help=True]
    
                But if used outside of the Admin or in an ManyToMany admin inline then you need the help text.
    """

    from ajax_select.fields import AutoCompleteField, \
                                   AutoCompleteSelectMultipleField, \
                                   AutoCompleteSelectField

    field = model._meta.get_field(model_fieldname)
    if kwargs.has_key('label'):
        label = kwargs.pop('label')
    else:
        label = _(capfirst(unicode(field.verbose_name)))

    if kwargs.has_key('help_text'):
        help_text = kwargs.pop('help_text')
    else:
        if isinstance(field.help_text, basestring) and field.help_text:
            help_text = _(field.help_text)
        else:
            help_text = field.help_text
    if kwargs.has_key('required'):
        required = kwargs.pop('required')
    else:
        required = not field.blank

    if isinstance(field, ManyToManyField):
        kwargs['show_help_text'] = show_m2m_help
        f = AutoCompleteSelectMultipleField(channel,
                                            required=required,
                                            help_text=help_text,
                                            label=label,
                                            **kwargs)
    elif isinstance(field, ForeignKey):
        f = AutoCompleteSelectField(channel,
                                    required=required,
                                    help_text=help_text,
                                    label=label,
                                    **kwargs)
    else:
        f = AutoCompleteField(channel,
                              required=required,
                              help_text=help_text,
                              label=label,
                              **kwargs)
    return f
Beispiel #24
0
class ResourceSearchForm(SearchForm):
    """
    Main search form.
    
    Ordering of results is computed according to the following:
    
    """
    def __init__(self, *args, **kwargs):
        kwargs['auto_id'] = True
        kwargs['label_suffix'] = ''
        super(ResourceSearchForm, self).__init__(*args, **kwargs)

    #q = forms.CharField(label=__(u'Quoi?'), initial='',required=True)
    q = AutoCompleteField('resource',
                          help_text='',
                          label=__(u'Quoi?'),
                          initial='',
                          required=True)
    a = AutoCompleteField('location',
                          help_text='',
                          label=__(u'Où?'),
                          initial='',
                          required=False)
    t = RecurrenceField(label=__(u'Quand?'),
                        initial='',
                        required=False,
                        max_rdates=0,
                        max_exdates=0)
    d = forms.CharField(label=__(u'Quand?'), initial='', required=False)

    def search(self):
        # First, store the SearchQuerySet received from other processing.
        sqs = super(ResourceSearchForm, self).search()
        address = self.cleaned_data.get('a')
        if (address):
            g = geocoders.Nominatim(
            )  # this should be changed to openstreetmap
            try:
                place, (lat, lng) = g.geocode(address)
                print "address: %s, lat : %g, lng : %g" % (address, lat, lng)
                loc = Point(lng, lat)
                max_dist = D(km=10)
                #sqs = sqs.dwithin('location',loc,max_dist).distance('location',loc)
            except geopy.exc.GeocoderServiceError:
                pass
        time = self.cleaned_data.get('t')
        if (time):
            # extract serialized events from search query set index
            events = sqs.exclude(event='toto')
            excluded = list()
            for e in events:
                if e.event:
                    # we only check if we can go to the next upcoming occurrence
                    # checking all occurrences would be too costly
                    ev = deserialize(e.event).after(datetime.now())
                    if not ev in time.occurrences(dtstart=ev):
                        excluded.append(e.pk)
            if (excluded):
                sqs = sqs.exclude(id__in=excluded)
        return sqs

    def no_query_found(self):
        return self.searchqueryset.all()