Skip to content

Index

hypha.apply.projects.forms

BatchUpdateInvoiceStatusForm

BatchUpdateInvoiceStatusForm(*args, **kwargs)

Bases: Form

Source code in hypha/apply/projects/forms/payment.py
def __init__(self, *args, **kwargs):
    self.user = kwargs.pop("user")
    super().__init__(*args, **kwargs)
    if self.user.is_apply_staff:
        self.fields["invoice_action"].choices = [
            (DECLINED, get_invoice_status_display_value(DECLINED))
        ]
    elif self.user.is_finance:
        self.fields["invoice_action"].choices = [
            (DECLINED, get_invoice_status_display_value(DECLINED)),
            (PAID, get_invoice_status_display_value(PAID)),
            (PAYMENT_FAILED, get_invoice_status_display_value(PAYMENT_FAILED)),
        ]

invoice_action class-attribute instance-attribute

invoice_action = ChoiceField(label=gettext_lazy('Status'))

invoices class-attribute instance-attribute

invoices = CharField(widget=HiddenInput(attrs={'class': 'js-invoices-id'}))

user instance-attribute

user = pop('user')

clean_invoices

clean_invoices()
Source code in hypha/apply/projects/forms/payment.py
def clean_invoices(self):
    value = self.cleaned_data["invoices"]
    invoice_ids = [int(invoice) for invoice in value.split(",")]
    return Invoice.objects.filter(id__in=invoice_ids)

ChangeInvoiceStatusForm

ChangeInvoiceStatusForm(*args, **kwargs)

Bases: ModelForm

Source code in hypha/apply/projects/forms/payment.py
def __init__(self, *args, **kwargs):
    user = kwargs.pop("user")
    instance = kwargs.pop("instance")
    super().__init__(*args, **kwargs, instance=instance)
    invoice_choices = get_invoice_possible_transition_for_user(
        user, invoice=instance
    )

    self.initial["comment"] = ""
    if len(invoice_choices) > 4:
        self.fields["status"] = forms.TypedChoiceField(choices=invoice_choices)
    else:
        self.fields["status"].choices = invoice_choices

name_prefix class-attribute instance-attribute

name_prefix = 'change_invoice_status_form'

paid_date class-attribute instance-attribute

paid_date = DateField(required=False)

Meta

fields class-attribute instance-attribute
fields = ['status', 'paid_date', 'comment']
model class-attribute instance-attribute
model = Invoice
widgets class-attribute instance-attribute
widgets = {'status': RadioSelect}

CreateInvoiceForm

CreateInvoiceForm(user=None, *args, **kwargs)

Bases: FileFormMixin, InvoiceBaseForm

