示例#1
0
class UserForm(forms.Form):
    age = forms.IntegerField(
        label="Tuổi",
        required=True
    )
    sex = forms.ModelChoiceField(
        queryset=Sex.objects.all(),
        label=u'Giới tính',
        empty_label=None
    )
    height = forms.DecimalField(
        label="Chiều cao",
        required=True,
        widget=forms.NumberInput(
            attrs={'placeholder': 'Đơn vị là cm'}
        )
    )
    weight = forms.DecimalField(
        label="Cân nặng",
        required=True,
        widget=forms.NumberInput(
            attrs={'placeholder': 'Đơn vị là kg'}
        )
    )
    activity_level = forms.ModelChoiceField(
        queryset=ActivityLevel.objects.all(),
        label=u'Mức độ hoạt động',
        empty_label=None,
    )

    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()

        self.helper.form_class = "form-horizontal"
        self.helper.form_method = 'post'
        self.helper.form_action = ''
        self.helper.html5_required = True
        self.helper.layout = Layout(
            'age',
            'height',
            'weight',
            InlineRadios('sex'),
            'activity_level',
        )
        self.helper.add_input(Submit('submit', 'Tư vấn'))
示例#2
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))
示例#3
0
class GradeFilterForm(TimeBasedForm):
    marking_period = forms.ModelMultipleChoiceField(required=False, queryset=MarkingPeriod.objects.all())

    filter_choices = (
        ("lt", "Less Than"),
        ("lte", "Less Than Equals"),
        ("gt", "Greater Than"),
        ("gte", "Greater Than Equals"),
    )

    grade = forms.CharField(max_length=5,
                            widget=forms.TextInput(attrs={'placeholder': 'Enter Grade Here'}),
                            required=False,
                            help_text="P counts as 100%, F counts as 0%",)
    grade_filter = forms.ChoiceField(choices=filter_choices)
    grade_times = StarOrIntField(max_length=2, required=False, initial="*", widget=forms.TextInput(attrs={'style':'width:20px;'}))
    final_grade = forms.CharField(max_length=5,
                            widget=forms.TextInput(attrs={'placeholder': 'Enter Grade Here'}),
                            required=False,
                            help_text="P counts as 100%, F counts as 0%",)
    final_grade_filter = forms.ChoiceField(choices=filter_choices)
    final_grade_times = StarOrIntField(max_length=2, required=False, initial="*", widget=forms.TextInput(attrs={'style':'width:20px;'}))

    gpa = forms.DecimalField(max_digits=5, decimal_places=2, required=False)
    gpa_equality =  forms.ChoiceField(choices=filter_choices)
    filter_year = forms.ModelMultipleChoiceField(required=False, queryset=GradeLevel.objects.all())
    in_individual_education_program = forms.BooleanField(required=False)
    #disc
    if 'ecwsp.discipline' in settings.INSTALLED_APPS:
        from ecwsp.discipline.models import DisciplineAction
        filter_disc_action = forms.ModelChoiceField(required=False, queryset=DisciplineAction.objects.all())
        filter_disc = forms.ChoiceField(choices=filter_choices, required=False)
        filter_disc_times = forms.CharField(max_length=2, required=False, widget=forms.TextInput(attrs={'style':'width:20px;'}))
        # Aggregated
        aggregate_disc = forms.ChoiceField(choices=filter_choices, required=False)
        aggregate_disc_times = forms.CharField(max_length=2, required=False, widget=forms.TextInput(attrs={'style':'width:20px;'}))
        aggregate_disc_major = forms.BooleanField(required=False)
    # Absences
    filter_attn = forms.ChoiceField(choices=filter_choices, required=False)
    filter_attn_times = forms.CharField(max_length=2, required=False, widget=forms.TextInput(attrs={'style':'width:20px;'}))
    # Tardies
    filter_tardy = forms.ChoiceField(choices=filter_choices, required=False)
    filter_tardy_times = forms.CharField(max_length=2, required=False, widget=forms.TextInput(attrs={'style':'width:20px;'}))
