Ejemplo n.º 1
0
class ProjectCompleteCreateForm(forms.ModelForm):

    class Meta:
        model = ProjectComplete
        fields = '__all__'

    map = forms.CharField(widget=GoogleMapsWidget(
        attrs={'width': 700, 'height': 400, 'longitude': 'longitude', 'latitude': 'latitude'}), required=False)

    expected_start_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    expected_end_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    actual_start_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    actual_end_date = forms.DateField(widget=DatePicker.DateInput(), required=False)

    program = forms.ModelChoiceField(queryset=Program.objects.filter(funding_status="Funded"))

    def __init__(self, *args, **kwargs):
        #get the user object from request to check permissions
        self.request = kwargs.pop('request')
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-6'
        self.helper.form_error_title = 'Form Errors'
        self.helper.error_text_inline = True
        self.helper.help_text_inline = True
        self.helper.html5_required = True
        self.helper.layout = Layout(

            HTML("""<br/>"""),
            TabHolder(
                Tab('Executive Summary',
                    Fieldset('Program', 'program', 'project_proposal', 'project_agreement', 'activity_code', 'office', 'sector', 'project_name','project_activity','site'
                    ),
                    Fieldset(
                        'Dates',
                        'expected_start_date','expected_end_date', 'expected_duration', 'actual_start_date', 'actual_end_date', 'actual_duration',
                        PrependedText('on_time', ''), 'no_explanation',

                    ),
                ),
            ),

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

        #override the program queryset to use request.user for country
        countries = getCountry(self.request.user)
        self.fields['program'].queryset = Program.objects.filter(funding_status="Funded", country__in=countries)

        #override the office queryset to use request.user for country
        self.fields['office'].queryset = Office.objects.filter(province__country__in=countries)
Ejemplo n.º 2
0
class PontoForm(forms.ModelForm):
    class Meta:
        model = Ponto
        fields = [
            'coll', 'req_min_date', 'req_max_date', 'missoes', 'satelites'
        ]

    coll = forms.gis.GeometryCollectionField(required=False,
                                             widget=PointWidget,
                                             label='')
    req_min_date = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            'format': 'DD-MM-YYYY',
            'type': 'datepicker'
        }),
        label='Data mínima desejada')
    #req_max_date = forms.DateField(required=False, widget=SelectDateWidget(years=range(1971, 2019)), label='Data máxima desejada')
    req_max_date = forms.DateField(
        required=False,
        widget=forms.DateInput(attrs={
            'format': 'DD-MM-YYYY',
            'type': 'datepicker'
        }),
        label='Data máxima desejada')
    missoes = forms.ModelMultipleChoiceField(
        queryset=Missao.objects.all(),
        widget=forms.CheckboxSelectMultiple,
        required=False,
        label='Missão')
    satelites = forms.ModelMultipleChoiceField(
        queryset=Satelite.objects.all(),
        widget=forms.CheckboxSelectMultiple,
        required=False,
        label='Satélite')

    #chaves = forms.ModelMultipleChoiceField(
    #queryset = Chave.objects.all(),
    #widget = forms.CheckboxSelectMultiple,
    #required=False,
    #label='Filtro'
    #)

    def clean_req_date(self):
        cleaned_data = super(PontoForm, self).clean()
        req_min_date = cleaned_data.get("req_min_date")
        req_max_date = cleaned_data.get("req_max_date")

        if req_min_date and req_max_date:
            if req_max_date < req_min_date:
                raise forms.ValidationError(
                    "A data máxima não pode ser menor que a data mínima.")
        return cleaned_data
Ejemplo n.º 3
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        today = date.today()
        first_day_of_month = date(today.year, today.month, 1)
        if today.month == 12:
            month_of_next = 1
            year_of_next = today.year + 1
        else:
            month_of_next = today.month + 1
            year_of_next = today.year
        first_day_of_next_month = date(year_of_next, month_of_next, 1)
        last_day_of_month = first_day_of_next_month - timedelta(days=1)

        self.fields['start_date'] = forms.DateField(label=_("From"),
                                                    required=True,
                                                    initial=first_day_of_month)
        self.fields['end_date'] = forms.DateField(label=_("To"),
                                                  required=True,
                                                  initial=last_day_of_month)
Ejemplo n.º 4
0
class LecturerSignUpForm(UserCreationForm):
    # Declare user option fields to form
    first_name = forms.CharField(required=True, widget=forms.TextInput(
        attrs={'placeholder': 'First name'}))
    other_name = forms.CharField(required=True, widget=forms.TextInput(
        attrs={'placeholder': 'Other name'}))
    last_name = forms.CharField(required=True, widget=forms.TextInput(
        attrs={'placeholder': 'Surname '}))
    birth_place = forms.ChoiceField(required=True, choices=STATES)
    sex = forms.ChoiceField(required=True, choices=GENDER)
    birth_date = forms.DateField(required=True, widget=forms.DateInput)
    email = forms.EmailField(widget=forms.EmailInput(
        attrs={'placeholder': 'Enter email address'}), required=True)
    phone = forms.CharField(required=True, widget=forms.PhoneNumberInput(
        attrs={'placeholder': 'Mobile Number'}))
    address = forms.CharField(required=False, widget=forms.TextInput(attrs={'placeholder': 'House/Street/City/Town '}),
                              max_length=100)
    faculty = forms.ModelChoiceField(
        queryset=Faculty.objects.all(), required=False)

    class Meta:
        model = User
        fields = ('first_name', 'other_name', 'last_name', 'sex', 'birth_place', 'address',
                  'phone', 'email', 'faculty', 'birth_date', 'username',)

    # Add placeholder to UserCreationForm fields
    def __init__(self, *args, **kwargs):
        super(LecturerSignUpForm, self).__init__(*args, **kwargs)
        self.fields['username'].widget.attrs.update(
            {'placeholder': 'Choose A Unique Username'})
        self.fields['password1'].widget.attrs.update(
            {'placeholder': 'Choose A Password'})
        self.fields['password2'].widget.attrs.update(
            {'placeholder': 'Verify Password'})

    # Check if inputted email has not been used by another user
    def clean_email(self):
        email = self.cleaned_data['email']
        check = User.objects.values('email')
        if email in check:
            msg = 'this email has been used!'
            self.add_error('email', msg)
        return email

    def save(self, commit=True):
        user = super().save(commit=False)
        user.is_lecturer = True
        if commit:
            user.save()
            # Create lecturer object with user id
            Lecturer.objects.create(user=user)

        return user