Source code in hypha/apply/projects/forms/payment.py
def __init__(self, user=None, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.initial["message_for_pm"] = ""

document class-attribute instance-attribute

document = SingleFileField(label=gettext_lazy('Invoice file'), required=True, help_text=gettext_lazy('The invoice must be a PDF.'))

supporting_documents class-attribute instance-attribute

supporting_documents = MultiFileField(required=False, help_text=gettext_lazy('Files that are related to the invoice. They could be xls, microsoft office documents, open office documents, pdfs, txt files.'))

field_order class-attribute instance-attribute

field_order = ['invoice_number', 'invoice_amount', 'invoice_date', 'document', 'supporting_documents', 'message_for_pm']

Meta

fields class-attribute instance-attribute
fields = ['invoice_number', 'invoice_amount', 'invoice_date', 'document', 'message_for_pm']
model class-attribute instance-attribute
model = Invoice

save

save(commit=True)
Source code in hypha/apply/projects/forms/payment.py
def save(self, commit=True):
    invoice = super().save(commit=commit)

    supporting_documents = self.cleaned_data["supporting_documents"] or []

    SupportingDocument.objects.bulk_create(
        SupportingDocument(invoice=invoice, document=document)
        for document in supporting_documents
    )

    return invoice

EditInvoiceForm

EditInvoiceForm(user=None, *args, **kwargs)

Bases: FileFormMixin, InvoiceBaseForm

Source code in hypha/apply/projects/forms/payment.py
def __init__(self, user=None, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.initial["message_for_pm"] = ""

document class-attribute instance-attribute

document = SingleFileField(label=gettext_lazy('Invoice File'), required=True)

supporting_documents class-attribute instance-attribute

supporting_documents = MultiFileField(required=False)

field_order class-attribute instance-attribute

field_order = ['invoice_number', 'invoice_amount', 'invoice_date', 'document', 'supporting_documents', 'message_for_pm']

Meta

fields class-attribute instance-attribute
fields = ['invoice_number', 'invoice_amount', 'invoice_date', 'document', 'message_for_pm']
model class-attribute instance-attribute
model = Invoice

save

save(commit=True)
Source code in hypha/apply/projects/forms/payment.py
@transaction.atomic
def save(self, commit=True):
    invoice = super().save(commit=commit)
    not_deleted_original_filenames = [
        file["name"]
        for file in json.loads(self.cleaned_data["supporting_documents-uploads"])
    ]
    for f in invoice.supporting_documents.all():
        if f.document.name not in not_deleted_original_filenames:
            f.document.delete()
            f.delete()

    for f in self.cleaned_data["supporting_documents"]:
        if not isinstance(f, FieldFile):
            try:
                SupportingDocument.objects.create(invoice=invoice, document=f)
            finally:
                f.close()
    return invoice

SelectDocumentForm

SelectDocumentForm(existing_files, *args, **kwargs)

Bases: ModelForm

Source code in hypha/apply/projects/forms/payment.py
def __init__(self, existing_files, *args, **kwargs):
    super().__init__(*args, **kwargs)

    self.files = existing_files

    choices = [(f.url, f.filename) for f in self.files]

    self.fields["document"].choices = choices

document class-attribute instance-attribute

document = ChoiceField(label=gettext_lazy('Document'), widget=Select(attrs={'id': 'from_submission'}))

files instance-attribute

files = existing_files

Meta

model class-attribute instance-attribute
model = PacketFile
fields class-attribute instance-attribute
fields = ['category', 'document']

clean_document

clean_document()
Source code in hypha/apply/projects/forms/payment.py
def clean_document(self):
    file_url = self.cleaned_data["document"]
    for file in self.files:
        if file.url == file_url:
            new_file = ContentFile(file.read())
            new_file.name = file.filename
            return new_file
    raise forms.ValidationError(_("File not found on submission"))

save

save(*args, **kwargs)
Source code in hypha/apply/projects/forms/payment.py
@transaction.atomic()
def save(self, *args, **kwargs):
    return super().save(*args, **kwargs)

ApproveContractForm

ApproveContractForm(*args, instance, **kwargs)

Bases: Form

Source code in hypha/apply/projects/forms/project.py
def __init__(self, *args, instance, **kwargs):
    super().__init__(*args, **kwargs)
    self.instance = instance
    if instance:
        self.fields["id"].initial = instance.id

id class-attribute instance-attribute

id = IntegerField(widget=HiddenInput())

instance instance-attribute

instance = instance

clean_id

clean_id()
Source code in hypha/apply/projects/forms/project.py
def clean_id(self):
    if self.has_changed():
        raise forms.ValidationError(
            _("Something changed before your approval please re-review")
        )

clean

clean()
Source code in hypha/apply/projects/forms/project.py
def clean(self):
    if not self.instance:
        raise forms.ValidationError(
            _("The contract you were trying to approve has already been approved")
        )

    if not self.instance.signed_by_applicant:
        raise forms.ValidationError(_("You can only approve a signed contract"))

    super().clean()

save

save(*args, **kwargs)
Source code in hypha/apply/projects/forms/project.py
def save(self, *args, **kwargs):
    self.instance.save()
    return self.instance

ApproversForm

ApproversForm(*args, user=None, **kwargs)

Bases: ModelForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, *args, user=None, **kwargs):
    from hypha.apply.activity.adapters.utils import get_users_for_groups

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

    for paf_reviewer_role in PAFReviewersRole.objects.all():
        users = get_users_for_groups(
            list(paf_reviewer_role.user_roles.all()), exact_match=True
        )
        approval = PAFApprovals.objects.filter(
            project=self.instance, paf_reviewer_role=paf_reviewer_role
        )
        if approval:
            initial_user = approval.first().user
        self.fields[slugify(paf_reviewer_role.label)] = forms.ModelChoiceField(
            queryset=users,
            required=False,
            blank=True,
            label=paf_reviewer_role.label,
            initial=initial_user if approval else None,
            disabled=approval.first().approved if approval.first() else False,
            # using approval.first() as condition for existing projects
        )

Meta

fields class-attribute instance-attribute
fields = ['id']
model class-attribute instance-attribute
model = Project
widgets class-attribute instance-attribute
widgets = {'id': HiddenInput()}

save

save(commit=True)
Source code in hypha/apply/projects/forms/project.py
def save(self, commit=True):
    # add users as PAFApprovals
    for paf_reviewer_role in PAFReviewersRole.objects.all():
        assigned_user = self.cleaned_data[slugify(paf_reviewer_role.label)]
        paf_approvals = PAFApprovals.objects.filter(
            project=self.instance, paf_reviewer_role=paf_reviewer_role
        )
        if not paf_approvals.exists():
            PAFApprovals.objects.create(
                project=self.instance,
                paf_reviewer_role=paf_reviewer_role,
                user=assigned_user if assigned_user else None,
                approved=False,
            )
        elif not paf_approvals.first().approved:
            paf_approval = paf_approvals.first()
            paf_approval.user = assigned_user if assigned_user else None
            paf_approval.save()
    return super().save(commit=True)

AssignApproversForm

AssignApproversForm(*args, user=None, **kwargs)

Bases: ModelForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, *args, user=None, **kwargs):
    from hypha.apply.activity.adapters.utils import get_users_for_groups

    super().__init__(*args, **kwargs)
    self.user = user

    paf_approval = get_latest_project_paf_approval_via_roles(
        project=self.instance, roles=user.groups.all()
    )

    if paf_approval:
        current_paf_reviewer_role = paf_approval.paf_reviewer_role

        users = get_users_for_groups(
            list(current_paf_reviewer_role.user_roles.all()), exact_match=True
        )

        self.fields[slugify(current_paf_reviewer_role.label)] = (
            forms.ModelChoiceField(
                queryset=users,
                required=False,
                blank=True,
                label=current_paf_reviewer_role.label,
                initial=paf_approval.user,
                disabled=paf_approval.approved,
            )
        )