示例#4
0
class RegistrationForm(forms.Form):
    honeypot = forms.CharField(required=False, widget=forms.HiddenInput)
    firstname = forms.CharField(label=_(u'Your first name?'))
    lastname = forms.CharField(label=_(u'Your last name:'))
    username = forms.CharField(max_length=30)
    password = forms.CharField(
        widget=forms.PasswordInput,
        help_text=_(u'Make sure to use a secure password.'),
    )
    password2 = forms.CharField(label=_(u'Retype password'),
                                widget=forms.PasswordInput)
    age = forms.IntegerField(required=False)
    height = forms.DecimalField(localize=True, required=False)
    agree_to_terms = forms.BooleanField()

    def clean_honeypot(self):
        if self.cleaned_data.get('honeypot'):
            raise ValidationError(u'Haha, you trapped into the honeypot.')
        return self.cleaned_data['honeypot']

    def clean(self):
        if self.errors:
            raise ValidationError(u'Please correct the errors below.')
示例#5
0
 class RangeForm(forms.Form):
     range_ = forms.DecimalField(widget=forms.RangeInput)
示例#6
0
 class NumberForm(forms.Form):
     num = forms.DecimalField(widget=NumInput(attrs={'step': 12}))
示例#7
0
 class NumberForm(forms.Form):
     num = forms.DecimalField(widget=NumInput)
示例#8
0
 class NumberForm(forms.Form):
     num = forms.DecimalField(widget=forms.NumberInput(attrs={
         'min': 5,
         'max': 10
     }))
示例#9
0
 class NumberForm(forms.Form):
     num = forms.DecimalField()
示例#10
0
class SellOutfitForm(forms.Form):
    """
    First step of selling an outfit, including basic info of outfit and its pictures
    """
    name = forms.CharField(
        max_length=50,
        label=u'Name',
        widget=forms.TextInput(
            attrs={
                'placeholder': _(u"Give your outfit a cool name.")
            }
        ),
    )

    price = forms.DecimalField(
        required=True,
        widget = forms.TextInput(
            attrs={
                'placeholder': _(u"Price for all the pieces for sale in this outfit.")
            }
        )
    )
    description = forms.CharField(
        widget=forms.Textarea(
            attrs={
                'rows': 3,
                'placeholder':
                _(u"What inspired you? Where or when would you wear this outfit? Share your story!")
            }
        ),
        max_length=500,
        required=True,
    )

    def __init__(self, *args, **kwargs):
        if 'request' in kwargs:
            self.request = kwargs['request']
            del kwargs['request']
        else:
            raise Exception('Request was not passed in kwargs when initializing form SellOutfitForm')
        super(SellOutfitForm, self).__init__(*args, **kwargs)

    def clean(self):
        # need to make sure the seller uploaded pictures in the fileupload form
        outfit_pics = Picture.objects.filter(
            seller=self.request.user,
            type='o',
            outfit__isnull=True)

        if not outfit_pics:
            raise forms.ValidationError(u'Remember to upload one or more of your outfit photos!')

        # make sure primary photo was selected
        if outfit_pics.filter(is_primary=True).count() == 0:
            if outfit_pics.count() == 1:
                # if there is only one outfit picture, default this to primary
                for pic in outfit_pics:
                    pic.is_primary=True
                    pic.save()
            else:
                raise forms.ValidationError(make_primary_error_message)
        return self.cleaned_data
