Example #1
0
	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 __init__(self,
              attrs=None,
              map_template_name=None,
              google_maps_api_vars=None,
              map_attrs=None):
     widgets = (
         forms.HiddenInput(attrs=attrs),
         forms.HiddenInput(attrs=attrs),
         forms.CheckboxInput(attrs=attrs),
     )
     self.google_maps_api_vars = google_maps_api_vars or \
                                 self.google_maps_api_vars
     self.map_template_name = map_template_name or self.map_template_name
     self.map_attrs = {
         'width': self.map_width,
         'height': self.map_height,
         'zoom': self.map_zoom,
     }
     self.map_attrs.update(map_attrs or {})
     super(MapWidget, self).__init__(widgets, attrs)
Example #3
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 #4
0
class TimeBasedForm(forms.Form):
    """A generic template for time and school year based forms"""
    this_year = forms.BooleanField(
        required=False,
        initial=True,
        widget=forms.CheckboxInput(
            attrs={'onclick': 'toggle("id_this_year")'}))
    all_years = forms.BooleanField(
        required=False,
        widget=forms.CheckboxInput(
            attrs={'onclick': 'toggle("id_all_years")'}))
    date_begin = forms.DateField(widget=adminwidgets.AdminDateWidget(),
                                 required=False,
                                 validators=settings.DATE_VALIDATORS)
    date_end = forms.DateField(widget=adminwidgets.AdminDateWidget(),
                               required=False,
                               validators=settings.DATE_VALIDATORS)
    # CourseMeet.day_choice is a tuple of tuples; need the first value from each inner tuple for initial
    schedule_days = forms.MultipleChoiceField(
        required=False,
        choices=CourseMeet.day_choice,
        help_text=
        '''On applicable reports, only the selected days will be included.
            Hold down "Control", or "Command" on a Mac, to select more than one.'''
    )
    marking_period = forms.ModelMultipleChoiceField(
        required=False, queryset=MarkingPeriod.objects.all())
    include_deleted = forms.BooleanField(required=False)

    class Media:
        js = ('/static/js/time_actions.js', )

    def clean(self):
        data = self.cleaned_data
        if not data.get("this_year") and not data.get("all_years"):
            if not data.get("date_begin") or not data.get("date_end"):
                if not data.get("marking_period"):
                    raise forms.ValidationError(
                        "You must select this year, all years, specify a date, or select a marking period."
                    )
        return data

    def get_dates(self):
        """ Returns begining and start dates in a tuple
        Pass it form.cleaned_data """
        data = self.cleaned_data
        if data['this_year'] and not data['marking_period']:
            start = SchoolYear.objects.get(active_year=True).start_date
            # if they want a date in the future, let them specify it explicitly
            end = min(date.today(),
                      SchoolYear.objects.get(active_year=True).end_date)
        elif not data['this_year'] and not data['all_years'] and not data[
                'marking_period']:
            start = data['date_begin']
            end = data['date_end']
        elif data['marking_period']:
            start = data['marking_period'].all().order_by(
                'start_date')[0].start_date
            end = data['marking_period'].all().order_by(
                '-end_date')[0].end_date
        else:  # all of time
            start = date(1980, 1, 1)
            end = date(2980, 1, 1)
        return (start, end)
Example #5
0
class StudentGradeReportWriterForm(forms.Form):
    date = forms.DateField(widget=adminwidgets.AdminDateWidget(),
                           initial=date.today,
                           validators=settings.DATE_VALIDATORS)
    template = forms.ModelChoiceField(required=False,
                                      queryset=Template.objects.all())
    upload_template = forms.FileField(
        required=False,
        help_text="You may choose a template or upload one here")
    include_deleted = forms.BooleanField(required=False)
    all_students = forms.BooleanField(
        required=False, widget=forms.CheckboxInput(attrs={'onclick': ''}))
    student = AutoCompleteSelectMultipleField('student', required=False)
    sort_by = forms.ChoiceField(choices=(('last_name', 'Student last name'),
                                         ('year', 'School year'),
                                         ('cohort', 'Primary Cohort')),
                                initial=1)
    filter_year = forms.ModelMultipleChoiceField(
        required=False, queryset=GradeLevel.objects.all())
    filter_cohort = forms.ModelMultipleChoiceField(
        required=False, queryset=Cohort.objects.all())
    omit_substitutions = forms.BooleanField(
        required=False
    )  # benchmark_grade only; displayed conditionally in template

    def clean(self):
        data = super(StudentGradeReportWriterForm, self).clean()
        if not data.get('student') and not data.get('all_students'):
            raise forms.ValidationError(
                "You must either check \"all students\" or select a student")
        if not data.get('template') and not data.get('upload_template'):
            raise forms.ValidationError(
                "You must either select a template or upload one.")
        return data

    def get_students(self, options, worker=False):
        """ Returns all students based on criteria. data should be form.cleaned_data """
        if worker:
            from ecwsp.work_study.models import StudentWorker
            students = StudentWorker.objects.all()
        else:
            students = Student.objects.all()

        # if selecting individual students, don't filter out deleted
        # why? Because it's unintuitive to pick one student, forgot about "include
        # deleted" and hit go to recieve a blank sheet.
        if not options['all_students']:
            students = students.filter(id__in=options['student'])
        elif not options['include_deleted']:
            students = students.filter(is_active=True)

        if options['student'].count == 1:
            data['student'] = options['student'][0]

        if options['sort_by'] == "year":
            students = students.order_by('year', 'last_name', 'first_name')
        elif options['sort_by'] == "hoomroom":
            pass

        if options['filter_year']:
            students = students.filter(year__in=options['filter_year'])

        if options['filter_cohort']:
            students = students.filter(cohorts__in=options['filter_cohort'])

        return students