user instance-attribute

user = user

Meta

fields class-attribute instance-attribute
fields = ['id']
model class-attribute instance-attribute
model = Project
widgets class-attribute instance-attribute
widgets = {'id': HiddenInput()}

save

save(commit=True)
Source code in hypha/apply/projects/forms/project.py
def save(self, commit=True):
    paf_approval = get_latest_project_paf_approval_via_roles(
        project=self.instance, roles=self.user.groups.all()
    )

    current_paf_reviewer_role = paf_approval.paf_reviewer_role
    assigned_user = self.cleaned_data[slugify(current_paf_reviewer_role.label)]

    if not paf_approval.approved:
        paf_approval.user = assigned_user if assigned_user else None
        paf_approval.save()

    return super().save(commit=True)

ChangePAFStatusForm

ChangePAFStatusForm(*args, user=None, instance=None, **kwargs)

Bases: ModelForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, *args, user=None, instance=None, **kwargs):
    super().__init__(*args, **kwargs, instance=instance)
    self.fields["paf_status"].widget.attrs["class"] = "grid--status-update"

name_prefix class-attribute instance-attribute

name_prefix = 'change_paf_status_form'

paf_status class-attribute instance-attribute

paf_status = ChoiceField(label=gettext_lazy('Project form status'), choices=PAF_STATUS_CHOICES, widget=RadioSelect())