Ejemplo n.º 5
0
class AddExtraSaleForm(BetterBsForm):
    """A form for adding a new extra sale"""

    analysis_code = forms.ChoiceField(label=_('Analysis code'), required=True)
    amount = forms.DecimalField(max_digits=9,
                                decimal_places=2,
                                required=True,
                                label=_('Amount'))
    vat_rate = forms.ChoiceField(label=_('VAT rate'), required=True)
    date = forms.DateField(label=_('Date'), required=True)

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

        self.valid_action_types = [
            item.action_type
            for item in StoreManagementActionType.objects.all()
        ]

        self.fields['analysis_code'].choices = [
            (analysis_code.id, analysis_code.name)
            for analysis_code in SaleAnalysisCode.objects.filter(
                action_type__in=self.valid_action_types)
        ]
        self.fields['vat_rate'].choices = [
            (vat_rate.id, vat_rate.name) for vat_rate in VatRate.objects.all()
        ]
        self.fields['date'].initial = date.today()

    def clean_analysis_code(self):
        """validate the analysis code"""
        analysis_code_id = self.cleaned_data['analysis_code']
        try:
            return SaleAnalysisCode.objects.get(
                id=analysis_code_id, action_type__in=self.valid_action_types)
        except SaleAnalysisCode.DoesNotExist:
            forms.ValidationError(ugettext('Invalid analysis code'))

    def clean_vat_rate(self):
        """validate the analysis code"""
        vat_rate_id = self.cleaned_data['vat_rate']
        try:
            return VatRate.objects.get(id=vat_rate_id)
        except VatRate.DoesNotExist:
            forms.ValidationError(ugettext('Invalid analysis code'))
Ejemplo n.º 6
0
class ActionForContactsForm(forms.ModelForm):
    """Create action for contacts"""
    date = forms.DateField(label=_("planned date"),
                           required=False,
                           widget=forms.TextInput())
    time = forms.TimeField(label=_("planned time"), required=False)
    contacts = forms.CharField(widget=forms.HiddenInput())

    class Meta:
        """create form from model"""
        model = Action
        fields = ('date', 'time', 'type', 'subject', 'in_charge', 'detail',
                  'planned_date', 'contacts', 'opportunity')

    def __init__(self, *args, **kwargs):
        initial = kwargs.get('initial')
        initial_contacts = ''
        if initial and 'contacts' in initial:
            initial_contacts = ';'.join(
                ['{0}'.format(c.id) for c in initial['contacts']])
            initial.pop('contacts')
        super(ActionForContactsForm, self).__init__(*args, **kwargs)
        if initial_contacts:
            self.fields['contacts'].initial = initial_contacts
        self.fields['opportunity'].widget = OpportunityAutoComplete(
            attrs={
                'placeholder': _('Enter the name of an opportunity'),
                'size': '80',
                'class': 'colorbox'
            })

    def get_contacts(self):
        """return contacts"""
        contact_ids = self.cleaned_data["contacts"].split(";")
        return Contact.objects.filter(id__in=contact_ids)

    def clean_planned_date(self):
        """validate planned date"""
        the_date = self.cleaned_data["date"]
        the_time = self.cleaned_data.get("time", None)
        if the_date:
            return datetime.combine(the_date, the_time or datetime.min.time())
        return None