示例#11
0
class SellPieceForm(forms.ModelForm):
    """
    Second step of selling an outfit, including upload pictures of individual pieces to sell
    """
    #TODO: fix this so we don't need to do these one off definitons. Can use monkey patching to fix
    # This is needed for now to use HTML5 form to do client side validation
    price = forms.DecimalField(
        required=True
    )

    size = forms.CharField(
        required=True,
        widget = forms.TextInput(
            attrs={
                'placeholder': _(u"Enter 'N/A' if there is no size.")
            }
        )
    )

    brand = forms.CharField(
        required=True
    )

    description = forms.CharField(
        widget=forms.Textarea(
            attrs={
                'rows': 5,
                'placeholder':
                _(u"Any damages? Does the size run too small or too large?")
            }
        ),
        max_length=500,
        required=False,
    )

    CHOICES = ((1, 'Yes',), (0, 'No',))
    more_pieces = forms.ChoiceField(
        widget=forms.RadioSelect,
        choices=CHOICES,
        required=True,
        label=_(u"Are there more pieces from this outfit you'd like to sell?")
    )

    def __init__(self, *args, **kwargs):
        if 'request' in kwargs:
             self.request = kwargs['request']
             del kwargs['request']
        else:
            raise Exception('Request was not passed in kwargs when initializing form SellPieceForm')
        super(SellPieceForm, self).__init__(*args, **kwargs)

    def clean(self):
        # need to make sure the seller uploaded pictures in the fileupload form
        if self.request.session['check_for_sell_piece_pics']:
            # set this value back to False, so calls from FormWizards will not need to check again
            # for this instance of the form
            self.request.session['check_for_sell_piece_pics'] = False

            # use self.prefix as current step, minor hack :)
            piece_pics = Picture.objects.filter(
                seller=self.request.user,
                type='p',
                piece__isnull=True,
                piece_step=int(self.prefix))

            if not piece_pics:
                # throw an error to tell seller to upload pictures for outfit
                raise forms.ValidationError(_(u'Remember to upload one or more photos above!'))

            # make sure primary photo was selected
            if piece_pics.filter(is_primary=True).count() == 0:
                if piece_pics.count() == 1:
                    # if there is only one photo, just mark this as primary
                    for pic in piece_pics:
                        pic.is_primary = True
                        pic.save()
                else:
                    raise forms.ValidationError(make_primary_error_message)
        return self.cleaned_data

    class Meta:
        model = Piece
        fields = ['price', 'size', 'brand', 'category', 'condition', 'description']
示例#12
0
文件: forms.py 项目: xalegor/mymoney
class RatioForm(forms.Form):
    """
    Form to display bank transaction sums grouped by tags.
    """

    SINGLE_CREDIT = 'single_credit'
    SINGLE_DEBIT = 'single_debit'
    SUM_CREDIT = 'sum_credit'
    SUM_DEBIT = 'sum_debit'
    TYPES = (
        (ugettext_lazy('Sum'), (
            (SUM_DEBIT, ugettext_lazy('Expenses')),
            (SUM_CREDIT, ugettext_lazy('Income')),
        )),
        (ugettext_lazy('Single'), (
            (SINGLE_DEBIT, ugettext_lazy('Expenses')),
            (SINGLE_CREDIT, ugettext_lazy('Income')),
        )),
    )
    type = forms.ChoiceField(choices=TYPES, initial=SUM_DEBIT)

    CHART_DOUGHNUT = 'doughtnut'
    CHART_PIE = 'pie'
    CHART_POLAR = 'polar'
    CHART_TYPES = (
        (CHART_DOUGHNUT, ugettext_lazy('Doughnut')),
        (CHART_PIE, ugettext_lazy('Pie')),
        (CHART_POLAR, ugettext_lazy('Polar area')),
    )
    chart = forms.ChoiceField(
        choices=CHART_TYPES,
        initial=CHART_DOUGHNUT,
        required=False,
    )

    date_start = forms.DateField(
        widget=Datepicker(attrs={
            'placeholder': ugettext_lazy('Date start'),
        }), )
    date_end = forms.DateField(
        widget=Datepicker(attrs={
            'placeholder': ugettext_lazy('Date end'),
        }), )

    reconciled = forms.NullBooleanField(required=False)

    tags = forms.ModelMultipleChoiceField(
        queryset=BankTransactionTag.objects.none(), required=False)

    sum_min = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        localize=True,
        required=False,
        widget=forms.NumberInput(attrs={
            'placeholder': _('Minimum sum'),
        }),
    )
    sum_max = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        localize=True,
        required=False,
        widget=forms.NumberInput(attrs={
            'placeholder': _('Maximum sum'),
        }),
    )

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

        self.fields['tags'].queryset = (
            BankTransactionTag.objects.get_user_tags_queryset(user))
        self.fields['reconciled'].widget.choices[0] = ('1', _('Reconciled?'))

    def clean(self):
        cleaned_data = super(RatioForm, self).clean()

        date_start = cleaned_data.get('date_start')
        date_end = cleaned_data.get('date_end')
        if date_start and date_end and date_start > date_end:
            raise forms.ValidationError(
                _("Date start could not be greater than date end."),
                code='date_start_greater',
            )

        sum_min = cleaned_data.get('sum_min', None)
        sum_max = cleaned_data.get('sum_max', None)
        if sum_min is not None and sum_max is not None and sum_min > sum_max:
            raise forms.ValidationError(
                _("Minimum sum could not be greater than maximum sum."),
                code='sum_min_greater',
            )

        return cleaned_data