Example #1
0
    def test_specify_template_at_init_as_None(self):
        """Can give an explicit template_name=None without overriding."""
        widget = forms.TextInput(template_name=None)

        self.assertIsNot(widget.template_name, None)
Example #2
0
 class Form(forms.Form):
     foo = forms.CharField(
         widget=forms.TextInput(datalist=['Foo', 'Bar', 'Baz'], ))
Example #3
0
    def test_specify_template_at_init(self):
        """Can customize the template used when instantiating the widget."""
        widget = forms.TextInput(template_name='custom.html')

        rendered = widget.render('text', 'value')
        self.assertHTMLEqual(rendered, '<input type="custom" name="text" />')
Example #4
0
class UploadForm(forms.Form):
    id                = forms.IntegerField(required=False)
    appcc_id          = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    manautctrl_id     = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    planautoctrl_id   = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cabreg_id         = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    detreg_id         = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    registros_id      = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cuadgest_id       = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    relentes_id       = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    gestincid_id      = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cabanali_id       = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cabinftec_id      = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    fecha             = forms.DateField(initial=datetime.date.today,required=False)
    denominacion      = forms.CharField(max_length="200",required=False)    
    archivos          = forms.FileField(label='Selecciona un archivo',required=False)
    contenido         = forms.CharField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
Example #5
0
class DocumentosForms(forms.ModelForm):
    class Meta:
        model = Documentos
        exclude = ('user','fechaalta')

    def __init__(self, *args, **kwargs):
        prefijo="documentos"
        self.helper = FormHelper()
        self.helper.form_tag = False
        self.helper.layout = Layout(
            TR( Field('id',css_class="control-group hidden",template=campo),
                Field('appcc_id',css_class="control-group hidden",template=campo),
                Field('manautctrl_id',css_class="control-group hidden", template=campo),
                Field('planautoctrl_id',css_class="control-group hidden",template=campo),
                Field('cabreg_id',css_class="control-group hidden",template=campo),
                Field('detreg_id',css_class="control-group hidden",template=campo),
                Field('registros_id',css_class="control-group hidden",template=campo),
                Field('cuadgest_id',css_class="control-group hidden",template=campo),
                Field('relentes_id',css_class="control-group hidden",template=campo),
                Field('gestincid_id',css_class="control-group hidden",template=campo),
                Field('cabanali_id',css_class="control-group hidden",template=campo),
                Field('cabinftec_id',css_class="control-group hidden",template=campo),
                TD(Field('fecha',css_class="control-group", template="form/field_date_table.html")),
                TD(Field('denominacion',css_class="control-group", template="form/field.html")),
                TD(Field('archivos',css_class="control-group", template="form/field.html")),
                TD(Field('DELETE',template="form/field.html")), css_class="form-row inline %s" % prefijo ) ,#cambiar por el prefijo

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


    id                = forms.IntegerField(required=False)
    appcc_id          = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    manautctrl_id     = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    planautoctrl_id   = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cabreg_id         = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    detreg_id         = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    registros_id      = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cuadgest_id       = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    relentes_id       = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    gestincid_id      = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cabanali_id       = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
    cabinftec_id      = forms.IntegerField(required=False,widget=forms.TextInput(attrs= {'class':'hidden'}))
Example #6
0
class RequestForm(forms.Form):
    public_body = forms.CharField(
        widget=PublicBodySelect,
        label=_("Search for a topic or a public body:"),
        required=False)
    subject = forms.CharField(
        label=_("Subject"),
        widget=forms.TextInput(attrs={
            'placeholder': _("Subject"),
            "class": "span8"
        }))
    body = forms.CharField(
        label=_("Body"),
        widget=forms.Textarea(attrs={
            'placeholder': _("Specify your request here..."),
            "class": "span11"
        }))
    public = forms.BooleanField(
        required=False,
        initial=True,
        label=_("This request will be public immediately."))
    reference = forms.CharField(widget=forms.HiddenInput, required=False)

    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))

    def laws_to_json(self):
        return json.dumps(
            dict([(l.id, l.as_dict()) for l in self.list_of_laws]))

    def clean_public_body(self):
        pb = self.cleaned_data['public_body']
        if pb == "new":
            if not new_publicbody_allowed:
                raise forms.ValidationError(
                    _("You are not allowed to create a new public body"))
        elif pb == "":
            if not publicbody_empty:
                raise forms.ValidationError(
                    _("You must specify a public body"))
            pb = None
        else:
            try:
                pb_pk = int(pb)
            except ValueError:
                raise forms.ValidationError(_("Invalid value"))
            try:
                public_body = PublicBody.objects.get(pk=pb_pk)
            except PublicBody.DoesNotExist:
                raise forms.ValidationError(_("Invalid value"))
            self.public_body_object = public_body
            self.foi_law_object = public_body.default_law
        return pb

    public_body_object = None

    def clean_reference(self):
        ref = self.cleaned_data['reference']
        if ref == '':
            return None
        try:
            kind, value = ref.split(':')
        except ValueError:
            return None
        try:
            return {kind: value}
        except ValueError:
            return None

    def clean_law_for_public_body(self, public_body):
        law = self.clean_law_without_public_body()
        if law is None:
            return None
        if law.jurisdiction.id != public_body.jurisdiction.id:
            self._errors["law"] = self.error_class(
                [_("Invalid Information Law")])
            return None
        return law

    def clean_law_without_public_body(self):
        try:
            law = self.cleaned_data['law']
            law = self.indexed_laws[int(law)]
        except (ValueError, KeyError):
            self._errors["law"] = self.error_class(
                [_("Invalid Information Law")])
            return None
        return law

    def clean(self):
        cleaned = self.cleaned_data
        public_body = cleaned.get("public_body")
        if public_body is not None and (public_body != "new"
                                        and public_body != ""):
            self.foi_law = self.clean_law_for_public_body(
                self.public_body_object)
        else:
            self.foi_law = self.clean_law_without_public_body()
        return cleaned
