Пример #1
0
class StartTrajectoryForm(forms.Form):
    majors = forms.ChoiceField(widget=forms.SelectMultiple,
                               choices=[(obj.id, obj.name)
                                        for obj in Major.objects.all()])
    minors = forms.ChoiceField(widget=forms.SelectMultiple,
                               choices=[(obj.id, obj.name)
                                        for obj in Minor.objects.all()])
Пример #2
0
class TrendtimeForm(forms.Form):
    """
    Form to display bank transaction sums with a timeline.
    """
    CHART_LINE = 'line'
    CHART_BAR = 'bar'
    CHART_RADAR = 'radar'
    CHART_TYPES = (
        (CHART_LINE, ugettext_lazy('Line')),
        (CHART_BAR, ugettext_lazy('Bar')),
        (CHART_RADAR, ugettext_lazy('Radar')),
    )
    chart = forms.ChoiceField(choices=CHART_TYPES, initial=CHART_LINE)

    GRANULARITY_CHOICES = (
        (GRANULARITY_WEEK, ugettext_lazy('Week')),
        (GRANULARITY_MONTH, ugettext_lazy('Month')),
    )
    granularity = forms.ChoiceField(
        choices=GRANULARITY_CHOICES,
        initial=GRANULARITY_MONTH,
    )

    date = forms.DateField(required=True, widget=Datepicker())

    reconciled = forms.NullBooleanField(required=False)

    def __init__(self, *args, **kwargs):
        super(TrendtimeForm, self).__init__(*args, **kwargs)
        self.fields['reconciled'].widget.choices[0] = ('1', _('Reconciled?'))
        self.fields['date'].initial = formats.date_format(
            datetime.date.today(),
            'SHORT_DATE_FORMAT',
        )
Пример #3
0
class CallSearch(forms.Form):
    org_type = forms.ChoiceField(choices=ORG_TYPE_CHOICES, required=False)
    clause = forms.ChoiceField(choices=(('', u'Tout voir'), ) + CLAUSE_CHOICES, required=False)
    organization = forms.ModelChoiceField(queryset=Organization.objects.filter(is_customer=True, status=ORGANIZATION_STATUSES.VALIDATED), required=False, empty_label=u'Toutes')
    sector = forms.ModelChoiceField(queryset=ActivityNomenclature.objects.filter(level=0), empty_label=u'Tout voir', required=False)
    period = forms.ChoiceField(choices=PERIOD_CHOICES, required=False)
    q = forms.CharField(required=False)

    def __init__(self, *args, **kwargs):
        super(CallSearch, self).__init__(*args, **kwargs)
        for field in self.fields.itervalues():
            field.widget.attrs['class'] = 'form-control'
Пример #4
0
class GenerateStatisticsForm(Form):
    provider_model = forms.ChoiceField(label=_('Report Type'),
                                       help_text=_('Select statistics provider.'))
    date_start = forms.DateField(label=_('Time Period'),
                                 help_text=_('Enter start and end date for time period you want to take data from to use in graph.'),
                                 initial=tz.now() - timedelta(days=7))
    date_end = forms.DateField(initial=tz.now() + timedelta(days=1))
    stats_precision = forms.ChoiceField(label=_('Graph Precision'),
                                        choices=(('day', _('For each day')), ('week', _('For each week')), ('month', _('For each month')), ('year', _('For each year'))))

    def __init__(self, *args, **kwargs):
        provider_choices = kwargs.get('provider_choices')
        del kwargs['provider_choices']
        super(GenerateStatisticsForm, self).__init__(*args, **kwargs)
        self.fields['provider_model'] = forms.ChoiceField(choices=provider_choices)