Ejemplo n.º 7
0
class ActionForm(FormWithFieldsetMixin, BetterBsModelForm):
    """form for creating or editing action"""

    date = forms.DateField(label=_(u"planned date"), required=False, widget=forms.TextInput())
    time = forms.TimeField(label=_(u"planned time"), required=False)

    end_date = forms.DateField(label=_(u"end date"), required=False, widget=forms.TextInput())
    end_time = forms.TimeField(label=_(u"end time"), required=False)

    amount = forms.DecimalField(label=_("Amount"), required=False)

    class Meta:
        """form from model"""
        model = models.Action
        fields = (
            'type', 'subject', 'date', 'time', 'status', 'status2', 'in_charge', 'detail',
            'amount', 'number', 'planned_date', 'end_date', 'end_time', 'end_datetime', 'opportunity'
        )
        fieldsets = [
            ('summary', {
                'fields': [
                    'subject', 'in_charge', 'date', 'time', 'planned_date', 'end_date', 'end_time', 'end_datetime',
                    'opportunity'
                ],
                'legend': _('Summary')
            }),
            ('type', {'fields': ['type', 'status', 'status2', 'amount', 'number'], 'legend': _('Type')}),
            ('details', {'fields': ['detail'], 'legend': _('Details')}),
        ]
        help_texts = {
            'amount': _('Amount is disabled when value is calculated'),
        }

    def __init__(self, *args, **kwargs):
        kwargs.pop('entity', None)
        instance = kwargs.get('instance', None)
        action_type = kwargs.pop('action_type', None)
        super(ActionForm, self).__init__(*args, **kwargs)
        self.title = u""
        if instance:
            action_type = instance.type
        self.action_type = action_type

        is_amount_calculated = False
        if action_type:
            is_amount_calculated = action_type.is_amount_calculated
            self.calculated_amount = Decimal("0")
            for fieldset_name, fieldset_attrs in self.Meta.fieldsets:
                if fieldset_name == 'type':
                    fieldset_attrs['legend'] = action_type.name
                    break
            self.fields['type'].widget = forms.HiddenInput()
            self.fields['type'].initial = action_type
            if instance:
                self.title = ugettext(u"Edition {0}").format(action_type.name)
            else:
                self.title = ugettext(u"Creation {0}").format(action_type.name)
        else:
            self.title = ugettext(u"Edit action") if instance else ugettext(u"Create action")

        is_auto_generated = (action_type and action_type.number_auto_generated) or \
                            (instance and instance.type and instance.type.number_auto_generated)
        if is_auto_generated:
            self.fields['number'].widget.attrs['disabled'] = 'disabled'
            self.fields['number'].required = False

        self.fields['amount'].widget.attrs['step'] = 'any'
        if is_amount_calculated:
            self.fields['amount'].widget.attrs['disabled'] = 'disabled'
        self.is_amount_calculated = is_amount_calculated

        if action_type and action_type.allowed_status.count():
            # let javascript disable the blank value if default_status
            choices = [('', "---------")]
            allowed_status = action_type.allowed_status.all()
            if instance and instance.frozen:
                allowed_status = allowed_status.filter(allowed_on_frozen=True)
            self.fields['status'].choices = choices + [
                (status.id, status.name) for status in allowed_status
            ]
            if action_type.default_status:
                self.fields['status'].initial = action_type.default_status.id
            else:
                self.fields['status'].initial = ''

        if action_type and action_type.allowed_status2.count():
            # let javascript disable the blank value if default_status2
            allowed_status2 = action_type.allowed_status2.all()
            if instance and instance.frozen:
                allowed_status2 = allowed_status2.filter(allowed_on_frozen=True)
            choices = [('', "---------")]
            self.fields['status2'].choices = choices + [
                (status.id, status.name) for status in allowed_status2
            ]
            if action_type.default_status2:
                self.fields['status2'].initial = action_type.default_status2.id
            else:
                self.fields['status2'].initial = ''
        else:
            self.fields['status2'].widget = forms.HiddenInput()

        self.fields['opportunity'].widget = forms.HiddenInput()
        self.fields['detail'].widget = forms.Textarea(attrs={'placeholder': _('enter details'), 'cols': '72'})

        self._init_dt_field("planned_date", "date", "time")
        self._init_dt_field("end_datetime", "end_date", "end_time")

    def _init_dt_field(self, dt_field, date_field, time_field):
        """init datetime fields"""
        self.fields[dt_field].widget = CalcHiddenInput()
        the_datetime = getattr(self.instance, dt_field) if self.instance else self.fields[dt_field].initial
        if the_datetime:
            self.fields[date_field].initial = the_datetime.date()
            if settings.USE_TZ:
                utc_dt = the_datetime.replace(tzinfo=timezone.utc)
                loc_dt = utc_dt.astimezone(timezone.get_current_timezone())
                self.fields[time_field].initial = loc_dt.time()
            else:
                self.fields[time_field].initial = the_datetime.time()

        is_frozen = self.instance.frozen if self.instance else False
        if is_frozen:
            self.fields[date_field].widget.attrs['disabled'] = 'disabled'
            self.fields[time_field].widget.attrs['disabled'] = 'disabled'

    def clean_status(self):
        """status validation"""
        type_of = self.cleaned_data.get('type') or self.action_type
        status = self.cleaned_data['status']
        if type_of:
            allowed_status = ([] if type_of.default_status else [None]) + list(type_of.allowed_status.all())
            if len(allowed_status) > 0 and status not in allowed_status:
                raise ValidationError(ugettext(u"This status can't not be used for this action type"))
        else:
            if status:
                raise ValidationError(ugettext(u"Please select a type before defining the status"))
        return status

    def clean_status2(self):
        """status validation"""
        type_of = self.cleaned_data['type']
        status = self.cleaned_data['status2']
        if type_of:
            allowed_status = ([] if type_of.default_status2 else [None]) + list(type_of.allowed_status2.all())
            if len(allowed_status) > 0 and status not in allowed_status:
                raise ValidationError(ugettext(u"This status can't not be used for this action type"))
        else:
            if status:
                raise ValidationError(ugettext(u"Please select a type before defining the status"))
        return status

    def clean_planned_date(self):
        """planned date validation"""
        the_date = self.cleaned_data.get("date", None)
        the_time = self.cleaned_data.get("time", None)
        if the_date:
            return datetime.combine(the_date, the_time or datetime.min.time())
        return None

    def clean_time(self):
        """time validation"""
        the_date = self.cleaned_data.get("date", None)
        the_time = self.cleaned_data.get("time", None)
        if the_time and not the_date:
            raise ValidationError(_(u"You must set a date"))
        return the_time

    def clean_end_date(self):
        """end date validation"""
        date1 = self.cleaned_data.get("date", None)
        date2 = self.cleaned_data.get("end_date", None)
        if date2:
            start_dt = self.cleaned_data["planned_date"]
            if not start_dt:
                raise ValidationError(_(u"The planned date is not defined"))
            if date1 > date2:
                raise ValidationError(_(u"The end date must be after the planned date"))
        return date2

    def clean_end_time(self):
        """end time validation"""
        date1 = self.cleaned_data.get("date", None)
        date2 = self.cleaned_data.get("end_date", None)
        time1 = self.cleaned_data.get("time", None)
        time2 = self.cleaned_data.get("end_time", None)

        if time2:
            if time2 and not date2:
                raise ValidationError(_(u"You must set a end date"))

            if date1 == date2 and (time1 or datetime.min.time()) >= time2:
                raise ValidationError(_(u"The end time must be after the planned time"))

        elif time1:
            if date1 == date2 and time1 >= datetime.min.time():
                raise ValidationError(_(u"The end time must be set"))
        return time2

    def clean_end_datetime(self):
        """clean end datetime"""
        end_date = self.cleaned_data.get("end_date", None)
        end_time = self.cleaned_data.get("end_time", None)
        if end_date:
            return datetime.combine(end_date, end_time or datetime.min.time())
        return None

    def clean_amount(self):
        if self.is_amount_calculated:
            return self.calculated_amount
        else:
            return self.cleaned_data['amount']

    def save(self, *args, **kwargs):
        return super(ActionForm, self).save(*args, **kwargs)
Ejemplo n.º 8
0
class CollectedDataForm(forms.ModelForm):

    class Meta:
        model = CollectedData
        exclude = ['create_date', 'edit_date']

    date_collected = forms.DateField(widget=DatePicker.DateInput(), required=True)

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.request = kwargs.pop('request')
        self.program = kwargs.pop('program')
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-6'
        self.helper.form_error_title = 'Form Errors'
        self.helper.error_text_inline = True
        self.helper.help_text_inline = True
        self.helper.html5_required = True
        self.helper.form_tag = True
        self.helper.layout = Layout(

            HTML("""<br/>"""),

            Fieldset('Collected Data',
                'targeted', 'achieved', 'date_collected','indicator', 'program','description',

            ),

            HTML("""<br/>"""),

            Fieldset('Evidence',
                'agreement','method','evidence','tola_table',
                HTML("""<a class="output" data-toggle="modal" data-target="#myModal" href="/indicators/collecteddata_import/">Import Evidence From Tola Tables</a>"""),

            ),



                MultiField(
                        "",
                        HTML("""<br/>
                                {% if getDisaggregationLabel and not getDisaggregationValue%}
                                    <div class='panel panel-default'>
                                        <!-- Default panel contents -->
                                        <div class='panel-heading'>New Disaggregations</div>
                                          <!-- Table -->
                                          <table class="table">
                                            <tr>
                                            <th>Disaggregation Level</th>
                                            <th>Actuals</th>
                                            </tr>
                                            {% for item in getDisaggregationLabel %}
                                            <tr>
                                                <td>{{ item.label }}</td>
                                                <td><input type="text" name="{{ item.id }}" value=""></td>
                                            </tr>
                                            {% endfor %}
                                          </table>
                                    </div>
                                {% else %}
                                    <h4>Disaggregation Levels Not Entered For This Indicator</h4>
                                    <a href="/indicators/indicator_update/{{ indicator_id }}">Add a Disaggregation</a>
                                {% endif %}

                                {% if getDisaggregationValue %}
                                    <div class='panel panel-default'>
                                        <!-- Default panel contents -->
                                        <div class='panel-heading'>Existing Disaggregations</div>

                                          <!-- Table -->
                                          <table class="table">
                                            <tr>
                                            <th>Disaggregation Level</th>
                                            <th>Actuals</th>
                                            </tr>
                                            {% for item in getDisaggregationValue %}
                                            <tr>
                                                <td>{{ item.disaggregation_label.label }}</td>
                                                <td><input type="text" name="{{ item.disaggregation_label.id }}" value="{{ item.value }}"></td>
                                            </tr>
                                            {% endfor %}
                                          </table>

                                    </div>
                                {% endif %}
                             """),
                ),

            HTML("""<br/>"""),
            FormActions(
                Submit('submit', 'Save', css_class='btn-default'),
                Reset('reset', 'Reset', css_class='btn-warning')
            )
        )

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

        #override the program queryset to use request.user for country
        self.fields['evidence'].queryset = Documentation.objects.filter(program=self.program)

        #override the program queryset to use request.user for country
        self.fields['agreement'].queryset = ProjectAgreement.objects.filter(program=self.program)

        #override the program queryset to use request.user for country
        countries = getCountry(self.request.user)
        self.fields['program'].queryset = Program.objects.filter(funding_status="Funded", country__in=countries).distinct()

        self.fields['indicator'].queryset = Indicator.objects.filter(name__isnull=False, country__in=countries)