Example #7
0
class PostalReplyForm(forms.Form, PostalScanMixin):
    scan_help_text = mark_safe(
        _("Uploaded scans can be PDF, JPG or PNG. Please make sure to <strong>redact/black out all private information concerning you</strong>."
          ))
    date = forms.DateField(
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": _('mm/dd/YYYY')
        }),
        label=_("Send Date"),
        help_text=_("Please give the date the reply was sent."),
        localize=True)
    sender = forms.CharField(
        label=_("Sender Name"),
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": _("Sender Name")
        }),
        required=True)
    subject = forms.CharField(
        label=_("Subject"),
        required=False,
        max_length=230,
        widget=forms.TextInput(attrs={
            "class": "form-control",
            "placeholder": _("Subject")
        }))
    text = forms.CharField(
        label=_("Letter"),
        widget=forms.Textarea(
            attrs={
                "placeholder": _("Letter text you have received"),
                "class": "form-control"
            }),
        required=False,
        help_text=
        _("The text can be left empty, instead you can upload scanned documents."
          ))
    scan = forms.FileField(label=_("Scanned Letter"),
                           required=False,
                           help_text=scan_help_text)
    not_publishable = forms.BooleanField(
        label=_("You are not allowed to publish some received documents"),
        initial=False,
        required=False,
        help_text=
        _('If the reply explicitly states that you are not allowed to publish some of the documents (e.g. due to copyright), check this.'
          ))

    def clean_date(self):
        date = self.cleaned_data['date']
        now = timezone.now().date()
        if date > now:
            raise forms.ValidationError(
                _("Your reply date is in the future, that is not possible."))
        return date

    def clean(self):
        cleaned_data = self.cleaned_data
        text = cleaned_data.get("text")
        scan = cleaned_data.get("scan")
        if not (text or scan):
            raise forms.ValidationError(
                _("You need to provide either the letter text or a scanned document."
                  ))
        return cleaned_data
 def __init__(self, *args, **kwargs):
     widgets = (forms.TextInput(), forms.TextInput())
     super(LatLngWidget, self).__init__(widgets, *args, **kwargs)
