Ejemplo n.º 1
0
    def __init__(self, *args, **kwargs):

        error_messages = {
            'required': _("Debe indicar un numero de RIF"),
            'invalid': _("El valor indicado no es válido"),
            'incomplete': _("El número de RIF esta incompleto")
        }

        fields = (ChoiceField(choices=SHORT_TIPO_PERSONA),
                  CharField(max_length=8,
                            min_length=8), CharField(max_length=1,
                                                     min_length=1))

        label = _("R.I.F.:")

        super(RifField, self).__init__(error_messages=error_messages,
                                       fields=fields,
                                       label=label,
                                       require_all_fields=True,
                                       *args,
                                       **kwargs)
Ejemplo n.º 2
0
class LinkCreate(Form):

    site = ChoiceField(choices=SITE_CHOICES, label=_("SITE"), required=True)
    profile = CharField(max_length=1024, label=_("URL"), required=True)

    def __init__(self, *args, **kwargs):
        self.account = kwargs.pop("account")
        self.team = kwargs.pop("team")
        super(LinkCreate, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(LinkCreate, self).clean()
        profile = self.cleaned_data["profile"]
        site = self.cleaned_data["site"]
        if control.site_link_exists(self.team, site):
            raise ValidationError(_("ERROR_LINK_PROFILE_FOR_SITE_EXISTS"))
        if not link_control.valid_profile_format(profile, site):
            raise ValidationError(_("ERROR_BAD_PROFILE_FORMAT"))
        if not control.can_create_link(self.account, self.team, site, profile):
            raise ValidationError(_("ERROR_CANNOT_CREATE_LINK"))
        return cleaned_data
Ejemplo n.º 3
0
class TestSearchForm(Form):
    # TODO: Create a field for ModelChoiceField
    STATUS_CHOICES = [('', 'All'), (True, 'Active'), (False, 'Inactive')]

    field1 = CharField()
    field2 = TextInput()
    field3 = ChoiceField(choices=STATUS_CHOICES)
    field4 = BooleanField()
    field5 = DateField()
    field6 = DateTimeField()
    field7 = FloatField()
    field8 = DecimalField()
    field9 = IntegerField()

    field90 = CharField()
    field91 = CharField()

    def __init__(self, *args, **kwargs):
        super(TestSearchForm, self).__init__(*args, **kwargs)
        self.fields['field90'].label = "Date Start"
        self.fields['field91'].label = "Date End"
Ejemplo n.º 4
0
    def __init__(self, *args, **kwargs):
        super(CustomerAdminForm, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            self.owners = self.instance.get_owners()
            self.support_users = self.instance.get_support_users()
            self.fields['owners'].initial = self.owners
            self.fields['support_users'].initial = self.support_users
        else:
            self.owners = User.objects.none()
            self.support_users = User.objects.none()
        self.fields[
            'agreement_number'].initial = models.get_next_agreement_number()

        textarea_attrs = {'cols': '40', 'rows': '4'}
        self.fields['contact_details'].widget.attrs = textarea_attrs
        self.fields['access_subnets'].widget.attrs = textarea_attrs
        type_choices = ['']
        type_choices.extend(settings.WALDUR_CORE['COMPANY_TYPES'])
        self.fields['type'] = ChoiceField(required=False,
                                          choices=[(t, t)
                                                   for t in type_choices])
Ejemplo n.º 5
0
class AudioConfig(Form):
    audio_keep_original_file = BooleanField(
        required=False,
        label=_('Keep original files'),
        help_text=_(
            "Should original files be kept on the server after they're "
            "transcoded."))
    audio_quality = ChoiceField(
        choices=[('256k', '256 kb/s'), ('128k', '128 kb/s'),
                 ('96k', '96 kb/s'), ('64k', '64 kb/s'), ('32k', '32 kb/s'),
                 ('16k', '16 kb/s')],
        label=_('Transcoded audio quality'),
        help_text=_('This settings affects both audio sources and snippets.'))
    audio_staff_size_limit = IntegerField(max_value=2000,
                                          min_value=10,
                                          label=_('Staff size limit'),
                                          help_text=_('In megabytes'))
    audio_user_size_limit = IntegerField(max_value=2000,
                                         min_value=10,
                                         label=_('User size limit'),
                                         help_text=_('In megabytes'))
Ejemplo n.º 6
0
    def __init__(self, user, *args, **kwargs):
        if 'instance' in kwargs:
            self.instance = kwargs['instance']
            del kwargs['instance']

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

        self.fields['status'].queryset = Object.filter_permitted(
            user, TaskStatus.objects, mode='x')
        self.fields['status'].label = _("Mark as")
        self.fields['project'].queryset = Object.filter_permitted(
            user, Project.objects, mode='x')
        self.fields['project'].label = _("Move to Project")
        self.fields['milestone'].queryset = Object.filter_permitted(
            user, Milestone.objects, mode='x')
        self.fields['milestone'].label = _("Move to Milestone")
        self.fields['delete'] = ChoiceField(
            label=_("Delete"),
            choices=(('', '-----'), ('delete', _('Delete Completely')),
                     ('trash', _('Move to Trash'))),
            required=False)
Ejemplo n.º 7
0
class WorkoutScheduleDownloadForm(Form):
    """
    Form for the workout schedule download
    """
    pdf_type = ChoiceField(
        label=gettext_lazy("Type"),
        choices=(("log", gettext_lazy("Log")),
                 ("table", gettext_lazy("Table")))
    )
    images = BooleanField(label=gettext_lazy("with images"),
                          required=False)
    comments = BooleanField(label=gettext_lazy("with comments"),
                            required=False)

    def __init__(self):
        super(WorkoutScheduleDownloadForm, self).__init__()
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.add_input(Submit('submit', _("Download"),
                                     css_class='btn-success btn-block',
                                     css_id="download-pdf-button-schedule"))
Ejemplo n.º 8
0
class SignUpForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('email', 'first_name', 'last_name', 'username')

    user_type = ChoiceField(choices=choises)
    address = CharField(max_length=500)
    picture = CharField(max_length=500)
    accept_terms = BooleanField()

    def save(self, commit=True):
        user = super().save(commit)
        profile = CustomUser(
            user_type=self.cleaned_data.get('user_type'),
            address=self.cleaned_data.get('address'),
            picture=self.cleaned_data.get('picture'),
            accept_terms=self.cleaned_data.get('accept_terms'),
        )
        if commit:
            profile.save()
        return user
Ejemplo n.º 9
0
class EventForm(ModelForm):

    GENRES_CHOICES = (
        ('Other', 'Other'),
        ('Rock', 'Rock'),
        ('Pop', 'Pop'),
        ('Jazz', 'Jazz'),
    )

    date = DateField(input_formats=['%d/%m/%Y'],
                     widget=DateInput(format='%d/%m/%Y'))
    musicgenres = ChoiceField(widget=RadioSelect,
                              choices=GENRES_CHOICES,
                              initial='Other')

    class Meta:
        model = Event
        fields = [
            'name', 'location', 'date', 'time', 'imageurl', 'description',
            'musicgenres'
        ]
Ejemplo n.º 10
0
class FilterPending(Form):

    searchtext = CharField(
        label=_("SEARCH_TEXT"),
        required=False,
        widget=TextInput(attrs={
            'class': 'form-control',
            'placeholder': _('SEARCH_TITLE_AND_TAGS')
        }))

    ordering = ChoiceField(choices=[
        ('REWARD_HIGHEST', _('REWARD_HIGHEST')),
        ('REWARD_LOWEST', _('REWARD_LOWEST')),
        ('DEADLINE_NEAREST', _('DEADLINE_NEAREST')),
        ('DEADLINE_FARTHEST', _('DEADLINE_FARTHEST')),
        ('NEWEST_BOUNTY', _('NEWEST_BOUNTY')),
        ('OLDEST_BOUNTY', _('OLDEST_BOUNTY')),
    ],
                           label=_("ORDERING"),
                           initial="REWARD_HIGHEST",
                           widget=Select(attrs={'class': 'form-control'}))
Ejemplo n.º 11
0
class PickStateForm(CrispyForm):

    states = ChoiceField(label='Saved reports', choices=(('', ''), ))

    def __init__(self, *args, user=None, table_id=None, **kwargs):
        kwargs['no_buttons'] = True
        super().__init__(*args, **kwargs)
        self.fields['states'].widget = Select2(
            attrs={'id': table_id + '_state_id'})
        reports = (SavedState.objects.order_by('name').filter(
            Q(table_id=table_id),
            Q(public=True) | Q(user_id=user.id)).values_list(
                'id', 'name', 'public'))
        self.fields['states'].choices = [
            ('', ''),
            ('Private Reports', [(report_id, name)
                                 for report_id, name, public in reports
                                 if not public])
        ] + [('Public reports', [
            (report_id, name) for report_id, name, public in reports if public
        ])]
Ejemplo n.º 12
0
class ReportConfigurationForm(ModelForm):
    target_model = MyModelChoiceField(queryset=ContentType.objects.order_by(
        'app_label', 'name'),
                                      required=False)
    report_class = ChoiceField()

    def __init__(self, *args, **kwargs):
        from ereports.engine.registry import registry
        super(ReportConfigurationForm, self).__init__(*args, **kwargs)

        self.fields['report_class'].choices = registry.choices()

    def clean_groupby(self):
        value = self.cleaned_data['groupby']
        for line in value.splitlines():
            if len(line.split(';')) != 2:
                raise ValidationError('wqww')
        return value

    class Meta:
        model = ReportConfiguration
Ejemplo n.º 13
0
class CompaniaRolForm(Form):

    compania = ChoiceField(widget=Select(attrs={'class': 'select2'}))

    def __init__(self, *args, **kargs):
        super(CompaniaRolForm, self).__init__(*args, **kargs)
        self.fields['compania'].choices = self.get_Companias()

    def get_Companias(self):

        valores = [('', '-------')]

        companias = VIEW_COMPANIAS.objects.using('jde_p').all()

        for compania in companias:

            valores.append((
                str(compania.comp_code) + ':' + compania.comp_desc,
                str(int(compania.comp_code)) + ' - ' + compania.comp_desc,
            ))
        return valores
    def create(self, field):
        if field.single_select_flag:
            for opt in field.options:
                if opt['text'] == field.value:
                    field.value = opt['val']

            return ChoiceField(choices=self._create_choices(field), required=field.is_required(),
                               label=field.label,
                               initial=field.value, help_text=field.instruction)
        else:
            field_values = []
            if field.value is not None:
                field_labels = field.value.split(',')
                for opt in field.options:
                    if opt['text'] in field_labels:
                        field_values.append(opt['val'])

        return forms.MultipleChoiceField(label=field.label, widget=forms.CheckboxSelectMultiple,
                                         choices=self._create_choices(field),
                                         initial=field_values, required=field.is_required(),
                                         help_text=field.instruction)
Ejemplo n.º 15
0
class ReviewForm(ModelForm):
    # rating = CharField(label='Rating', widget=TextInput(attrs={'min': 1, 'max': '5', 'type': 'number'}))
    CHOICES = [(str(x), str(x)) for x in range(0, 6)]
    # CHOICES = [('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5')]
    rating = ChoiceField(label="Evaluation",
                         widget=RadioSelect,
                         choices=CHOICES)

    class Meta:
        model = Review
        fields = ["headline", "rating", "body"]

        labels = {
            "headline": "Titre de la revue",
            "rating": "Evaluation",
            "body": "Revue",
        }

        widgets = {
            "body": Textarea(attrs={"class": "review__textarea"}),
        }
Ejemplo n.º 16
0
class SearchForm(Form):
	q = CharField(label='جست‌وجو', widget=TextInput(attrs={'placeholder': 'مثال: دانشگاه صنعتی شریف', 'class': 'mainSearch'}),
				  max_length=100)

	filter_by = ChoiceField(label='میان', initial='all',
							widget=RadioSelect,
							choices=(('all', 'همه'), ('profs', 'اساتید'),
									 ('deps', 'دانشکده‌ها'),
									 ('unis', 'دانشگاه‌ها')))

	def __init__(self, *args, **kwargs):
		super(Form, self).__init__(*args, **kwargs)
		self.helper = FormHelper()
		self.helper.form_method = 'GET'
		self.helper.form_class = 'no-asterisk'
		self.helper.form_action = reverse_lazy('entities:search_results')
		self.helper.disable_csrf = True
		self.helper.layout = Layout(
			Div('q'),
			Div(InlineRadios('filter_by'))
		)
Ejemplo n.º 17
0
class PhoneVerificationForm(Form):
    country_code = CharField(max_length=3, widget=PhoneCountryCodeWidget())
    phone_number = CharField(max_length=12)
    via = ChoiceField(choices=[('sms', 'Text me (SMS)'), ('call', 'Call me')],
                      widget=CustomRadioSelectWidget())

    def clean_country_code(self):
        country_code = self.cleaned_data['country_code']
        if not country_code.startswith('+'):
            country_code = '+' + country_code
        return country_code

    def clean(self):
        data = self.cleaned_data
        phone_number = data['country_code'] + data['phone_number']
        try:
            phone_number = phonenumbers.parse(phone_number, None)
            if not phonenumbers.is_valid_number(phone_number):
                self.add_error('phone_number', 'Invalid phone number')
        except phonenumbers.NumberParseException as e:
            self.add_error('phone_number', e)
Ejemplo n.º 18
0
class ExportForm(Form):
    title = CharField(required=False,
                      widget=TextInput(attrs={
                          'class': 'form-control',
                          'disabled': ''
                      }))
    per_participant = BooleanField(initial=True, required=False)
    per_questionnaire = BooleanField(initial=True, required=False)

    questionnaire_entrance_selected = []

    # patient_fields_selected = MultipleChoiceField(required=True,
    #                                               widget=CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES)

    headings = ChoiceField(widget=RadioSelect(), choices=HEADINGS_CHOICES)
    responses = MultipleChoiceField(
        widget=CheckboxSelectMultiple(
            attrs={'data-error': _('Response must be selected')}),
        choices=RESPONSES_CHOICES,
    )

    #
    # questionnaire_entrance_fields_selected = []
    #
    # patient_fields_selected = []
    #
    # diagnosis_fields_selected = []
    #
    # per_questionnaire_field = True

    def clean(self):
        cleaned_data = super(ExportForm, self).clean()
        participant_field = cleaned_data.get("per_participant")
        questionnaire_field = cleaned_data.get("per_questionnaire")

        if not (participant_field or questionnaire_field):
            self.add_error(
                'per_participant',
                _("Either one or both Per participant/Per questionnaire must be set."
                  ))
Ejemplo n.º 19
0
class CompleteDelivery(Form):
    delivery_date = DateField(required=True,
                              initial=timezone.now(),
                              widget=DateInput(attrs={
                                  'class': 'form-control',
                                  'type': 'date'
                              }))
    delivery_time = TimeField(required=True,
                              initial=timezone.now(),
                              widget=TimeInput(attrs={
                                  'class': 'form-control',
                                  'type': 'time'
                              }))
    delivery_type = ChoiceField(required=True,
                                choices=DELIVERY_TYPES,
                                widget=Select(attrs={'class': 'form-control'}))
    newborn_weight_lbs = IntegerField(
        min_value=0,
        required=True,
        widget=TextInput(attrs={'class': 'form-control'}))
    newborn_weight_oz = IntegerField(
        min_value=0,
        max_value=16,
        required=True,
        widget=TextInput(attrs={'class': 'form-control'}))
    live_birth = BooleanField(required=False)

    def clean_delivery_date(self):
        data = self.cleaned_data['delivery_date']
        if data > timezone.now().date():
            raise forms.ValidationError(
                "Cannot set delivery date in the future")
        return data

    def clean_delivery_time(self):
        data = self.cleaned_data['delivery_time']
        if data > timezone.now().time():
            raise forms.ValidationError(
                "Cannot set delivery time in the future")
        return data
Ejemplo n.º 20
0
    def __init__(self,
                 project,
                 data,
                 is_datasender,
                 datasender_name,
                 reporter_id,
                 reporter_name,
                 enable_datasender_edit,
                 initial=None):
        super(BaseSubmissionForm, self).__init__(data, initial=initial)
        self.form_model = project
        self.fields['form_code'] = CharField(widget=HiddenInput,
                                             initial=project.form_code)
        self.is_datasender = is_datasender
        if not is_datasender:

            default_choice = [("", gettext("Choose Data Sender"))]
            list_ds = (as_choices(project.get_data_senders(project._dbm)))
            list_sorted = sorted(list_ds, key=itemgetter(1))
            default_choice.extend(list_sorted)
            if data:
                error_message = {
                    'invalid_choice':
                    _("The Data Sender %s (%s) is not linked to your Questionnaire."
                      ) % (datasender_name, data.get("dsid"))
                }
            else:
                error_message = None

            if enable_datasender_edit:
                required = data is not None and data.has_key("on_behalf_of")
                widget = None if len(list_sorted) else Select(
                    attrs={'disabled': 'disabled'})
                self.fields['dsid'] = ChoiceField(label=_(
                    'I want to submit this data on behalf of a registered Data Sender'
                ),
                                                  choices=default_choice,
                                                  required=required,
                                                  error_messages=error_message,
                                                  widget=widget)
Ejemplo n.º 21
0
class RequestDomainNameForm(Form):

    # Request info
    priority = ChoiceField(label='Request Priority')
    requestor_username = CharField(
        label='Requestor Alias',
        max_length=25,
        error_messages={'required': 'A valid requestor is required'})

    # Domain Name info
    domain_names = DomainNameListFormFiled(
        label='Domain Name(s)',
        widget=Textarea,
        error_messages={
            'required': 'At least one domain name must be entered.'
        })

    def __init__(self, *args, **kwargs):
        super(RequestDomainNameForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.html5_required = True

        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-10'

        self.helper.layout = Layout(
            Fieldset(
                'Request a Domain Name (CNAME)',
                HTML(IP_REQUEST_INFORMATION),
                Field('priority', placeholder=self.fields['priority'].label),
                Field('requestor_username',
                      placeholder=self.fields['requestor_username'].label),
                Field('domain_names',
                      placeholder=self.fields['domain_names'].label),
            ), FormActions(Submit('submit', 'Submit'), ))

        self.fields["priority"].choices = PRIORITY_CHOICES
Ejemplo n.º 22
0
class RegisterForm(Form):
    username = CharField(
        label="Username",
        max_length=100,
        required=True,
    )

    password = CharField(
        label="Password",
        max_length=100,
        required=True,
        widget=PasswordInput,
    )

    group = ChoiceField(
        label="Group",
        choices=(
            ('Contributor', 'Contributor'),
            ('Project Manager', 'Project Manager'),
        ),
        required=True,
    )

    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.form_method = 'POST'
        self.helper.form_action = '/charts/account/register/'
        self.helper.label_class = 'col-xs-12 col-md-1'
        self.helper.field_class = 'col-xs-12 col-md-5'
        self.helper.layout = Layout(
            'username', 'password', 'group',
            StrictButton('Register',
                         css_class='btn-primary col-md-offset-1',
                         type='submit'),
            HTML(
                '<a href="/charts/" class="btn btn-default" role="button">Cancel</a>'
            ))
Ejemplo n.º 23
0
class JobLocationForm(forms.ModelForm):
    state = NoValidationChoiceField(choices=JobLocation.state_choices,
                                    widget=SelectWithOptionClasses())
    country = ChoiceField(choices=JobLocation.country_choices,
                          initial='United States')
    region = CharField(max_length=255, required=False)

    class Meta:
        fields = ('city', 'state', 'region', 'country', 'zipcode')
        excluded = ('guid', 'state_short', 'country_short')
        model = JobLocation

    def clean(self):
        cleaned_data = self.cleaned_data
        if (cleaned_data.get('country') not in ["United States", "Canada"]
                and not self.instance.pk):
            region = cleaned_data.get('region')
            if region:
                cleaned_data['state'] = region
            else:
                raise ValidationError('State or region is required.')
        return cleaned_data
Ejemplo n.º 24
0
    def __init__(self, *args, **kwargs):
        dim = kwargs.pop('dim', 1)
        choices = kwargs.pop('choices', None)

        if not isinstance(dim, (int, long)) or (dim < 1):
            raise ValidationError(self.error_messages['invalid_dim'])

        if not is_iterable(choices) or \
                any(not is_iterable(c) for c in choices) or \
                any(not isinstance(c[0], ureg.Unit) for c in choices):
            raise ValidationError(self.error_messages['invalid_choices'])

        if any(c[0].dimensionality != choices[0][0].dimensionality for c in choices):
            raise ValidationError(self.error_messages['different_units'])

        fields = [FloatField() for i in range(dim)] + [ChoiceField(choices=[(str(u), c) for u, c in choices])]

        kwargs.update({
            'widget': MultiQuantityWidget(dim=dim, choices=choices)
        })

        super(MultiQuantityFormField, self).__init__(fields, *args, **kwargs)
Ejemplo n.º 25
0
class BulkTimeUpdateForm(Form):
    ADD = 'add'
    SUBTRACT = 'subtract'
    CHOICES = ((ADD, 'Add'), (SUBTRACT, 'Subtract'))
    DIMENSIONS = ('days', 'seconds', 'minutes', 'hours', 'weeks')
    _selected_action = CharField(widget=MultipleHiddenInput)
    method = ChoiceField(choices=CHOICES)
    interval = CharField()

    def clean_interval(self):
        interval = self.cleaned_data['interval']
        dimensions_symbol = tuple(i[0] for i in self.DIMENSIONS)
        if not re.match(r'[\d{0}]'.format(''.join(dimensions_symbol)),
                        interval):
            raise ValidationError('Wrong format, support only {0}'.format(
                self.DIMENSIONS))
        kwargs = {}
        for symbol, dimension in zip(dimensions_symbol, self.DIMENSIONS):
            match = re.search(r'\d+{0}'.format(symbol), interval)
            if match:
                kwargs[dimension] = int(match.group()[:-1])
        return timedelta(**kwargs)
Ejemplo n.º 26
0
class Edit(Form):

    name = CharField(label=_("NAME"))
    active = BooleanField(label=_("ACTIVE"), initial=True, required=False)
    reserve = BooleanField(label=_("RESERVE"), initial=False, required=False)
    station = ModelChoiceField(label=_("STATION"), queryset=None, required=True)
    lockcode = CharField(label=_("LOCKCODE"))
    size = ChoiceField(choices=SIZE_CHOICES, label=_("SIZE"), initial="MEDIUM")
    lights = BooleanField(label=_("LIGHTS"), initial=False, required=False)
    description = CharField(label=_("DESCRIPTION"), widget=Textarea)

    def __init__(self, *args, **kwargs):
        self.bike = kwargs.pop("bike")
        self.account = kwargs.pop("account")
        super(Edit, self).__init__(*args, **kwargs)
        self.fields["name"].initial = self.bike.name
        self.fields["active"].initial = self.bike.active
        self.fields["reserve"].initial = self.bike.reserve
        self.fields["station"].queryset = self.bike.team.stations.filter(active=True)
        self.fields["station"].initial = self.bike.station
        self.fields["lockcode"].initial = self.bike.lockcode
        self.fields["size"].initial = self.bike.size
        self.fields["lights"].initial = self.bike.lights
        self.fields["description"].initial = self.bike.description

    def clean(self):
        cleaned_data = super(Edit, self).clean()
        station = cleaned_data.get("station")
        active = cleaned_data.get("active")

        if (not active and self.bike.active and
                not control.can_deactivate(self.account, self.bike)):
            raise ValidationError(_("ERROR_CANNOT_DEACTIVATE_BIKE_IN_USE"))

        if (station and station != self.bike.station and
                not control.can_change_station(self.account, self.bike, station)):
            raise ValidationError(_("ERROR_CANNOT_CHANGE_STATION_BIKE_IN_USE"))

        return cleaned_data
Ejemplo n.º 27
0
 def __init__(self,
              currency_widget=None,
              currency_choices=CURRENCY_CHOICES,
              choices=CURRENCY_CHOICES,
              max_value=None,
              min_value=None,
              max_digits=None,
              decimal_places=None,
              *args,
              **kwargs):
     if currency_choices != CURRENCY_CHOICES:
         warn('currency_choices will be deprecated in favor of choices',
              PendingDeprecationWarning)
         choices = currency_choices
     decimal_field = DecimalField(max_value, min_value, max_digits,
                                  decimal_places, *args, **kwargs)
     choice_field = ChoiceField(choices=currency_choices)
     self.widget = currency_widget if currency_widget else MoneyWidget(
         amount_widget=decimal_field.widget,
         currency_widget=choice_field.widget)
     fields = (decimal_field, choice_field)
     super(MoneyField, self).__init__(fields, *args, **kwargs)
Ejemplo n.º 28
0
class GenericEventScheduleForm(ModelForm):
    required_css_class = 'required'
    error_css_class = 'error'
    type = ChoiceField(choices=new_event_options,
                       help_text=event_help_texts['type'])
    e_description = CharField(widget=TinyMCE(attrs={
        'cols': 80,
        'rows': 20
    }),
                              label=event_labels['e_description'])

    class Meta:
        model = GenericEvent
        fields = [
            'e_title',
            'e_description',
            'duration',
            'type',
            'default_location',
        ]
        help_texts = event_help_texts
        labels = event_labels
Ejemplo n.º 29
0
class _TemplateBaseForm(BaseEditForm):
    status = ChoiceField(label=_('Status'), choices=())

    # class Meta:
    class Meta(BaseEditForm.Meta):
        model = get_template_base_model()
        # exclude = (*BaseEditForm.Meta.exclude, 'ct', 'status_id')

    def _build_status_field(self, billing_ct):
        meta = billing_ct.model_class()._meta
        status_field = self.fields['status']

        status_field.label = gettext('Status of {}').format(meta.verbose_name)
        status_field.choices = [(status.id, str(status))
                                for status in meta.get_field(
                                    'status').remote_field.model.objects.all()]

        return status_field

    def save(self, *args, **kwargs):
        self.instance.status_id = self.cleaned_data['status']
        return super().save(*args, **kwargs)
Ejemplo n.º 30
0
    def get_form_class(self):
        if not self.model:
            raise ImproperlyConfigured(
                'RAIChooseParentHandler needs to be bound to a model before '
                'the form class can be provided')
        self.compute_choices()
        opts = self.model._meta
        name = '{}{}ParentChooser'.format(opts.app_label, opts.model_name)
        page_choices = list(self.page_choices)
        page_choices.sort(key=lambda x: x.specific.title_de)
        print(page_choices)
        choices = ((choice.pk, choice.specific.title_de)
                   for choice in page_choices)

        return rai_form_factory(
            name, {
                'parent_page':
                ChoiceField(required=True,
                            label=self.label,
                            choices=choices,
                            widget=RAIRadioSelect)
            })