Example #6
0
class StudentSelectForm(TimeBasedForm):
    """ Generic student selection form."""
    all_students = forms.BooleanField(
        required=False, widget=forms.CheckboxInput(attrs={'onclick': ''}))
    student = AutoCompleteSelectMultipleField('student', required=False)
    sort_by = forms.ChoiceField(choices=(('last_name', 'Student last name'),
                                         ('year', 'School year'),
                                         ('cohort', 'Primary Cohort')),
                                initial=1)
    filter_year = forms.ModelMultipleChoiceField(
        required=False, queryset=GradeLevel.objects.all())
    filter_cohort = forms.ModelMultipleChoiceField(
        required=False, queryset=Cohort.objects.all())

    def get_template(self, request):
        if self.cleaned_data['template']:
            # use selected template
            template = self.cleaned_data['template']
            if template.file:
                return template.file.path
            else:
                messages.error(request, 'Template not found')
        else:
            # or use uploaded template, saving it to temp file
            template = request.FILES['upload_template']
            tmpfile = mkstemp()[1]
            f = open(tmpfile, 'wb')
            f.write(template.read())
            f.close()
            return tmpfile

    def get_students(self, options, worker=False):
        """ Returns all students based on criteria. data should be form.cleaned_data """
        if worker:
            from ecwsp.work_study.models import StudentWorker
            students = StudentWorker.objects.all()
        else:
            students = Student.objects.all()

        # if selecting individual students, don't filter out deleted
        # why? Because it's unintuitive to pick one student, forgot about "include
        # deleted" and hit go to recieve a blank sheet.
        if not options['all_students']:
            students = students.filter(id__in=options['student'])
        elif not options['include_deleted']:
            students = students.filter(is_active=True)

        if options['student'].count == 1:
            data['student'] = options['student'][0]

        if options['sort_by'] == "year":
            students = students.order_by('year', 'last_name', 'first_name')
        elif options['sort_by'] == "cohort":
            students = students.order_by('cache_cohort', 'last_name',
                                         'first_name')

        if options['filter_year']:
            students = students.filter(year__in=options['filter_year'])

        if options['filter_cohort']:
            students = students.filter(cohorts__in=options['filter_cohort'])

        return students
Example #7
0
class RegistrationForm(FloppyWidgetsMixin, NonFieldErrorsMixin,
                       registration_forms.RegistrationForm):
    username = forms.CharField(
        max_length=30,
        widget=forms.HiddenInput(),
        required=False,
        label=_("Username"),
        error_messages={
            'invalid':
            _("This value must contain only letters, numbers and underscores.")
        })

    email = forms.EmailField(
        max_length=75, label=_("Email address (this will be your username)"))
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    tos = forms.BooleanField(
        widget=forms.CheckboxInput(),
        label=_(u'I have read and agree to the Terms of Service'),
        error_messages={
            'required': _("You must agree to the terms to register")
        })

    is_general_public = forms.BooleanField(required=False,
                                           label=_(u'General Public'))
    is_community_advocate = forms.BooleanField(required=False,
                                               label=_(u'Community Advocate'))
    is_journalist = forms.BooleanField(required=False, label=_(u'Journalist'))
    is_researcher = forms.BooleanField(required=False, label=_(u'Researcher'))
    is_grant_writer = forms.BooleanField(required=False,
                                         label=_(u'Grant Writer'))
    is_city_state_agency_staff = forms.BooleanField(
        required=False, label=_(u'City / State Agency Staff'))
    is_consultant = forms.BooleanField(required=False, label=_(u'Consultant'))
    is_legislator = forms.BooleanField(required=False, label=_(u'Legislator'))
    is_policy_analyst = forms.BooleanField(required=False,
                                           label=_(u'Policy Analyst'))
    is_other = forms.BooleanField(required=False, label=_(u'Other'))
    organization = forms.CharField(max_length=300, required=False)
    org_is_non_profit = forms.BooleanField(required=False,
                                           label=_(u'Non-Profit'))
    org_is_state_city_agency = forms.BooleanField(
        required=False, label=_(u'City / State Agency'))
    org_is_university = forms.BooleanField(required=False,
                                           label=_(u'University'))
    org_is_other = forms.BooleanField(required=False, label=_(u'Other'))
    wants_notifications = forms.BooleanField(
        required=False,
        label=
        _(u"I'd like to receive notifications about trainings, new datasets, and general Profiles news"
          ))

    def clean_email(self):
        """
        Validate that the supplied email address is unique for the
        site.
        
        """
        if User.objects.filter(email__iexact=self.cleaned_data['email']):
            raise forms.ValidationError(
                _("This email address is already in use. Please supply a different email address."
                  ))
        return self.cleaned_data['email']

    def clean(self):
        """
        Verifiy that the values entered into the two password fields
        match. Note that an error here will end up in
        ``non_field_errors()`` because it doesn't apply to a single
        field.
         
        """
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(
                    _("The two password fields didn't match."))

        # hash the user's email address to use as a username
        m = hashlib.md5()
        m.update(self.cleaned_data['email'])
        self.cleaned_data['username'] = base64.b64encode(m.digest())
        return self.cleaned_data