Пример #5
0
class OrgSearch(forms.Form):
    org_type = forms.ChoiceField(choices=ORG_TYPE_CHOICES, required=False)
    prov_type = forms.ModelChoiceField(queryset=AgreementIAE.objects.all(),
                                       empty_label=u'Tout voir',
                                       required=False)
    interim = forms.BooleanField(required=False)
    sector = forms.ModelChoiceField(
        queryset=ActivityNomenclature.objects.filter(level=0),
        empty_label=u'Tout voir',
        required=False)
    area = AutoCompleteSelectField(lookup_class=AreaLookup, required=False)
    radius = forms.IntegerField(required=False)
    q = forms.CharField(
        required=False,
        widget=forms.TextInput(attrs={
            'class': 'form-control',
            'placeholder': 'Recherche libre : mot clés'
        }))

    def __init__(self, *args, **kwargs):
        super(OrgSearch, self).__init__(*args, **kwargs)
        for name, field in self.fields.iteritems():
            if name == 'interim':
                continue
            field.widget.attrs['class'] = 'form-control'
        self.fields['area'].widget.attrs['placeholder'] = u'Tout voir'
        self.fields['area'].widget.attrs[
            'class'] = u'form-control form-control-small'
        self.fields['radius'].widget.attrs['placeholder'] = u'Dans un rayon de'
        self.fields['radius'].widget.attrs[
            'class'] = u'form-control form-control-small'
Пример #6
0
class UserForumOptionsForm(Form):
    newsletters = forms.BooleanField(label=_("Newsletters"),
                                     help_text=_("On occasion board administrator may want to send e-mail message to multiple members."),
                                     required=False)
    timezone = forms.ChoiceField(label=_("Your Current Timezone"),
                                 help_text=_("If dates and hours displayed by forums are inaccurate, you can fix it by adjusting timezone setting."),
                                 choices=tzlist())
    hide_activity = forms.TypedChoiceField(label=_("Your Visibility"),
                                           help_text=_("If you want to, you can limit other members ability to track your presence on forums."),
                                           choices=(
                                                    (0, _("Show my presence to everyone")),
                                                    (1, _("Show my presence to people I follow")),
                                                    (2, _("Show my presence to nobody")),
                                                    ), coerce=int)
    subscribe_start = forms.TypedChoiceField(label=_("Threads I start"),
                                             choices=(
                                                      (0, _("Don't watch")),
                                                      (1, _("Put on watched threads list")),
                                                      (2, _("Put on watched threads list and e-mail me when somebody replies")),
                                                      ), coerce=int)
    subscribe_reply = forms.TypedChoiceField(label=_("Threads I reply to"),
                                             choices=(
                                                      (0, _("Don't watch")),
                                                      (1, _("Put on watched threads list")),
                                                      (2, _("Put on watched threads list and e-mail me when somebody replies")),
                                                      ), coerce=int)
    allow_pds = forms.TypedChoiceField(label=_("Allow Private Threads Invitations"),
                                       help_text=_("If you wish, you can restrict who can invite you to private threads. Keep in mind some groups or members may be allowed to override this preference."),
                                       choices=(
                                                (0, _("From everyone")),
                                                (1, _("From everyone but not members I ignore")),
                                                (2, _("From members I follow")),
                                                (2, _("From nobody")),
                                                ), coerce=int)
Пример #7
0
    def __init__(self, *args, **kwargs):
        """Accepts ``environments`` queryset and ``current`` env id."""
        environments = kwargs.pop("environments", [])
        current = kwargs.pop("current", None)

        super(EnvironmentSelectionForm, self).__init__(*args, **kwargs)

        # list of categories, ordered by name
        self.categories = []

        # maps category to set of elements
        self.elements_by_category = {}

        # maps environment ID to list of element IDs, ordered by category
        self.elementids_by_envid = {}

        # elements in current environment
        current_elements = []

        env_element_through_model = model.Environment.elements.through
        env_element_relationships = env_element_through_model.objects.filter(
            environment__in=environments).select_related()

        # first construct the ordered list of categories (and current elements)
        cat_set = set()
        for ee in env_element_relationships:
            cat_set.add(ee.element.category)
            if ee.environment.id == current:
                current_elements.append(ee.element)
        self.categories = sorted(cat_set, key=lambda c: c.name)

        num_categories = len(self.categories)

        # populate elements by category and environment
        for ee in env_element_relationships:
            byenv = self.elementids_by_envid.setdefault(
                ee.environment.id, [None] * num_categories)
            category_index = self.categories.index(ee.element.category)
            byenv[category_index] = ee.element.id

            bycat = self.elements_by_category.setdefault(
                ee.element.category, set())
            bycat.add(ee.element)

        # construct choice-field for each env type
        for category in self.categories:
            self.fields["category_{0}".format(
                category.id)] = forms.ChoiceField(
                    choices=[("", "---------")] +
                    [(e.id, e.name)
                     for e in sorted(self.elements_by_category[category],
                                     key=lambda e: e.name)],
                    label=category.name,
                    required=False)

        # set initial data based on current user environment
        for element in current_elements:
            field_name = "category_{0}".format(element.category.id)
            self.initial[field_name] = element.id