Ejemplo n.º 9
0
class PostalBaseForm(AttachmentSaverMixin, forms.Form):
    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>."
          ))
    public_body = forms.ModelChoiceField(label=_('Public body'),
                                         queryset=PublicBody.objects.all(),
                                         widget=PublicBodySelect)
    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)
    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"),
            "class": "form-control"
        }),
        required=False,
        help_text=
        _("The text can be left empty, instead you can upload scanned documents."
          ))
    files = forms.FileField(label=_("Scanned Letter"),
                            required=False,
                            validators=[validate_upload_document],
                            help_text=scan_help_text,
                            widget=forms.FileInput(attrs={'multiple': True}))
    FIELD_ORDER = ['public_body', 'date', 'subject', 'text', 'files']

    def __init__(self, *args, **kwargs):
        self.foirequest = kwargs.pop('foirequest')
        super(PostalBaseForm, self).__init__(*args, **kwargs)
        self.fields['public_body'].label = self.PUBLIC_BODY_LABEL
        self.fields['public_body'].initial = self.foirequest.public_body
        self.order_fields(self.FIELD_ORDER)

    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_files(self):
        if 'files' not in self.files:
            return self.cleaned_data['files']
        files = self.files.getlist('files')
        names = set()
        for file in files:
            validate_upload_document(file)
            name = self.make_filename(file.name)
            if name in names:
                # FIXME: dont make this a requirement
                raise forms.ValidationError(
                    _('Upload files must have distinct names'))
            names.add(name)
        return self.cleaned_data['files']

    def clean(self):
        cleaned_data = self.cleaned_data
        text = cleaned_data.get("text")
        if 'files' in self.files:
            files = self.files.getlist('files')
        else:
            files = None
        if not (text or files):
            raise forms.ValidationError(
                _("You need to provide either the letter text or a scanned document."
                  ))
        return cleaned_data

    def save(self):
        foirequest = self.foirequest
        message = FoiMessage(
            request=foirequest,
            is_postal=True,
        )
        # TODO: Check if timezone support is correct
        date = datetime.datetime.combine(self.cleaned_data['date'],
                                         datetime.time())
        message.timestamp = timezone.get_current_timezone().localize(date)
        message.subject = self.cleaned_data.get('subject', '')
        message.subject_redacted = message.redact_subject()[:250]
        message.plaintext = ""
        if self.cleaned_data.get('text'):
            message.plaintext = self.cleaned_data.get('text')
        message.plaintext_redacted = message.get_content()
        message = self.contribute_to_message(message)
        message.save()
        foirequest.last_message = message.timestamp
        foirequest.status = 'awaiting_classification'
        foirequest.save()
        foirequest.add_postal_reply.send(sender=foirequest)

        if self.cleaned_data.get('files'):
            self.save_attachments(self.files.getlist('files'), message)
        return message
Ejemplo n.º 10
0
class SiteProfileForm(forms.ModelForm):

    class Meta:
        model = SiteProfile
        exclude = ['create_date', 'edit_date']

    map = forms.CharField(widget=GoogleMapsWidget(
        attrs={'width': 700, 'height': 400, 'longitude': 'longitude', 'latitude': 'latitude'}), required=False)

    date_of_firstcontact = forms.DateField(widget=DatePicker.DateInput(), required=False)

    approval = forms.ChoiceField(
        choices=APPROVALS,
        initial='in progress',
        required=False,
    )

    def __init__(self, *args, **kwargs):

        # get the user object from request to check user permissions
        self.request = kwargs.pop('request')

        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-6'
        self.helper.form_error_title = 'Form Errors'
        self.helper.error_text_inline = True
        self.helper.help_text_inline = True
        self.helper.html5_required = True

        # Organize the fields in the site profile form using a layout class
        self.helper.layout = Layout(

            HTML("""<br/>"""),
            TabHolder(
                Tab('Profile',
                    Fieldset('Description',
                        'code', 'name', 'type', 'office',
                    ),
                    Fieldset('Contact Info',
                        'contact_leader', 'date_of_firstcontact', 'contact_number', 'num_members',
                    ),
                ),
                Tab('Location',
                    Fieldset('Places',
                        'country','province','district','village', Field('latitude', step="any"), Field('longitude', step="any"),
                    ),
                    Fieldset('Map',
                        'map',
                    ),
                ),
                Tab('Demographic Information',
                    Fieldset('Households',
                        'total_num_households','avg_household_size', 'male_0_14', 'female_0_14', 'male_15_24', 'female_15_24',
                        'male_25_59', 'female_25_59', 'male_over_60', 'female_over_60', 'total_population',
                    ),
                    Fieldset('Land',
                        'classify_land','total_land','total_agricultural_land','total_rainfed_land','total_horticultural_land',
                        'populations_owning_land', 'avg_landholding_size', 'households_owning_livestock','animal_type'
                    ),
                    Fieldset('Literacy',
                        'literate_males','literate_females','literacy_rate',
                    ),
                    Fieldset('Demographic Info Data Source',
                             'info_source'
                    ),
                ),
                 Tab('Approvals',
                    Fieldset('',
                        'approval','approved_by','filled_by',
                    ),
                ),

            ),
            FormActions(
                Submit('submit', 'Save', css_class='btn-default'),
                Reset('reset', 'Reset', css_class='btn-warning')
            ),

             HTML("""
                  <br/>
                  <div class='panel panel-default'>

                  <!-- Default panel contents -->
                  <div class='panel-heading'>Projects in this Site</div>
                    {% if getProjects %}
                      <!-- Table -->
                      <table class="table">
                       <tr>
                         <th>Project Name</th>
                         <th>Program</th>
                         <th>Activity Code</th>
                         <th>View</th>
                       </tr>

                    {% for item in getProjects %}
                       <tr>
                        <td>{{ item.project_name }}</td>
                        <td>{{ item.program.name }}</td>
                        <td>{{ item.activity_code }}</td>
                        <td><a target="_new" href='/activitydb/projectagreement_detail/{{ item.id }}/'>View</a>
                       </tr>
                    {% endfor %}
                     </table>
                    {% endif %}
                  </div>
             """),
        )

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

        #override the office queryset to use request.user for country
        countries = getCountry(self.request.user)
        self.fields['office'].queryset = Office.objects.filter(province__country__in=countries)
        self.fields['province'].queryset = Province.objects.filter(country__in=countries)