comment class-attribute instance-attribute

comment = CharField(required=False, widget=Textarea)

Meta

fields class-attribute instance-attribute
fields = ['paf_status', 'comment']
model class-attribute instance-attribute
model = Project

ChangeProjectStatusForm

ChangeProjectStatusForm(instance, user, *args, **kwargs)

Bases: ModelForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, instance, user, *args, **kwargs):
    super().__init__(*args, **kwargs, instance=instance)
    status_field = self.fields["status"]
    possible_status_transitions = {
        INVOICING_AND_REPORTING: filter_request_choices([CLOSING, COMPLETE]),
        CLOSING: filter_request_choices([INVOICING_AND_REPORTING, COMPLETE]),
        COMPLETE: filter_request_choices([INVOICING_AND_REPORTING, CLOSING]),
    }
    status_field.choices = possible_status_transitions.get(instance.status, [])

name_prefix class-attribute instance-attribute

name_prefix = 'change_project_status_form'

comment class-attribute instance-attribute

comment = CharField(required=False, widget=Textarea)

Meta

fields class-attribute instance-attribute
fields = ['status', 'comment']
model class-attribute instance-attribute
model = Project

ProjectCreateForm

ProjectCreateForm(*args, instance=None, **kwargs)

Bases: Form

Source code in hypha/apply/projects/forms/project.py
def __init__(self, *args, instance=None, **kwargs):
    super().__init__(*args, **kwargs)

    if instance:
        self.fields["submission"].initial = instance.id

    # Update lead field queryset
    lead_field = self.fields["project_lead"]
    qwargs = Q(groups__name=STAFF_GROUP_NAME) | Q(is_superuser=True)
    lead_field.queryset = lead_field.queryset.filter(qwargs).distinct()
    if instance:
        lead_field.initial = instance.lead

submission class-attribute instance-attribute

submission = ModelChoiceField(queryset=filter(project__isnull=True), widget=HiddenInput())

project_lead class-attribute instance-attribute

project_lead = ModelChoiceField(label=gettext_lazy('Select Project Lead'), queryset=all())

clean_project_lead

clean_project_lead()
Source code in hypha/apply/projects/forms/project.py
def clean_project_lead(self):
    project_lead = self.cleaned_data["project_lead"]
    if not project_lead:
        raise forms.ValidationError(_("Project lead is a required field"))
    return project_lead

save

save(*args, **kwargs)
Source code in hypha/apply/projects/forms/project.py
def save(self, *args, **kwargs):
    submission = self.cleaned_data["submission"]
    lead = self.cleaned_data["project_lead"]
    return Project.create_from_submission(submission, lead=lead)

ProjectForm

ProjectForm(*args, extra_fields=None, **kwargs)

Bases: StreamBaseForm, ModelForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, *args, extra_fields=None, **kwargs):
    super().__init__(*args, **kwargs)

Meta

fields class-attribute instance-attribute
fields = ['title']
model class-attribute instance-attribute
model = Project
widgets class-attribute instance-attribute
widgets = {'title': HiddenInput()}

swap_fields_for_display

swap_fields_for_display(func)
Source code in hypha/apply/stream_forms/forms.py
def swap_fields_for_display(func):
    def wrapped(self, *args, **kwargs):
        # Replaces the form fields with the display fields
        # should only add new streamblocks and wont affect validation
        fields = self.fields.copy()
        self.fields = self.display
        yield from func(self, *args, **kwargs)
        self.fields = fields

    return wrapped

hidden_fields

hidden_fields()
Source code in hypha/apply/stream_forms/forms.py
def hidden_fields(self):
    # No hidden fields are returned by default because of MixedFieldMetaclass
    return [self[f] for f in self.fields.keys() if self[f].is_hidden]

delete_temporary_files