Пример #8
0
class ReadForm(forms.Form):
    READ_ALL = 'read-all'
    READ_PAGE = 'read-page'

    action = forms.ChoiceField(
        choices=(
            (READ_ALL, 'read all'),
            (READ_PAGE, 'read page'),
        ),
        widget=forms.HiddenInput,
        initial='read-all',
    )

    def __init__(self,
                 entries=None,
                 feed=None,
                 category=None,
                 user=None,
                 pages_only=False,
                 *args,
                 **kwargs):
        if entries is not None:
            entries = entries.filter(read=False)
        self.entries = entries
        self.feed = feed
        self.category = category
        self.user = user
        self.pages_only = pages_only
        super(ReadForm, self).__init__(*args, **kwargs)
        if self.pages_only:
            self.fields['entries'] = forms.CharField(widget=forms.HiddenInput)

    def clean_entries(self):
        return json.loads(self.cleaned_data['entries'])

    def save(self):
        if self.pages_only:
            # pages is a list of IDs to mark as read
            entries = self.user.entries.filter(
                pk__in=self.cleaned_data['entries'])
        else:
            entries = self.entries
        pks = list(entries.values_list('pk', flat=True))
        entries.update(read=True)
        if self.feed is not None:
            feeds = Feed.objects.filter(pk=self.feed.pk)
        elif self.category is not None:
            feeds = self.category.feeds.all()
        else:
            feeds = self.user.feeds.all()

        if self.pages_only:
            # TODO combine code with mark-all-as-read?
            for feed in feeds:
                Feed.objects.filter(pk=feed.pk).update(
                    unread_count=feed.entries.filter(read=False).count())
        else:
            feeds.update(unread_count=0)
        return pks
Пример #9
0
 def make_thread_form(self):
     self.thread_form = None
     list_choices = self.thread_actions();
     if (not self.request.user.is_authenticated()
         or not list_choices):
         return
     form_fields = {'thread_action': forms.ChoiceField(choices=list_choices)}
     self.thread_form = type('ThreadViewForm', (Form,), form_fields)
Пример #10
0
class ActionForm(forms.Form):
    action = forms.ChoiceField(choices=(
        ('images', 'images'),
        ('unread', 'unread'),
        ('read_later', 'read_later'),
        ('star', 'star'),
        ('unstar', 'unstar'),
    ))
Пример #11
0
    def __init__(self, queryset, filters, columns, search, *args, **kwargs):
        super(QueryForm, self).__init__(*args, **kwargs)
        self.model = queryset.model
        self.queryset = queryset.all()
        self.columns = columns
        # Records whether this instance needs to use a distinct query
        self.use_distinct = False

        if columns:
            self.order_fields = {}
            for column in columns:
                if isinstance(column, basestring):
                    order = force_unicode(column)
                    try:
                        self.model._meta.get_field(column)
                    except FieldDoesNotExist:
                        if (hasattr(self.model, column)
                                and hasattr(column, 'admin_order_field')):
                            order = column.admin_order_field
                        else:
                            continue
                elif hasattr(column, 'admin_order_field'):
                    order = column.admin_order_field
                else:
                    continue
                self.order_fields[column] = order
            if self.order_fields:
                choices = reduce(operator.add,
                                 (((f, f),
                                   (_reverse_order(f), _reverse_order(f)))
                                  for f in self.order_fields.itervalues()))
                self.fields['order'] = forms.ChoiceField(choices=choices,
                                                         required=False)

        self.search = search
        if search:
            self.fields['search'] = forms.CharField(required=False)

        self.filters = filters
        if filters:
            if 'search' in filters or 'order' in filters:
                raise ValueError(
                    "'search' and 'order' can't be used as filter names.")
            for f in filters:
                if isinstance(f, basestring):
                    model_field = self.model._meta.get_field(f).__class__
                    if model_field in self.model_field_filters:
                        field_class = self.model_field_filters[model_field]
                    else:
                        field_class = SimpleFilterField
                    field = field_class(self.model, f, required=False)
                else:
                    field = f
                if getattr(field, 'requires_distinct', False):
                    self.use_distinct = True
                self.fields[f] = field