Example #9
0
class SendMessageForm(forms.Form):
    to = forms.TypedChoiceField(
        label=_("To"),
        choices=[],
        coerce=int,
        required=True,
        widget=forms.RadioSelect(attrs={"class": "form-control"}))
    subject = forms.CharField(
        label=_("Subject"),
        max_length=230,
        widget=forms.TextInput(attrs={"class": "form-control"}))
    message = forms.CharField(
        widget=forms.Textarea(attrs={"class": "form-control"}),
        label=_("Your message"))

    def __init__(self, foirequest, *args, **kwargs):
        super(SendMessageForm, self).__init__(*args, **kwargs)
        self.foirequest = foirequest

        choices = [(0, _("Default address of %(publicbody)s") % {
            "publicbody": foirequest.public_body.name
        })]
        choices.extend([
            (m.id, m.reply_address_entry)
            for k, m in foirequest.possible_reply_addresses().items()
        ])
        self.fields['to'].choices = choices

        if foirequest.law and foirequest.law.email_only:
            self.fields['send_address'] = forms.BooleanField(
                label=_("Send physical address"),
                help_text=(_(
                    'If the public body is asking for your post '
                    'address, check this and we will append it to your message.'
                )),
                required=False)

    def clean(self):
        throttle_message = check_throttle(self.foirequest.user, FoiMessage)
        if throttle_message:
            raise forms.ValidationError(throttle_message)

    def save(self, user):
        if self.cleaned_data["to"] == 0:
            recipient_name = self.foirequest.public_body.name
            recipient_email = self.foirequest.public_body.email
            recipient_pb = self.foirequest.public_body
        else:
            message = list(
                filter(lambda x: x.id == self.cleaned_data["to"],
                       list(self.foirequest.messages)))[0]
            recipient_name = message.sender_name
            recipient_email = message.sender_email
            recipient_pb = message.sender_public_body
        return self.foirequest.add_message(user,
                                           recipient_name,
                                           recipient_email,
                                           self.cleaned_data["subject"],
                                           self.cleaned_data['message'],
                                           recipient_pb=recipient_pb,
                                           send_address=self.cleaned_data.get(
                                               'send_address', True))
Example #10
0
class SettingsForm(forms.ModelForm):
	start = forms.DateField(input_formats=('%d.%m.%Y',), error_messages=RU_ERRORS, widget=forms.DateInput(attrs={'class': 'input-small form-control'}))
	finish = forms.DateField(input_formats=('%d.%m.%Y',), error_messages=RU_ERRORS, widget=forms.DateInput(attrs={'class': 'input-small form-control'}))
	time = forms.TimeField(input_formats=('%H:%M',), error_messages=RU_ERRORS, widget=forms.TimeInput(attrs={'class': 'form-control', 'id': 'alert-time-display', 'value': '12:00'}))
	email = forms.EmailField(required=False, error_messages=RU_ERRORS, widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': u'Укажите email для оповещений'}))
	phone = forms.RegexField(r'^\+79\d{9}$', '^\+79\d{9}$', required=False, error_messages=RU_ERRORS, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': u'+79123456789'}))
	user_time = forms.CharField(widget=forms.HiddenInput())

	class Meta:
		model = Alert
		widgets = {
			'alert_email': forms.CheckboxInput(attrs={'id': 'email-alert'}),
			'alert_sms': forms.CheckboxInput(attrs={'id': 'sms-alert'}),
			'period': forms.Select(attrs={'class': 'form-control'}),
		}
		exclude = ['user', 'alert_server_time']

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

		if cleaned_data.get('alert_email') and cleaned_data.get('email') == '':
			raise forms.ValidationError(u'Введите email')

		if cleaned_data.get('alert_sms') and cleaned_data.get('phone') == '':
			raise forms.ValidationError(u'Введите номер телефона')
	
		return cleaned_data
Example #11
0
class ContactForm(forms.Form):
	email = forms.CharField(error_messages=RU_ERRORS, widget=forms.EmailInput(attrs={'class': 'form-control'}))
	subject = forms.CharField(error_messages=RU_ERRORS, widget=forms.TextInput(attrs={'class': 'form-control'}))
	message = forms.CharField(error_messages=RU_ERRORS, widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 7}))