delete_temporary_files()

Overridden method of django_file_form's FileFormMixin, to handle multiple forms on the same page.

Source code in hypha/apply/stream_forms/forms.py
def delete_temporary_files(self):
    """
    Overridden method of django_file_form's FileFormMixin, to handle multiple forms on the same page.
    """
    form_id = self.data.getlist(self.add_prefix("form_id"))

    if not form_id:
        return

    form_id = form_id[0]
    for field_name, field in self.fields.items():
        if hasattr(field, "delete_file_data"):
            prefixed_field_name = self.add_prefix(field_name)
            field.delete_file_data(prefixed_field_name, form_id)

clean

clean()
Source code in hypha/apply/projects/forms/project.py
def clean(self):
    cleaned_data = super().clean()
    cleaned_data["form_data"] = {
        key: value
        for key, value in cleaned_data.items()
        if key not in self._meta.fields
    }
    return cleaned_data

save

save(*args, **kwargs)
Source code in hypha/apply/projects/forms/project.py
def save(self, *args, **kwargs):
    self.instance.form_fields = kwargs.pop("paf_form_fields", {})
    self.instance.form_data = {
        field: self.cleaned_data[field]
        for field in self.instance.question_field_ids
        if field in self.cleaned_data
    }
    self.instance.process_file_data(self.cleaned_data)
    self.instance.user_has_updated_details = True
    return super().save(*args, **kwargs)

ProjectSOWForm

ProjectSOWForm(*args, extra_fields=None, **kwargs)

Bases: StreamBaseForm, ModelForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, *args, extra_fields=None, **kwargs):
    super().__init__(*args, **kwargs)

Meta

fields class-attribute instance-attribute
fields = ['project']
model class-attribute instance-attribute
model = ProjectSOW
widgets class-attribute instance-attribute
widgets = {'project': HiddenInput()}

swap_fields_for_display

swap_fields_for_display(func)
Source code in hypha/apply/stream_forms/forms.py
def swap_fields_for_display(func):
    def wrapped(self, *args, **kwargs):
        # Replaces the form fields with the display fields
        # should only add new streamblocks and wont affect validation
        fields = self.fields.copy()
        self.fields = self.display
        yield from func(self, *args, **kwargs)
        self.fields = fields

    return wrapped

hidden_fields

hidden_fields()
Source code in hypha/apply/stream_forms/forms.py
def hidden_fields(self):
    # No hidden fields are returned by default because of MixedFieldMetaclass
    return [self[f] for f in self.fields.keys() if self[f].is_hidden]

delete_temporary_files

delete_temporary_files()

Overridden method of django_file_form's FileFormMixin, to handle multiple forms on the same page.

Source code in hypha/apply/stream_forms/forms.py
def delete_temporary_files(self):
    """
    Overridden method of django_file_form's FileFormMixin, to handle multiple forms on the same page.
    """
    form_id = self.data.getlist(self.add_prefix("form_id"))

    if not form_id:
        return

    form_id = form_id[0]
    for field_name, field in self.fields.items():
        if hasattr(field, "delete_file_data"):
            prefixed_field_name = self.add_prefix(field_name)
            field.delete_file_data(prefixed_field_name, form_id)

clean

clean()
Source code in hypha/apply/projects/forms/project.py
def clean(self):
    cleaned_data = super().clean()
    cleaned_data["form_data"] = {
        key: value
        for key, value in cleaned_data.items()
        if key not in self._meta.fields
    }
    return cleaned_data

save

save(*args, **kwargs)
Source code in hypha/apply/projects/forms/project.py
def save(self, *args, **kwargs):
    self.instance, _ = self._meta.model.objects.get_or_create(
        project=kwargs.pop("project", None)
    )
    self.instance.form_fields = kwargs.pop("sow_form_fields", {})
    self.instance.form_data = {
        field: self.cleaned_data[field]
        for field in self.instance.question_field_ids
        if field in self.cleaned_data
    }
    self.instance.process_file_data(self.cleaned_data)
    return super().save(*args, **kwargs)

