Esempio n. 1
0
class StockImportForm(BetterBsForm):
    """A form for importing stock values from Excel"""

    xls_file = forms.FileField(
        label=_('Excel file'),
        help_text=
        _('Same format than the export file. It will update the purchase price, stock count and threshold'
          ))
Esempio n. 2
0
class PostalAttachmentForm(AttachmentSaverMixin, forms.Form):
    files = forms.FileField(label=_("Scanned Document"),
                            help_text=PostalBaseForm.scan_help_text,
                            validators=[validate_upload_document])

    def save(self, message):
        result = self.save_attachments(self.files.getlist('files'),
                                       message,
                                       replace=True)
        return result
Esempio n. 3
0
class NewTopicForm(forms.ModelForm):
    subject = forms.CharField(widget=forms.TextInput(
        attrs={'placeholder': 'Add Subject'}))
    files = forms.FileField(required=False)

    class Meta:
        model = Topic
        fields = ['subject', 'course', 'message', 'files']

    # Filter topic courses list for appointed lecturer
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super().__init__(*args, **kwargs)
        self.fields["course"].queryset = Course.objects.filter(
            lecturer=self.request.user.lecturer)
Esempio n. 4
0
class BaseCaseVersionForm(forms.Form):
    """Base form class for AddCaseForm and EditCaseVersionForm."""
    name = forms.CharField(max_length=200)
    description = forms.CharField(required=False, widget=mtforms.BareTextarea)

    add_attachment = forms.FileField(required=False)


    def __init__(self, *args, **kwargs):
        """Initialize BaseCaseVersionForm, including StepFormSet."""
        super(BaseCaseVersionForm, self).__init__(*args, **kwargs)

        self.steps_formset = StepFormSet(
            data=self.data or None,
            instance=getattr(self, "instance", None),
            )


    def is_valid(self):
        """The form and the steps formset must both be valid."""
        return self.steps_formset.is_valid() and super(
            BaseCaseVersionForm, self).is_valid()


    def save_attachments(self, caseversion):
        # @@@ convert into a modelmultiplechoicefield widget?
        delete_ids = set(self.data.getlist("remove-attachment"))

        # TODO!
        # With upgrading to Django 1.5, we lost the ability to do a
        # queryset delete on the m2m field. E.g.
        # Doing caseversion.attachments.filter(id__in=delete_ids).delete()
        # entirely stopped working.
        # This long-form does though.
        [x.delete() for x in caseversion.attachments.filter(id__in=delete_ids)]

        if self.files:  # if no files, it's a plain dict, has no getlist
            for uf in self.files.getlist("add_attachment"):
                model.CaseAttachment.objects.create(
                    attachment=uf,
                    name=uf.name,
                    caseversion=caseversion,
                    user=self.user,
                    )
Esempio n. 5
0
class UnsubscribeContactsImportForm(forms.Form):
    """A form for uploading a file"""
    input_file = forms.FileField()
Esempio n. 6
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
Esempio n. 7
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"
Esempio n. 8
0
class VivaRealUploadFileForm(forms.Form):
    """
    Override the default authentication
    """
    vivarealfile = forms.FileField(label='Select a vivareal file')