Example #12
0
class NewUserBaseForm(forms.Form):
    first_name = forms.CharField(
        max_length=30,
        label=_('First name'),
        widget=forms.TextInput(attrs={
            'placeholder': _('First Name'),
            'class': 'form-control'
        }))
    last_name = forms.CharField(
        max_length=30,
        label=_('Last name'),
        widget=forms.TextInput(attrs={
            'placeholder': _('Last Name'),
            'class': 'form-control'
        }))
    #    address = forms.CharField(max_length=300,
    #            required=False,
    #            label=_('Mailing Address'),
    #            help_text=_('Optional. Your address will not be displayed publicly and is only needed in case a public agency needs to send you paper.'),
    #            widget=forms.Textarea(attrs={
    #                'rows': '3',
    #                'class': 'form-control',
    #                'placeholder': _('Street, City, Zip Code'),
    #            }))
    user_email = forms.EmailField(
        label=_('Email address'),
        max_length=75,
        help_text=_('Not public. The given address will '
                    'need to be confirmed.'),
        widget=forms.EmailInput(attrs={
            'placeholder': _('*****@*****.**'),
            'class': 'form-control'
        }))

    if HAVE_ORGANIZATION:
        organization = forms.CharField(
            required=False,
            label=_("Organization"),
            help_text=_(
                'Optional. Affiliation will be shown next to your name'),
            widget=forms.TextInput(attrs={
                'placeholder': _('Organization'),
                'class': 'form-control'
            }))

    if USER_CAN_HIDE_WEB:
        private = forms.BooleanField(
            required=False,
            label=_("Hide my name on the web"),
            help_text=mark_safe(
                _("If you check this, your name will still appear in requests to public agencies, but we will do our best to not display it publicly. However, we cannot guarantee your anonymity"
                  )))

    def __init__(self, *args, **kwargs):
        super(NewUserBaseForm, self).__init__(*args, **kwargs)
        if ALLOW_PSEUDONYM:
            self.fields["last_name"].help_text = mark_safe(
                _('<a target="_blank" href="{url}">You may use a pseudonym if you don\'t need to receive postal messages</a>.'
                  ).format(url=reverse("help-privacy") + '#pseudonym'))

    def clean_first_name(self):
        return self.cleaned_data['first_name'].strip()

    def clean_last_name(self):
        return self.cleaned_data['last_name'].strip()

    def clean_user_email(self):
        email = self.cleaned_data['user_email']
        user_model = get_user_model()
        try:
            user = user_model.objects.get(email=email)
        except user_model.DoesNotExist:
            pass
        else:
            if user.is_active:
                raise forms.ValidationError(
                    mark_safe(
                        _('This email address already has an account. <a href="%(url)s?simple&email=%(email)s" class="btn btn-warning target-small">Click here to login using that email address.</a>'
                          ) % {
                              'url': reverse("account-login"),
                              'email': email
                          }))
            else:
                raise forms.ValidationError(
                    _('This email address is already registered, but not yet confirmed! Please click on the confirmation link in the mail we send you.'
                      ))
        return email
Example #13
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
Example #14
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']
Example #15
0
 class TextForm(forms.Form):
     text = forms.CharField(widget=forms.TextInput(
         attrs={'placeholder': 'Heheheh'}))