SetPendingForm

SetPendingForm(*args, user=None, **kwargs)

Bases: ApproversForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, *args, user=None, **kwargs):
    from hypha.apply.activity.adapters.utils import get_users_for_groups

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

    for paf_reviewer_role in PAFReviewersRole.objects.all():
        users = get_users_for_groups(
            list(paf_reviewer_role.user_roles.all()), exact_match=True
        )
        approval = PAFApprovals.objects.filter(
            project=self.instance, paf_reviewer_role=paf_reviewer_role
        )
        if approval:
            initial_user = approval.first().user
        self.fields[slugify(paf_reviewer_role.label)] = forms.ModelChoiceField(
            queryset=users,
            required=False,
            blank=True,
            label=paf_reviewer_role.label,
            initial=initial_user if approval else None,
            disabled=approval.first().approved if approval.first() else False,
            # using approval.first() as condition for existing projects
        )

Meta

fields class-attribute instance-attribute
fields = ['id']
model class-attribute instance-attribute
model = Project
widgets class-attribute instance-attribute
widgets = {'id': HiddenInput()}

save

save(commit=True)
Source code in hypha/apply/projects/forms/project.py
def save(self, commit=True):
    # add users as PAFApprovals
    for paf_reviewer_role in PAFReviewersRole.objects.all():
        assigned_user = self.cleaned_data[slugify(paf_reviewer_role.label)]
        paf_approvals = PAFApprovals.objects.filter(
            project=self.instance, paf_reviewer_role=paf_reviewer_role
        )
        if not paf_approvals.exists():
            PAFApprovals.objects.create(
                project=self.instance,
                paf_reviewer_role=paf_reviewer_role,
                user=assigned_user if assigned_user else None,
                approved=False,
            )
        elif not paf_approvals.first().approved:
            paf_approval = paf_approvals.first()
            paf_approval.user = assigned_user if assigned_user else None
            paf_approval.save()
    return super().save(commit=True)

clean

clean()
Source code in hypha/apply/projects/forms/project.py
def clean(self):
    if self.instance.status != DRAFT:
        raise forms.ValidationError(
            _("A Project can only be sent for Approval when Drafted.")
        )

    # :todo: we should have a check form contains enough data to create PAF Approvals
    cleaned_data = super().clean()
    return cleaned_data

SkipPAFApprovalProcessForm

SkipPAFApprovalProcessForm(user=None, *args, **kwargs)

Bases: ModelForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, user=None, *args, **kwargs):
    super().__init__(*args, **kwargs)

Meta

fields class-attribute instance-attribute
fields = ['id']
model class-attribute instance-attribute
model = Project
widgets class-attribute instance-attribute
widgets = {'id': HiddenInput()}

StaffUploadContractForm

Bases: FileFormMixin, ModelForm

file class-attribute instance-attribute

file = SingleFileField(label=gettext_lazy('Contract'), required=True)

Meta

fields class-attribute instance-attribute
fields = ['file', 'signed_by_applicant']
model class-attribute instance-attribute
model = Contract

SubmitContractDocumentsForm

SubmitContractDocumentsForm(*args, user=None, **kwargs)

Bases: ModelForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, *args, user=None, **kwargs):
    super().__init__(*args, **kwargs)

Meta

fields class-attribute instance-attribute
fields = ['id']
model class-attribute instance-attribute
model = Project
widgets class-attribute instance-attribute
widgets = {'id': HiddenInput()}

UpdateProjectLeadForm

UpdateProjectLeadForm(user=None, *args, **kwargs)

Bases: ModelForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, user=None, *args, **kwargs):
    super().__init__(*args, **kwargs)

    lead_field = self.fields["lead"]
    lead_field.label = _("Update lead from {lead} to").format(
        lead=self.instance.lead
    )

    qwargs = Q(groups__name=STAFF_GROUP_NAME) | Q(is_superuser=True)
    lead_field.queryset = (
        lead_field.queryset.exclude(pk=self.instance.lead_id)
        .filter(qwargs)
        .distinct()
    )