Пример #12
0
 def __init__(self, foirequest, *args, **kwargs):
     super(FoiRequestStatusForm, self).__init__(*args, **kwargs)
     self.fields['refusal_reason'] = forms.ChoiceField(
         label=_("Refusal Reason"),
         choices=[('', _('No or other reason given'))] +
         foirequest.law.get_refusal_reason_choices(),
         required=False,
         help_text=
         _('When you are (partially) denied access to information, the Public Body should always state the reason.'
           ))
Пример #13
0
class FoiRequestStatusForm(forms.Form):
    def __init__(self, foirequest, *args, **kwargs):
        super(FoiRequestStatusForm, self).__init__(*args, **kwargs)
        self.fields['refusal_reason'] = forms.ChoiceField(
            label=_("Refusal Reason"),
            choices=[('', _('No or other reason given'))] +
            foirequest.law.get_refusal_reason_choices(),
            required=False,
            help_text=
            _('When you are (partially) denied access to information, the Public Body should always state the reason.'
              ))

    status = forms.ChoiceField(
        label=_("Status"),
        # widget=forms.RadioSelect,
        choices=[('', '-------')] +
        map(lambda x: (x[0], x[1]), FoiRequest.USER_SET_CHOICES),
        help_text=_('In what kind of state is this request?'))
    redirected = forms.IntegerField(
        label=_("Redirected to"),
        required=False,
        widget=PublicBodySelect,
        help_text=
        _('If your message is redirected to a different Public Body, please specify the new Public Body'
          ))
    if payment_possible:
        costs = forms.FloatField(
            label=_("Costs"),
            required=False,
            min_value=0.0,
            localize=True,
            widget=PriceInput(attrs={"size": "4"}),
            help_text=
            _('Please specify what the Public Body charges for the information.'
              ))

        def clean_costs(self):
            costs = self.cleaned_data['costs']
            if costs is None:
                return 0.0
            return costs

    def clean(self):
        pk = self.cleaned_data.get('redirected', None)
        status = self.cleaned_data.get('status', None)
        if status == "request_redirected":
            if pk is None:
                raise forms.ValidationError(
                    _("Provide the redirected public body!"))
            try:
                self._redirected_public_body = PublicBody.objects.get(id=pk)
            except PublicBody.DoesNotExist:
                raise forms.ValidationError(_("Invalid value"))
        return self.cleaned_data
Пример #14
0
class EventForm(forms.Form):

    name = forms.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'name your event'}))
    date = forms.DateTimeField(widget=forms.SplitDateTimeWidget)
    location = forms.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'address'}))
    city = forms.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'city'}))
    category = forms.ChoiceField(choices=CategoryOptions().CATEGORY_OPTIONS)
    description = forms.CharField(widget=forms.Textarea(
        attrs={'placeholder': 'don\'t be shy - tell us about it some more'}))
    budget = forms.IntegerField()
    max_people = forms.IntegerField()
    is_vegan = forms.BooleanField(required=False)
    is_kosher = forms.BooleanField(required=False)
    is_vegeterian = forms.BooleanField(required=False)
    rsvp = forms.ChoiceField(widget=forms.RadioSelect,
                             choices=RsvpOptions().RSVP_OPTIONS)
    picture = forms.ImageField()