Ejemplo n.º 11
0
class ProjectCompleteForm(forms.ModelForm):

    class Meta:
        model = ProjectComplete
        fields = '__all__'

    map = forms.CharField(widget=GoogleMapsWidget(
        attrs={'width': 700, 'height': 400, 'longitude': 'longitude', 'latitude': 'latitude'}), required=False)

    expected_start_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    expected_end_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    actual_start_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    actual_end_date = forms.DateField(widget=DatePicker.DateInput(), required=False)

    program = forms.ModelChoiceField(queryset=Program.objects.filter(funding_status="Funded"))

    approval = forms.ChoiceField(
        choices=APPROVALS,
        initial='in progress',
        required=False,
    )

    budget_variance = forms.ChoiceField(
        choices=BUDGET_VARIANCE,
        initial='Over Budget',
        required=False,
    )

    def __init__(self, *args, **kwargs):
        #get the user object from request to check permissions
        self.request = kwargs.pop('request')
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-6'
        self.helper.form_error_title = 'Form Errors'
        self.helper.error_text_inline = True
        self.helper.help_text_inline = True
        self.helper.html5_required = True
        self.helper.layout = Layout(

            HTML("""<br/>"""),
            TabHolder(
                Tab('Executive Summary',
                    Fieldset('', 'program', 'project_proposal', 'project_agreement', 'activity_code', 'office', 'sector', 'project_name', 'project_activity','site'
                    ),
                    Fieldset(
                        'Dates',
                        'expected_start_date','expected_end_date', 'actual_start_date', 'actual_end_date',
                        PrependedText('on_time', ''), 'no_explanation',

                    ),
                ),
                Tab('Budget',
                    Fieldset(
                        '',
                        PrependedAppendedText('estimated_budget','$', '.00'), PrependedAppendedText('actual_budget','$', '.00'),'actual_cost_date', 'budget_variance', 'explanation_of_variance',
                        PrependedAppendedText('total_cost','$', '.00'), PrependedAppendedText('agency_cost','$', '.00'),
                        AppendedText('local_total_cost', '.00'), AppendedText('local_agency_cost', '.00'),'account_code','lin_code','exchange_rate','exchange_rate_date',
                    ),

                ),
                Tab('Budget Other',
                    Fieldset("Other Budget Contributions:",
                        MultiField(
                                "",
                                HTML("""

                                    <div class='panel panel-default'>
                                      <!-- Default panel contents -->
                                      <div class='panel-heading'>Budget Contributions</div>
                                      {% if getBudget %}
                                          <!-- Table -->
                                          <table class="table">
                                            <tr>
                                            <th>Contributor</th>
                                            <th>Description</th>
                                            <th>Proposed Value</th>
                                            <th>View</th>
                                            </tr>
                                            {% for item in getBudget %}
                                            <tr>
                                                <td>{{ item.contributor}}</td>
                                                <td>{{ item.contributor_description}}</td>
                                                <td>{{ item.proposed_value}}</td>
                                                <td><a class="output" data-toggle="modal" data-target="#myModal" href='/activitydb/budget_update/{{ item.id }}/'>View</a> | <a class="output" href='/activitydb/budget_delete/{{ item.id }}/' data-toggle="modal" data-target="#myModal" >Delete</a>
                                            </tr>
                                            {% endfor %}
                                          </table>
                                      {% endif %}
                                      <div class="panel-footer">
                                        <a class="output" data-toggle="modal" data-target="#myModal" href="/activitydb/budget_add/{{ pk }}">Add Budget Contribution</a>
                                      </div>
                                    </div>
                                """),
                        ),
                    ),

                ),
                Tab('Impact',
                    Fieldset(
                        '',
                        MultiField(
                            '',
                             HTML("""
                                    <div class='panel panel-default'>
                                      <!-- Default panel contents -->
                                      <div class='panel-heading'>Indicator Evidence</div>
                                      {% if getQuantitative %}
                                          <!-- Table -->
                                          <table class="table">
                                            <tr>
                                            <th>Targeted</th>
                                            <th>Achieved</th>
                                            <th>Description</th>
                                            <th>Indicator</th>
                                            <th>View</th>
                                            </tr>
                                            {% for item in getQuantitative %}
                                            <tr>
                                                <td>{{ item.targeted}}</td>
                                                <td>{{ item.achieved}}</td>
                                                <td>{{ item.description}}</td>
                                                <td><a href="/indicators/indicator_update/{{ item.indicator_id }}">{{ item.indicator}}<a/></td>
                                                <td><a class="output" data-toggle="modal" data-target="#myModal" href='/activitydb/quantitative_update/{{ item.id }}/'>Edit</a> | <a class="output" href='/activitydb/quantitative_delete/{{ item.id }}/' data-target="#myModal">Delete</a>
                                            </tr>
                                            {% endfor %}
                                          </table>
                                      {% endif %}
                                      <div class="panel-footer">
                                        <a class="output" data-toggle="modal" data-target="#myModal" href="/activitydb/quantitative_add/{{ pk }}">Add Quantitative Outputs</a>
                                      </div>
                                    </div>
                             """),
                        ),
                    ),
                    Fieldset(
                        '',AppendedText('progress_against_targets','%'),'actual_contribution','beneficiary_type', 'direct_beneficiaries', 'average_household_size', 'indirect_beneficiaries', 'capacity_built','quality_assured','issues_and_challenges', 'lessons_learned',
                    ),
                ),

                Tab('Approval',
                    Fieldset('Approval',
                             'approval', 'approved_by',
                             Field('approval_remarks', rows="3", css_class='input-xlarge')
                    ),
                ),
            ),

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

        #override the program queryset to use request.user for country
        countries = getCountry(self.request.user)
        self.fields['program'].queryset = Program.objects.filter(funding_status="Funded", country__in=countries)

        #override the office queryset to use request.user for country
        self.fields['office'].queryset = Office.objects.filter(province__country__in=countries)

        #override the community queryset to use request.user for country
        self.fields['site'].queryset = SiteProfile.objects.filter(country__in=countries)

        if not 'Approver' in self.request.user.groups.values_list('name', flat=True):
            self.fields['approval'].widget.attrs['disabled'] = "disabled"
            self.fields['approved_by'].widget.attrs['disabled'] = "disabled"
            self.fields['approval_submitted_by'].widget.attrs['disabled'] = "disabled"
            self.fields['approval_remarks'].widget.attrs['disabled'] = "disabled"
            self.fields['approval'].help_text = "Approval level permissions required"
Ejemplo n.º 12
0
class ProjectAgreementForm(forms.ModelForm):

    class Meta:
        model = ProjectAgreement
        fields = '__all__'

    map = forms.CharField(widget=GoogleMapsWidget(
        attrs={'width': 700, 'height': 400, 'longitude': 'longitude', 'latitude': 'latitude'}), required=False)

    expected_start_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    expected_end_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    estimation_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    reviewed_by_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    approved_by_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    me_reviewed_by_date = forms.DateField(label="M&E Reviewed by Date", widget=DatePicker.DateInput(), required=False)
    checked_by_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    estimated_by_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    finance_reviewed_by_date = forms.DateField(widget=DatePicker.DateInput(), required=False)
    exchange_rate_date = forms.DateField(widget=DatePicker.DateInput(), required=False)

    documentation_government_approval = forms.FileField(required=False)
    documentation_community_approval = forms.FileField(required=False)

    effect_or_impact = forms.CharField(help_text="Please do not include outputs and keep less than 120 words", widget=forms.Textarea, required=False)
    justification_background = forms.CharField(help_text="As someone would write a background and problem statement in a proposal, this should be described here. What is the situation in this community where the project is proposed and what is the problem facing them that this project will help solve", widget=forms.Textarea, required=False)
    justification_description_community_selection = forms.CharField(help_text="How was this community selected for this project. It may be it was already selected as part of the project (like CDP-2, KIWI-2), but others may need to describe, out of an entire cluster, why this community? This can't be just 'because they wanted it', or 'because they are poor.' It must refer to a needs assessment, some kind of selection criteria, maybe identification by the government, or some formal process.", widget=forms.Textarea, required=False)
    description_of_project_activities = forms.CharField(help_text="How was this community selected for this project. It may be it was already selected as part of the project (like CDP-2, KIWI-2), but others may need to describe, out of an entire cluster, why this community? This can't be just 'because they wanted it', or 'because they are poor.' It must refer to a needs assessment, some kind of selection criteria, maybe identification by the government, or some formal process.", widget=forms.Textarea, required=False)
    description_of_government_involvement = forms.CharField(help_text="This is an open-text field for describing the project. It does not need to be too long, but this is where you will be the main description and the main description that will be in the database.  Please make this a description from which someone can understand what this project is doing. You do not need to list all activities, such as those that will appear on your benchmark list. Just describe what you are doing. You should attach technical drawings, technical appraisals, bill of quantity or any other appropriate documentation", widget=forms.Textarea, required=False)
    documentation_government_approval = forms.CharField(help_text="Check the box if there IS documentation to show government request for or approval of the project. This should be attached to the proposal, and also kept in the program file.", widget=forms.Textarea, required=False)
    description_of_community_involvement = forms.CharField(help_text="How the community is involved in the planning, approval, or implementation of this project should be described. Indicate their approval (copy of a signed MOU, or their signed Project Prioritization request, etc.). But also describe how they will be involved in the implementation - supplying laborers, getting training, etc.", widget=forms.Textarea, required=False)

    approval = forms.ChoiceField(
        choices=APPROVALS,
        initial='in progress',
        required=False,
    )

    def __init__(self, *args, **kwargs):

        #get the user object from request to check permissions
        self.request = kwargs.pop('request')
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-6'
        self.helper.form_error_title = 'Form Errors'
        self.helper.error_text_inline = True
        self.helper.help_text_inline = True
        self.helper.html5_required = True
        self.helper.form_tag = True
        self.helper.layout = Layout(

            HTML("""<br/>"""),
            TabHolder(
                Tab('Executive Summary',
                    Fieldset('Program', 'activity_code', 'office', 'sector','program', 'project_name', 'project_activity',
                             'project_type', 'site','stakeholder','mc_staff_responsible','expected_start_date','expected_end_date',
                    ),

                ),
                Tab('Budget',
                     Fieldset(
                        'Budget',
                        PrependedAppendedText('total_estimated_budget','$', '.00'), PrependedAppendedText('mc_estimated_budget','$', '.00'),
                        AppendedText('local_total_estimated_budget', '.00'), AppendedText('local_mc_estimated_budget', '.00'),
                        'exchange_rate','exchange_rate_date','estimation_date','other_budget','account_code','lin_code',
                    ),
                    Fieldset("Other Budget Contributions:",
                        MultiField(
                                "",
                                HTML("""

                                    <div class='panel panel-default'>
                                      <!-- Default panel contents -->
                                      <div class='panel-heading'>Budget Contributions</div>
                                      {% if getBudget %}
                                          <!-- Table -->
                                          <table class="table">
                                            <tr>
                                            <th>Contributor</th>
                                            <th>Description</th>
                                            <th>Proposed Value</th>
                                            <th>View</th>
                                            </tr>
                                            {% for item in getBudget %}
                                            <tr>
                                                <td>{{ item.contributor}}</td>
                                                <td>{{ item.description_of_contribution}}</td>
                                                <td>{{ item.proposed_value}}</td>
                                                <td><a class="output" data-toggle="modal" data-target="#myModal" href='/activitydb/budget_update/{{ item.id }}/'>Edit</a> | <a class="output" href='/activitydb/budget_delete/{{ item.id }}/' data-toggle="modal" data-target="#myModal" >Delete</a>
                                            </tr>
                                            {% endfor %}
                                          </table>
                                      {% endif %}
                                      <div class="panel-footer">
                                        <a class="output" data-toggle="modal" data-target="#myModal" href="/activitydb/budget_add/{{ pk }}">Add Budget Contribution</a>
                                      </div>
                                    </div>
                                     """),
                        ),
                    ),

                ),

                Tab('Justification and Description',
                     Fieldset(
                        'Description',
                        Field('description_of_project_activities', rows="4", css_class='input-xlarge'),

                    ),
                    Fieldset(
                        'Justification',
                        Field('effect_or_impact',rows="4", css_class='input-xlarge', label="Anticipated Outcome and Goal"),
                    ),
                ),
                Tab('M&E',
                    Fieldset(
                        '',
                        MultiField(
                            '',
                             HTML("""
                                    <div class='panel panel-default'>
                                      <!-- Default panel contents -->
                                      <div class='panel-heading'>Indicator Evidence</div>
                                      {% if getQuantitative %}
                                          <!-- Table -->
                                          <table class="table">
                                            <tr>
                                            <th>Targeted</th>
                                            <th>Description</th>
                                            <th>Indicator</th>
                                            <th>View</th>
                                            </tr>
                                            {% for item in getQuantitative %}
                                            <tr>
                                                <td>{{ item.targeted}}</td>
                                                <td>{{ item.description}}</td>
                                                <td><a href="/indicators/indicator_update/{{ item.indicator_id }}">{{ item.indicator}}<a/></td>
                                                <td><a class="output" data-toggle="modal" data-target="#myModal" href='/activitydb/quantitative_update/{{ item.id }}/'>Edit</a> | <a class="output" href='/activitydb/quantitative_delete/{{ item.id }}/' data-target="#myModal">Delete</a>
                                            </tr>
                                            {% endfor %}
                                          </table>
                                      {% endif %}
                                      <div class="panel-footer">
                                        <a class="output" data-toggle="modal" data-target="#myModal" href="/activitydb/quantitative_add/{{ pk }}">Add Quantitative Outputs</a>
                                      </div>
                                    </div>
                                     """),

                             HTML("""

                                    <div class='panel panel-default'>
                                      <!-- Default panel contents -->
                                      <div class='panel-heading'>Benchmarks</div>
                                      {% if getBenchmark %}
                                          <!-- Table -->
                                          <table class="table">
                                            <tr>
                                            <th>Percent Complete</th>
                                            <th>Percent Cumlative Completion</th>
                                            <th>Description</th>
                                            <th>View</th>
                                            </tr>
                                            {% for item in getBenchmark %}
                                            <tr>
                                                <td>{{ item.percent_complete}}</td>
                                                <td>{{ item.percent_cumulative}}</td>
                                                <td>{{ item.description}}</td>
                                                <td><a class="benchmarks" data-toggle="modal" data-target="#myModal" href='/activitydb/benchmark_update/{{ item.id }}/'>Edit</a> | <a class="benchmarks" href='/activitydb/benchmark_delete/{{ item.id }}/' data-toggle="modal" data-target="#myModal">Delete</a></td>
                                            </tr>
                                            {% endfor %}
                                          </table>
                                      {% endif %}
                                      <div class="panel-footer">
                                        <a class="benchmarks" data-toggle="modal" data-target="#myModal" href="/activitydb/benchmark_add/{{ pk }}">Add Benchmarks</a>
                                      </div>
                                    </div>

                                     """),

                            'capacity',
                        ),
                    ),
                    Fieldset(
                        '',
                        MultiField(
                            '',
                            HTML("""
                                    <br/>
                                    <div class='panel panel-default'>
                                      <!-- Default panel contents -->
                                      <div class='panel-heading'>Monitoring</div>
                                      {% if getMonitor %}
                                          <!-- Table -->
                                          <table class="table">
                                            <tr>
                                            <th>Person Responsible</th>
                                            <th>Frequency</th>
                                            <th>Type</th>
                                            <th>View</th>
                                            </tr>
                                            {% for item in getMonitor %}
                                            <tr>
                                                <td>{{ item.responsible_person}}</td>
                                                <td>{{ item.frequency}}</td>
                                                <td>{{ item.type}}</td>
                                                <td><a class="monitoring" data-toggle="modal" data-target="#myModal" href='/activitydb/monitor_update/{{ item.id }}/'>Edit</a> | <a class="monitoring" href='/activitydb/monitor_delete/{{ item.id }}/' data-toggle="modal" data-target="#myModal">Delete</a>
                                            </tr>
                                            {% endfor %}
                                          </table>
                                      {% endif %}
                                      <div class="panel-footer">
                                        <a class="monitoring" data-toggle="modal" data-target="#myModal" href="/activitydb/monitor_add/{{ pk }}">Add Monitoring Data</a>
                                      </div>
                                    </div>
                                     """),

                            'evaluate',
                        ),
                    ),
                ),

                Tab('Approval',
                    Fieldset('Approval',
                             'approval', 'estimated_by', 'reviewed_by',
                             'finance_reviewed_by','finance_reviewed_by_date','me_reviewed_by','me_reviewed_by_date','approved_by', 'approved_by_date',
                             Field('approval_remarks', rows="3", css_class='input-xlarge')
                    ),
                ),
            ),

            FormActions(
                Submit('submit', 'Save', css_class='btn-default'),
                Reset('reset', 'Reset', css_class='btn-warning')
            ),


            HTML("""<br/>"""),

            Fieldset(
                'Project Files',
                MultiField(
                    '',
                    HTML("""

                            <div class='panel panel-default'>
                              <!-- Default panel contents -->
                              <div class='panel-heading'>Documentation</div>
                              {% if getMonitor %}
                                  <!-- Table -->
                                  <table class="table">
                                    <tr>
                                    <th>Name</th>
                                    <th>Link(URL)</th>
                                    <th>Description</th>
                                    <th>&nbsp;</th>
                                    </tr>
                                    {% for item in getDocuments %}
                                    <tr>
                                        <td>{{ item.name}}</td>
                                        <td><a href="{{ item.url}}" target="_new">{{ item.url}}</a></td>
                                        <td>{{ item.description}}</td>
                                        <td><a class="monitoring" data-toggle="modal" data-target="#myModal" href='/activitydb/documentation_agreement_update/{{ item.id }}/{{ pk }}/'>Edit</a> | <a class="monitoring" href='/activitydb/documentation_agreement_delete/{{ item.id }}/' data-toggle="modal" data-target="#myModal">Delete</a>
                                    </tr>
                                    {% endfor %}
                                  </table>
                              {% endif %}
                              <div class="panel-footer">
                                <a class="documents" data-toggle="modal" data-target="#myModal" href="/activitydb/documentation_agreement_add/{{ pk }}">Add Documentation</a>
                              </div>
                            </div>
                             """),
                ),
            ),

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

        #override the program queryset to use request.user for country
        countries = getCountry(self.request.user)
        self.fields['program'].queryset = Program.objects.filter(funding_status="Funded", country__in=countries).distinct()

        #override the office queryset to use request.user for country
        self.fields['office'].queryset = Office.objects.filter(province__country__in=countries)

        #override the site queryset to use request.user for country
        self.fields['site'].queryset = SiteProfile.objects.filter(country__in=countries)

        #override the stakeholder queryset to use request.user for country
        self.fields['stakeholder'].queryset = Stakeholder.objects.filter(country__in=countries)

        if not 'Approver' in self.request.user.groups.values_list('name', flat=True):
            self.fields['approval'].widget.attrs['disabled'] = "disabled"
            self.fields['approved_by'].widget.attrs['disabled'] = "disabled"
            self.fields['approval_remarks'].widget.attrs['disabled'] = "disabled"
            self.fields['approval'].help_text = "Approval level permissions required"
Ejemplo n.º 13
0
class BankTransactionListForm(forms.Form):

    label = forms.CharField(
        max_length=255,
        required=False,
        widget=forms.TextInput(attrs={
            'placeholder': ugettext_lazy('Label'),
        }))

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

    amount_min = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        localize=True,
        required=False,
        widget=forms.NumberInput(
            attrs={
                'placeholder': ugettext_lazy('Minimum amount'),
            }),
    )
    amount_max = forms.DecimalField(
        max_digits=10,
        decimal_places=2,
        localize=True,
        required=False,
        widget=forms.NumberInput(
            attrs={
                'placeholder': ugettext_lazy('Maximum amount'),
            }),
    )

    status = forms.ChoiceField(
        choices=(('', ugettext_lazy('Status?')), ) + BankTransaction.STATUSES,
        initial='',
        required=False,
    )
    reconciled = forms.NullBooleanField(required=False)
    tags = forms.ModelMultipleChoiceField(
        queryset=BankTransactionTag.objects.none(), required=False)

    operation = forms.ChoiceField(
        choices=(),
        required=False,
    )

    def __init__(self, user, bt_ids, submit, *args, **kwargs):
        super(BankTransactionListForm, self).__init__(*args, **kwargs)

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

        for pk in bt_ids:
            self.fields['banktransaction_' + str(pk)] = forms.BooleanField(
                required=False,
                widget=forms.CheckboxInput(attrs={'data-id': pk}))

        choices = ()
        if user.has_perm('banktransactions.change_banktransaction'):
            choices += (
                ('reconcile', _('Reconcile')),
                ('unreconcile', _('Unreconcile')),
            )
        if user.has_perm('banktransactions.delete_banktransaction'):
            choices += (('delete', _('Delete')), )
        if choices:
            self.fields['operation'].choices = choices

        self._submit = submit

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

        if self._submit == 'filter':
            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',
                )

            amount_min = cleaned_data.get('amount_min', None)
            amount_max = cleaned_data.get('amount_max', None)
            if (amount_min is not None and amount_max is not None
                    and amount_min > amount_max):

                raise forms.ValidationError(
                    _("Minimum amount could not be greater than maximum "
                      "amount."),
                    code='amount_min_greater',
                )

        if self._submit == 'action' and cleaned_data['operation']:
            ids = set()
            for name, value in cleaned_data.items():
                if name.startswith('banktransaction_') and value:
                    ids.add(int(name[len('banktransaction_'):]))
            if not ids:
                raise forms.ValidationError(
                    _('To apply operations, you need to select some bank '
                      'transactions.'),
                    code='no_id',
                )
            cleaned_data['banktransactions'] = ids

        return cleaned_data