Meta

fields class-attribute instance-attribute
fields = ['lead']
model class-attribute instance-attribute
model = Project

UpdateProjectTitleForm

UpdateProjectTitleForm(user=None, *args, **kwargs)

Bases: ModelForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, user=None, *args, **kwargs):
    super().__init__(*args, **kwargs)

Meta

fields class-attribute instance-attribute
fields = ['title']
model class-attribute instance-attribute
model = Project

UploadContractDocumentForm

UploadContractDocumentForm(*args, user=None, instance=None, **kwargs)

Bases: FileFormMixin, ModelForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, *args, user=None, instance=None, **kwargs):
    super().__init__(*args, **kwargs)

document class-attribute instance-attribute

document = SingleFileField(label=gettext_lazy('Contract Document'), required=True)

Meta

fields class-attribute instance-attribute
fields = ['category', 'document']
model class-attribute instance-attribute
widgets class-attribute instance-attribute
widgets = {'category': HiddenInput()}

save

save(commit=True)
Source code in hypha/apply/projects/forms/project.py
def save(self, commit=True):
    self.instance.title = self.instance.document
    return super(UploadContractDocumentForm, self).save(commit=True)

UploadContractForm

Bases: FileFormMixin, ModelForm

file class-attribute instance-attribute

file = SingleFileField(label=gettext_lazy('Contract'), required=True)

signed_and_approved class-attribute instance-attribute

signed_and_approved = BooleanField(label=gettext_lazy('Signed and approved'), required=False)

Meta

fields class-attribute instance-attribute
fields = ['file', 'signed_and_approved']
model class-attribute instance-attribute
model = Contract

save

save(commit=True)
Source code in hypha/apply/projects/forms/project.py
def save(self, commit=True):
    self.instance.file = self.cleaned_data.get("file")
    return super().save(commit=True)

UploadDocumentForm

UploadDocumentForm(*args, user=None, instance=None, **kwargs)

Bases: FileFormMixin, ModelForm

Source code in hypha/apply/projects/forms/project.py
def __init__(self, *args, user=None, instance=None, **kwargs):
    super().__init__(*args, **kwargs)

document class-attribute instance-attribute

document = SingleFileField(label=gettext_lazy('Document'), required=True)

Meta

fields class-attribute instance-attribute
fields = ['category', 'document']
model class-attribute instance-attribute
model = PacketFile
widgets class-attribute instance-attribute
widgets = {'category': HiddenInput()}

save

save(commit=True)
Source code in hypha/apply/projects/forms/project.py
def save(self, commit=True):
    self.instance.title = self.instance.document
    return super(UploadDocumentForm, self).save(commit=True)

ReportEditForm

ReportEditForm(*args, user=None, initial=None, **kwargs)

Bases: StreamBaseForm, ModelForm

Source code in hypha/apply/projects/forms/report.py
def __init__(self, *args, user=None, initial=None, **kwargs):
    if initial is None:
        initial = {}
    # Need to populate form_fields, right?
    # No: The form_fields got populated from the view which instantiated this Form.
    # Yes: they don't seem to be here.
    # No: this is not where the magic happens.
    # self.form_fields = kwargs.pop("form_fields", {})
    # Need to populate form_data, right? Yes. No. IDK. Appears no.
    # self.form_data = kwargs.pop("form_data", {})
    # OK, both yes and no. If there is an existing value it will come via "initial", so if present there, use them.
    # if initial["form_fields"] is not None:
    #     self.form_fields = initial["form_fields"]
    # if initial["form_data"] is not None:
    #     self.form_data = initial["form_data"]
    # But this should not be needed because super().__init__ will already take these initial values and use them.
    super().__init__(*args, initial=initial, **kwargs)
    self.user = user

user instance-attribute

user = user

Meta