Пример #15
0
class AllFieldsForm(forms.Form):
    boolean = forms.BooleanField()
    char = forms.CharField(max_length=50)
    choices = forms.ChoiceField(choices=ALPHA_CHOICES)
    date = forms.DateField()
    datetime = forms.DateTimeField()
    decimal = forms.DecimalField(decimal_places=2, max_digits=4)
    email = forms.EmailField()
    file_field = forms.FileField()
    file_path = forms.FilePathField(path='uploads/')
    float_field = forms.FloatField()
    generic_ip_address = forms.GenericIPAddressField()
    image = forms.ImageField()
    integer = forms.IntegerField()
    ip_address = forms.IPAddressField()
    multiple_choices = forms.MultipleChoiceField(choices=ALPHA_CHOICES)
    null_boolean = forms.NullBooleanField()
    regex_field = forms.RegexField(regex='^\w+$', js_regex='^[a-zA-Z]+$')
    slug = forms.SlugField()
    split_datetime = forms.SplitDateTimeField()
    time = forms.TimeField()
    typed_choices = forms.TypedChoiceField(choices=NUMERIC_CHOICES, coerce=int)
    typed_multiple_choices = forms.TypedMultipleChoiceField(
        choices=NUMERIC_CHOICES, coerce=int)
    url = forms.URLField()

    # GIS fields.
    if gis_forms:
        osm_point = gis.PointField(
            widget=mixin(gis.PointWidget, gis.BaseOsmWidget))
        osm_multipoint = gis.MultiPointField(
            widget=mixin(gis.MultiPointWidget, gis.BaseOsmWidget))
        osm_linestring = gis.LineStringField(
            widget=mixin(gis.LineStringWidget, gis.BaseOsmWidget))
        osm_multilinestring = gis.MultiLineStringField(
            widget=mixin(gis.MultiLineStringWidget, gis.BaseOsmWidget))
        osm_polygon = gis.PolygonField(
            widget=mixin(gis.PolygonWidget, gis.BaseOsmWidget))
        osm_multipolygon = gis.MultiPolygonField(
            widget=mixin(gis.MultiPolygonWidget, gis.BaseOsmWidget))

        gmap_point = gis.PointField(
            widget=mixin(gis.PointWidget, BaseGMapWidget))
        gmap_multipoint = gis.MultiPointField(
            widget=mixin(gis.MultiPointWidget, BaseGMapWidget))
        gmap_linestring = gis.LineStringField(
            widget=mixin(gis.LineStringWidget, BaseGMapWidget))
        gmap_multilinestring = gis.MultiLineStringField(
            widget=mixin(gis.MultiLineStringWidget, BaseGMapWidget))
        gmap_polygon = gis.PolygonField(
            widget=mixin(gis.PolygonWidget, BaseGMapWidget))
        gmap_multipolygon = gis.MultiPolygonField(
            widget=mixin(gis.MultiPolygonWidget, BaseGMapWidget))
Пример #16
0
 def __init__(self, *args, **kwargs):
     selected_plan_type = kwargs.pop('selected_plan_type')
     super(PlanForm, self).__init__(*args, **kwargs)
     if selected_plan_type == 'basic' or selected_plan_type == 'supporter':
         monthly_plan = settings.SUBSCRIPTION_PLANS[selected_plan_type][
             'monthly']
         plans = [(monthly_plan.get('stripe_plan_id'), monthly_plan)]
     else:
         yearly_plan = settings.SUBSCRIPTION_PLANS[selected_plan_type][
             'yearly']
         plans = [(yearly_plan.get('stripe_plan_id'), yearly_plan)]
     self.fields['plan'] = forms.ChoiceField(choices=plans)
 def field_hook(self):
     self.prior_version = None
     if self.instance is not None:
         increment_choices = [
             ("major", "save as new version"),
         ]
         if self.instance.status.DRAFT:
             increment_choices += [("inplace", "save in place")]
         self.fields["increment"] = forms.ChoiceField(
             choices=increment_choices)
     else:
         self.fields["suite"] = ccforms.ModelChoiceField(
             required=False, choice_attrs=product_id_attrs)
