Skip to content

Forms

hypha.apply.review.forms

MixedMetaClass

Bases: type(StreamBaseForm), type(ModelForm)

ReviewModelForm

ReviewModelForm(*args, submission, user=None, initial=None, instance=None, **kwargs)

Bases: StreamBaseForm, ModelForm

Source code in hypha/apply/review/forms.py
def __init__(
    self, *args, submission, user=None, initial=None, instance=None, **kwargs
):
    if initial is None:
        initial = {}

    initial.update(submission=submission.id)

    if instance:
        for key, value in instance.form_data.items():
            if key not in self._meta.fields:
                initial[key] = value

    super().__init__(*args, initial=initial, instance=instance, **kwargs)

    for field in self._meta.widgets:
        self.fields[field].disabled = True
    if self.draft_button_name in self.data:
        for field in self.fields.values():
            field.required = False

draft_button_name class-attribute instance-attribute

draft_button_name = 'save_draft'

Meta

model class-attribute instance-attribute
model = Review
fields class-attribute instance-attribute
fields = ['recommendation', 'visibility', 'score', 'submission']
widgets class-attribute instance-attribute
widgets = {'recommendation': HiddenInput(), 'score': HiddenInput(), 'submission': HiddenInput(), 'visibility': HiddenInput()}
error_messages class-attribute instance-attribute
error_messages = {NON_FIELD_ERRORS: {'unique_together': 'You have already posted a review for this submission'}}

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/review/forms.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)
Source code in hypha/apply/review/forms.py
def save(self, commit=True):
    self.instance.score = self.calculate_score(self.cleaned_data)
    self.instance.recommendation = int(
        self.cleaned_data[self.instance.recommendation_field.id]
    )
    self.instance.is_draft = self.draft_button_name in self.data
    # Old review forms do not have the requred visability field.
    # This will set visibility to PRIVATE by default.
    try:
        self.instance.visibility = self.cleaned_data[
            self.instance.visibility_field.id
        ]
    except AttributeError:
        self.instance.visibility = PRIVATE

    self.instance.form_data = self.cleaned_data["form_data"]

    if not self.instance.is_draft:
        # Capture the revision against which the user was reviewing
        self.instance.revision = self.instance.submission.live_revision

    return super().save(commit)

calculate_score

calculate_score(data)
Source code in hypha/apply/review/forms.py
def calculate_score(self, data):
    scores = []
    for field in self.instance.score_fields:
        score = data.get(field.id)[1]
        # Include NA answers as 0.
        if score == NA:
            score = 0
        scores.append(score)
    # Check if there are score_fields_without_text and also
    # append scores from them.
    for field in self.instance.score_fields_without_text:
        score = data.get(field.id)
        # Include '' answers as 0.
        if score == "":
            score = 0
        scores.append(int(score))

    try:
        return sum(scores) / len(scores)
    except ZeroDivisionError:
        return NA

SubmitButtonWidget

Bases: Widget

render

render(name, value, attrs=None, renderer=None)
Source code in hypha/apply/review/forms.py
def render(self, name, value, attrs=None, renderer=None):
    disabled = "disabled" if attrs.get("disabled") else ""
    return '<input type="submit" name="{name}" value="{value}" class="button button--primary button--bottom-space" {disabled}>'.format(
        disabled=disabled,
        name=escape(name),
        value=escape(name.title()),
    )

OpinionField

OpinionField(*args, opinion, **kwargs)

Bases: IntegerField

Source code in hypha/apply/review/forms.py
def __init__(self, *args, opinion, **kwargs):
    kwargs["widget"] = SubmitButtonWidget
    self.opinion = opinion
    kwargs["label"] = ""
    super().__init__(*args, **kwargs)

opinion instance-attribute

opinion = opinion

clean

clean(value)
Source code in hypha/apply/review/forms.py
def clean(self, value):
    if value:
        return self.opinion

ReviewOpinionForm

ReviewOpinionForm(*args, **kwargs)

Bases: ModelForm

Source code in hypha/apply/review/forms.py
def __init__(self, *args, **kwargs):
    super().__init__(*args, **kwargs)
    for value, opinion in OPINION_CHOICES:
        self.fields[opinion.lower()] = OpinionField(
            label=opinion.title(),
            opinion=value,
            disabled=self.instance.opinion == value,
        )

opinion class-attribute instance-attribute

opinion = IntegerField(required=False, widget=HiddenInput())

Meta

model class-attribute instance-attribute
model = ReviewOpinion
fields class-attribute instance-attribute
fields = ('opinion')

clean

clean()
Source code in hypha/apply/review/forms.py
def clean(self):
    cleaned_data = super().clean()
    opinions = [cleaned_data.get(opinion.lower()) for _, opinion in OPINION_CHOICES]
    valid_opinions = [opinion for opinion in opinions if opinion is not None]
    if len(valid_opinions) > 1:
        self.add_error(None, "Cant submit both an agreement and disagreement")
    cleaned_data = {"opinion": valid_opinions[0]}
    return cleaned_data

save

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