model class-attribute instance-attribute
model = Report
fields class-attribute instance-attribute
fields = []

swap_fields_for_display

swap_fields_for_display(func)
Source code in hypha/apply/stream_forms/forms.py
def swap_fields_for_display(func):
    def wrapped(self, *args, **kwargs):
        # Replaces the form fields with the display fields
        # should only add new streamblocks and wont affect validation
        fields = self.fields.copy()
        self.fields = self.display
        yield from func(self, *args, **kwargs)
        self.fields = fields

    return wrapped

hidden_fields

hidden_fields()
Source code in hypha/apply/stream_forms/forms.py
def hidden_fields(self):
    # No hidden fields are returned by default because of MixedFieldMetaclass
    return [self[f] for f in self.fields.keys() if self[f].is_hidden]

delete_temporary_files

delete_temporary_files()

Overridden method of django_file_form's FileFormMixin, to handle multiple forms on the same page.

Source code in hypha/apply/stream_forms/forms.py
def delete_temporary_files(self):
    """
    Overridden method of django_file_form's FileFormMixin, to handle multiple forms on the same page.
    """
    form_id = self.data.getlist(self.add_prefix("form_id"))

    if not form_id:
        return

    form_id = form_id[0]
    for field_name, field in self.fields.items():
        if hasattr(field, "delete_file_data"):
            prefixed_field_name = self.add_prefix(field_name)
            field.delete_file_data(prefixed_field_name, form_id)

clean

clean()
Source code in hypha/apply/projects/forms/report.py
def clean(self):
    cleaned_data = super().clean()
    cleaned_data["form_data"] = {
        key: value
        for key, value in cleaned_data.items()
        if key not in self._meta.fields
    }
    return cleaned_data

save

save(commit=True, form_fields=dict)
Source code in hypha/apply/projects/forms/report.py
@transaction.atomic
def save(self, commit=True, form_fields=dict):
    self.instance.form_fields = form_fields
    instance = super().save(commit)
    # We need to save the fields first, not attempt to save form_data on first save, then update the form_data next.
    # Otherwise, we don't get access to the generator method "question_field_ids" which we use to prevent temp file
    # fields from getting into the saved form_data.
    # Inspired by ProjectForm.save and ProjectSOWForm.save but enhanced to support multi-answer fields.
    instance.form_data = {
        field: self.cleaned_data["form_data"][field]
        for field in self.cleaned_data["form_data"]
        # Where do we get question_field_ids? On the version, but only when it exists, thus the create-then-update.
        # The split-on-underscore supports the use of multi-answer fields such as MultiInputCharFieldBlock.
        if field.split("_")[0] in instance.question_field_ids
    }
    # In case there are stream form file fields, process those here.
    instance.process_file_data(self.cleaned_data["form_data"])

    is_draft = "save" in self.data
    version = ReportVersion.objects.create(
        report=instance,
        # Save a ReportVersion first then edit/update the form_data below.
        form_data=instance.form_data,
        submitted=timezone.now(),
        draft=is_draft,
        author=self.user,
    )
    version.process_file_data(self.cleaned_data["form_data"])
    version.save()

    if is_draft:
        instance.draft = version
    else:
        # If this is the first submission of the report we track that as the
        # submitted date of the report
        if not instance.submitted:
            instance.submitted = version.submitted
        instance.current = version
        instance.draft = None
    instance.save()
    return instance

ReportFrequencyForm

ReportFrequencyForm(*args, **kwargs)

Bases: ModelForm

Source code in hypha/apply/projects/forms/report.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    self.fields["occurrence"].required = False
    self.fields["frequency"].required = False

start class-attribute instance-attribute

start = DateField(label='Report on:', required=False)

Meta

model class-attribute instance-attribute
model = ReportConfig
fields class-attribute instance-attribute
fields = ('start', 'occurrence', 'frequency', 'does_not_repeat')
labels class-attribute instance-attribute
labels = {'occurrence': '', 'frequency': ''}