Пример #18
0
class ContactForm(forms.Form):

    name = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    subject = forms.CharField(required=forms.Textarea)

    # http://stackoverflow.com/questions/1694447/how-to-set-an-event-handler-in-a-django-form-input-field
    # https://chriskief.com/2012/12/16/override-django-form-is_valid/
    # http://stackoverflow.com/questions/30424394/django-forms-how-to-override-field-validation
    # overriding field validation

    # Creating drop-down list
    sales = "Sales"
    marketing = "Marketing"
    hr = "Recruitment"
    customer = "customers"
    it = "IT"
    other = "Other/Not Specified"

    dep_choices = {(sales, 'Sales'), (marketing, 'Marketing'),
                   (hr, 'Recruitment'), (it, 'IT'), (customer, 'Customers'),
                   (other, 'Other/Not Specified')}

    # choice field would be tracked
    # http://stackoverflow.com/questions/1694447/how-to-set-an-event-handler-in-a-django-form-input-field
    # http://stackoverflow.com/questions/1355150/django-when-saving-how-can-you-check-if-a-field-has-changed
    # triggering changes inside current contact form instance

    # from experiments I found that 'attrs' below executes pure javascript
    # so I just used javascript to update image
    department = forms.ChoiceField(
        choices=dep_choices,
        # widget=forms.Select(attrs={'onchange': "alert(this.value)"}))
        widget=forms.Select(attrs={'onchange': 'changepic(this.value)'}))

    # set initial state
    department.initial = {'other', 'Other/Not Specified'}

    # http://stackoverflow.com/questions/16076420/django-dropdownlist-onchange-submission

    message = forms.CharField(widget=forms.Textarea(
        attrs={'style': 'resize:allow;'}))

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.add_input(Submit('submit', 'Submit'))
        # self.initial['department'] = ... # possible variant here # http://herself.movielady.net/2012/12/15/initial-value-in-djangos-admin-for-a-choice-field/
        super(ContactForm, self).__init__(*args, **kwargs)
Пример #19
0
class ArtistInfoForm(forms.ModelForm):
    state = USStateField(widget=floppyforms.Select(choices=STATE_CHOICES_WITH_EMPTY), required=False)
    country = floppyforms.ChoiceField(choices=COUNTRIES_WITH_EMPTY)
    payout_method = forms.ChoiceField(
        choices=User.PAYOUT_CHOICES,
        widget=forms.RadioSelect()
    )
    paypal_email_again = floppyforms.EmailField(required=False)

    class Meta:
        fields = ('first_name', 'last_name', 'address_1', 'address_2', 'city', 'zip', 'state', 'country',
                  'payout_method', 'paypal_email', 'paypal_email_again', 'taxpayer_id')
        model = User

    def __init__(self, *args, **kwargs):
        super(ArtistInfoForm, self).__init__(*args, **kwargs)
        for field in self.Meta.fields:
            self.fields[field].widget.attrs['class'] = 'form-control'
        self.fields['state'].widget.attrs['class'] = 'form-control selectpicker'
        self.fields['country'].widget.attrs['class'] = 'form-control selectpicker'
        # default to US if nothing is set, initial not working as the form is bound
        if not self.initial['country']:
            self.initial['country'] = 'US'

    def clean(self):
        cleaned_data = super(ArtistInfoForm, self).clean()
        if cleaned_data.get('payout_method') == User.PAYOUT_CHOICES.PayPal:
            msg = u"This field is required."
            if not cleaned_data.get('paypal_email'):
                self.add_error('paypal_email', msg)
            if not cleaned_data.get('paypal_email_again'):
                self.add_error('paypal_email_again', msg)
            if cleaned_data.get('paypal_email') != cleaned_data.get('paypal_email_again'):
                raise forms.ValidationError(u'The two email addresses must match.')

        if cleaned_data.get('country') == 'US':
            state = cleaned_data.get('state')
            if not state:
                self.add_error('state', 'You must select a valid US state or territory.')
            taxpayer_id = cleaned_data.get('taxpayer_id')
            if not taxpayer_id:
                self.add_error('taxpayer_id', 'You must enter a valid taxpayer ID as a US citizen.')
            self.fields['state'].clean(state)
            self.fields['taxpayer_id'].clean(state)
        else:
            cleaned_data['state'] = ''
            cleaned_data['taxpayer_id'] = ''
        return cleaned_data