Ejemplo n.º 14
0
class StudentSignUpForm(UserCreationForm):
    # Declare user option fields to form
    first_name = forms.CharField(
        required=True,
        widget=forms.TextInput(attrs={'placeholder': 'First name'}))
    other_name = forms.CharField(
        required=True,
        widget=forms.TextInput(attrs={'placeholder': 'Other name'}))
    last_name = forms.CharField(
        required=True,
        widget=forms.TextInput(attrs={'placeholder': 'Surname'}))
    birth_place = forms.ChoiceField(required=True, choices=STATES)
    sex = forms.ChoiceField(required=True, choices=GENDER)
    birth_date = forms.DateField(required=True, widget=forms.DateInput)
    email = forms.EmailField(
        widget=forms.EmailInput(attrs={'placeholder': 'Enter email address'}),
        required=True)
    phone = forms.CharField(
        required=True,
        widget=forms.PhoneNumberInput(attrs={'placeholder': 'Mobile Number'}))
    address = forms.CharField(
        required=False,
        widget=forms.TextInput(
            attrs={'placeholder': 'House/Street/City/Town '}),
        max_length=100)
    faculty = forms.ModelChoiceField(queryset=Faculty.objects.all())

    # Add Extra Student options fields to form
    study_centre = forms.ModelChoiceField(queryset=Studycentre.objects.all(),
                                          required=False)
    programme = forms.ModelChoiceField(queryset=Programme.objects.all())
    department = forms.ModelChoiceField(queryset=Department.objects.all())
    level = forms.ChoiceField(choices=LEVEL, required=True)

    class Meta:
        model = User
        fields = (
            'first_name',
            'other_name',
            'last_name',
            'sex',
            'birth_place',
            'address',
            'phone',
            'email',
            'faculty',
            'department',
            'level',
            'programme',
            'study_centre',
            'birth_date',
        )

    # Add placeholders to UserCreationForm password fields
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['password1'].widget.attrs.update(
            {'placeholder': 'Choose A Password'})
        self.fields['password2'].widget.attrs.update(
            {'placeholder': 'Verify Password'})

        # Filter Department choice by selected faculty
        self.fields['department'].queryset = Department.objects.none()
        self.fields['programme'].queryset = Programme.objects.none()

        for field_name in ['password1', 'password2']:
            self.fields[field_name].help_text = None

        if 'faculty' in self.data:
            try:
                faculty_id = int(self.data.get('faculty'))
                self.fields['department'].queryset = Department.objects.filter(
                    faculty_id=faculty_id).exclude(
                        name='General Studies').order_by('name')
            except (ValueError, TypeError):
                pass  # invalid input from the client; ignore and fallback to empty department queryset
        elif self.instance.pk:
            self.fields[
                'department'].queryset = self.instance.faculty.department_set.order_by(
                    'name')

        if 'department' in self.data:
            try:
                department_id = int(self.data.get('department'))
                self.fields['programme'].queryset = Programme.objects.filter(
                    department_id=department_id).order_by('name')
            except (ValueError, TypeError):
                pass  # invalid input from the client; ignore and fallback to empty department queryset
        elif self.instance.pk:
            self.fields[
                'programme'].queryset = self.instance.department.programme_set.order_by(
                    'name')

    # Check if inputted email has not been used by another user
    def clean_email(self):
        email = self.cleaned_data['email']
        check = User.objects.values('email')
        if email in check:
            msg = 'this email has been used!'
            self.add_error('email', msg)
        return email

    @transaction.atomic
    def save(self):
        user = super().save(commit=False)

        while True:
            gen_matric = 'stu' + str(random.randint(10000, 50000))
            if not Student.objects.filter(user__username=gen_matric).exists():
                user.username = gen_matric
                break

        user.is_student = True
        user.save()
        # retrieve student info from relevant form field
        study_centre = self.cleaned_data.get('study_centre')
        programme = self.cleaned_data.get('programme')
        department = self.cleaned_data.get('department')
        level = self.cleaned_data.get('level')
        # Create student object with user id
        Student.objects.create(user=user,
                               study_centre=study_centre,
                               programme=programme,
                               department=department,
                               level=level)
        return user