Example #16
0
class RequestForm(forms.Form):
    public_body = forms.CharField(
        widget=PublicBodySelect,
        label=_("Search for a topic or a public body:"),
        required=False)
    subject = forms.CharField(
        label=_("Subject"),
        max_length=230,
        widget=forms.TextInput(attrs={
            'placeholder': _("Subject"),
            "class": "form-control"
        }))
    body = forms.CharField(
        label=_("Body"),
        widget=forms.Textarea(
            attrs={
                'placeholder': _("Specify your request here..."),
                "class": "form-control"
            }))
    full_text = forms.BooleanField(
        required=False,
        initial=False,
        label=_("Don't wrap in template"),
        widget=forms.CheckboxInput(attrs={'tabindex': '-1'}))
    public = forms.BooleanField(
        required=False,
        initial=True,
        label=_("This request is public."),
        help_text=_(
            "If you don't want your request to be public right now,"
            " uncheck this. You can always decide to make it public later."))
    reference = forms.CharField(widget=forms.HiddenInput, required=False)
    redirect_url = forms.CharField(widget=forms.HiddenInput, required=False)

    def __init__(self,
                 user=None,
                 list_of_laws=(),
                 default_law=None,
                 hide_law_widgets=True,
                 **kwargs):
        super(RequestForm, self).__init__(**kwargs)
        self.user = user
        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 hide_law_widgets else forms.HiddenInput,
            initial=default_law.pk,
            choices=((l.pk, l.name) for l in list_of_laws))

    def laws_to_json(self):
        return json.dumps(
            dict([(l.id, l.as_dict()) for l in self.list_of_laws]))

    def clean_public_body(self):
        pb = self.cleaned_data['public_body']
        if pb == "new":
            if not new_publicbody_allowed:
                raise forms.ValidationError(
                    _("You are not allowed to create a new public body"))
        elif pb == "":
            if not publicbody_empty:
                raise forms.ValidationError(
                    _("You must specify a public body"))
            pb = None
        else:
            try:
                pb_pk = int(pb)
            except ValueError:
                raise forms.ValidationError(_("Invalid value"))
            try:
                public_body = PublicBody.objects.get(pk=pb_pk)
            except PublicBody.DoesNotExist:
                raise forms.ValidationError(_("Invalid value"))
            self.public_body_object = public_body
            self.foi_law_object = public_body.default_law
        return pb

    public_body_object = None

    def clean_reference(self):
        ref = self.cleaned_data['reference']
        if not ref:
            return ''
        try:
            kind, value = ref.split(':', 1)
        except ValueError:
            return ''
        try:
            return '%s:%s' % (kind, value)
        except ValueError:
            return ''

    def clean_law_for_public_body(self, public_body):
        law = self.clean_law_without_public_body()
        if law is None:
            return None
        if law.jurisdiction.id != public_body.jurisdiction.id:
            self._errors["law"] = self.error_class(
                [_("Invalid Information Law")])
            return None
        return law

    def clean_law_without_public_body(self):
        try:
            law = self.cleaned_data['law']
            law = self.indexed_laws[int(law)]
        except (ValueError, KeyError):
            self._errors["law"] = self.error_class(
                [_("Invalid Information Law")])
            return None
        return law

    def clean(self):
        cleaned = self.cleaned_data
        public_body = cleaned.get("public_body")
        if public_body is not None and (public_body != "new"
                                        and public_body != ""):
            self.foi_law = self.clean_law_for_public_body(
                self.public_body_object)
        else:
            self.foi_law = self.clean_law_without_public_body()

        throttle_message = check_throttle(self.user, FoiRequest)
        if throttle_message:
            raise forms.ValidationError(throttle_message)

        return cleaned
Example #17
0
 class Form(forms.Form):
     text = forms.CharField(widget=forms.TextInput(attrs={
         'foo': True,
         'bar': False,
     }))
Example #18
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;'}))