Пример #20
0
    def __init__(self, list_of_laws, default_law, hidden, *args, **kwargs):
        super(RequestForm, self).__init__(*args, **kwargs)
        self.list_of_laws = list_of_laws
        self.indexed_laws = dict([(l.pk, l) for l in self.list_of_laws])
        self.default_law = default_law

        self.fields["public_body"].widget.set_initial_jurisdiction(
            kwargs.get('initial', {}).pop('jurisdiction', None))
        self.fields["public_body"].widget.set_initial_search(
            kwargs.get('initial', {}).pop('public_body_search', None))
        self.fields["law"] = forms.ChoiceField(
            label=_("Information Law"),
            required=False,
            widget=forms.Select if not hidden else forms.HiddenInput,
            initial=default_law.pk,
            choices=((l.pk, l.name) for l in list_of_laws))
Пример #21
0
    def get_table_form(self, page_items):
        order_form = {}

        # Build choices list
        choices = []
        for i in range(0, len(page_items)):
           choices.append([str(i), i + 1])

        # Build selectors list
        position = 0
        for item in page_items:
            order_form['pos_' + str(item.pk)] = forms.ChoiceField(choices=choices, initial=str(position))
            position += 1

        # Turn dict into object
        return type('OrderWarningLevelsForm', (Form,), order_form)
Пример #22
0
class OrgSearch(forms.Form):
    areas = Area.objects.filter(
        parent_rels__parent__label=settings.REGION_LABEL).order_by('reference')
    org_type = forms.ChoiceField(choices=ORG_TYPE_CHOICES, required=False)
    sector = forms.ModelChoiceField(
        queryset=ActivityNomenclature.objects.filter(level=0),
        empty_label=u'Secteur d\'activité',
        required=False)
    area_1 = AreaModelChoiceField(queryset=areas,
                                  empty_label=u'Territoire',
                                  required=False)

    def __init__(self, *args, **kwargs):
        super(OrgSearch, self).__init__(*args, **kwargs)
        for field in self.fields.itervalues():
            field.widget.attrs['class'] = 'form-control'
Пример #23
0
    def make_posts_form(self):
        self.posts_form = None
        list_choices = self.posts_actions();
        if (not self.request.user.is_authenticated()
            or not list_choices):
            return

        form_fields = {}
        form_fields['list_action'] = forms.ChoiceField(choices=list_choices)
        list_choices = []
        for item in self.posts:
            list_choices.append((item.pk, None))
        if not list_choices:
            return
        form_fields['list_items'] = forms.MultipleChoiceField(choices=list_choices, widget=forms.CheckboxSelectMultiple)
        self.posts_form = type('PostsViewForm', (Form,), form_fields)
Пример #24
0
def make_form(data):
    """Take Python data and return a django.forms.Form."""
    form_fields = {}
    for i, (tag, row) in enumerate(data):
        if isinstance(row, Choice):
            form_fields[tag] = forms.ChoiceField(
                [(i, x) for i, x in enumerate(row.choices)],
                label=row.question,
                widget=forms.RadioSelect,
                required=False)
        else:
            form_fields[tag] = row.field(label=row.question,
                                         required=False,
                                         widget=row.widget)

    Form = type('DynamicSurveyForm', (forms.Form, ), form_fields)
    return Form
Пример #25
0
 def get_actions_form(self, page_items):
     """
     Build a form object with list of all items actions
     """
     if not self.actions:
         return None  # Dont build form
     form_fields = {}
     list_choices = []
     for action in self.actions:
         list_choices.append((action[0], action[1]))
     form_fields['list_action'] = forms.ChoiceField(choices=list_choices)
     list_choices = []
     for item in page_items:
         list_choices.append((item.pk, None))
     form_fields['list_items'] = forms.MultipleChoiceField(
         choices=list_choices, widget=forms.CheckboxSelectMultiple)
     return type('AdminListForm', (Form, ), form_fields)
Пример #26
0
 def __init__(self, queryset, *args, **kwargs):
     super(PublicBodySuggestionsForm, self).__init__(*args, **kwargs)
     self.fields['suggestion'] = forms.ChoiceField(
         label=_("Suggestions"),
         widget=forms.RadioSelect,
         choices=
         ((s.public_body.id,
           mark_safe(
               '''%(name)s - <a class="info-link" href="%(url)s">%(link)s</a><br/>
             <span class="help">%(reason)s</span>''' % {
                   "name": escape(s.public_body.name),
                   "url": s.public_body.get_absolute_url(),
                   "link": _("More Info"),
                   "reason": _("Reason for this suggestion: %(reason)s") % {
                       "reason": s.reason
                   }
               })) for s in queryset))
Пример #27
0
class ParamRowForm(forms.Form):
    """Just a single obs row."""
    obs_parameter = forms.ChoiceField(
        choices=[('', 'Select one')] + [
            (p, p) for p in Parameter.objects.all().values_list(
                'name', flat=True)
        ] + [('__NEW__', 'Add new...')]
    )
    new_parameter = forms.CharField(required=False)

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.disable_csrf = True
        self.helper.layout = Layout(
            get_new_obs_row(kwargs.pop('row_id')),
        )
        super(ParamRowForm, self).__init__(*args, **kwargs)
Пример #28
0
class UndoReadForm(forms.Form):
    action = forms.ChoiceField(
        choices=(('undo-read', 'undo-read'), ),
        widget=forms.HiddenInput,
        initial='undo-read',
    )
    pks = forms.CharField(widget=forms.HiddenInput)

    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(UndoReadForm, self).__init__(*args, **kwargs)

    def clean_pks(self):
        return json.loads(self.cleaned_data['pks'])

    def save(self):
        self.user.entries.filter(pk__in=self.cleaned_data['pks']).update(
            read=False)
        return len(self.cleaned_data['pks'])
Пример #29
0
class SubscriptionForm(forms.Form):
    subscribe = forms.BooleanField(label=_('Subscribe?'), required=False)
    name = forms.CharField(label=_('Name'), required=False)
    url = forms.URLField(label=_('URL'))
    category = forms.ChoiceField(label=_('Category'), required=False)

    def clean_url(self):
        url = self.cleaned_data['url']
        if (self.cleaned_data.get('subscribe', False)
                and self.user.feeds.filter(url=url).exists()):
            raise forms.ValidationError(
                _("You are already subscribed to this feed."))
        return url

    def clean_name(self):
        if (self.cleaned_data.get('subscribe', False)
                and not self.cleaned_data['name']):
            raise forms.ValidationError(_('This field is required.'))
        return self.cleaned_data['name']
Пример #30
0
    def __init__(self, list_of_laws, default_law, hidden, *args, **kwargs):
        super(RequestForm, self).__init__(*args, **kwargs)
        self.list_of_laws = list_of_laws
        self.indexed_laws = dict([(l.pk, l) for l in self.list_of_laws])
        self.default_law = default_law

        self.fields["public_body"].widget.set_initial_jurisdiction(
            kwargs.get('initial', {}).pop('jurisdiction', None))
        self.fields["law"] = forms.ChoiceField(
            label=_("Information Law"),
            required=False,
            widget=forms.RadioSelect if not hidden else forms.HiddenInput,
            initial=default_law.pk,
            choices=(
                (l.pk,
                 mark_safe(
                     '%(name)s<span class="lawinfo">%(description)s</span>' % {
                         "name": escape(l.name),
                         "description": l.formatted_description
                     })) for l in list_of_laws))