Skip to content

Blocks

hypha.apply.categories.blocks

SEARCHABLE_SELECT_THRESHOLD module-attribute

SEARCHABLE_SELECT_THRESHOLD = 32

ModelChooserBlock

Bases: ChoiceBlock

CategoryQuestionBlock

Bases: OptionalFormFieldBlock

category class-attribute instance-attribute

category = ModelChooserBlock(required=True, choices=get_categories_as_choices)

multi class-attribute instance-attribute

multi = BooleanBlock(label=_('Multi select'), required=False)

field_label class-attribute instance-attribute

field_label = CharBlock(label=_('Label'), required=False, help_text=_('Leave blank to use the default Category label'))

help_text class-attribute instance-attribute

help_text = RichTextBlock(label=_('Help text'), required=False, help_text=_('Leave blank to use the default Category help text'))

field_class class-attribute instance-attribute

field_class = forms.CharField

widget class-attribute instance-attribute

widget = None

required class-attribute instance-attribute

required = BooleanBlock(label=_('Required'), required=False)

Meta

template class-attribute instance-attribute
template = 'stream_forms/render_list_field.html'
icon class-attribute instance-attribute
icon = 'folder-open-1'

model_class

model_class()
Source code in hypha/apply/categories/blocks.py
@cached_property
def model_class(self):
    return resolve_model_string("categories.Category")

get_instance

get_instance(id)
Source code in hypha/apply/categories/blocks.py
def get_instance(self, id):
    return self.model_class.objects.get(id=id)

get_field_class

get_field_class(struct_value)
Source code in hypha/apply/categories/blocks.py
def get_field_class(self, struct_value):
    return forms.MultipleChoiceField if struct_value["multi"] else forms.ChoiceField

use_defaults_from_category

use_defaults_from_category(kwargs, category)
Source code in hypha/apply/categories/blocks.py
def use_defaults_from_category(self, kwargs, category):
    category_fields = {"label": "name", "help_text": "help_text"}

    for field in category_fields.keys():
        if not kwargs.get(field):
            kwargs[field] = getattr(category, category_fields[field])

    return kwargs

widget_for_choices

widget_for_choices(struct_value, choices)
Source code in hypha/apply/categories/blocks.py
def widget_for_choices(self, struct_value, choices):
    # Pick widget according to number of options to maintain good usability.
    many_options = len(choices) >= SEARCHABLE_SELECT_THRESHOLD
    if struct_value["multi"]:
        return (
            ChoicesSelectMultipleWidget
            if many_options
            else forms.CheckboxSelectMultiple
        )
    return ChoicesSelectWidget if many_options else forms.RadioSelect

get_field_kwargs

get_field_kwargs(struct_value)
Source code in hypha/apply/categories/blocks.py
def get_field_kwargs(self, struct_value):
    kwargs = super().get_field_kwargs(struct_value)
    category = self.get_instance(id=struct_value["category"])
    kwargs = self.use_defaults_from_category(kwargs, category)
    choices = list(category.options.values_list("id", "value"))
    widget = self.widget_for_choices(struct_value, choices)
    if widget is ChoicesSelectWidget:
        # A <select> auto-selects its first option, so offer an empty one.
        choices.insert(0, BLANK_CHOICE_DASH[0])
    kwargs.update({"choices": choices, "widget": widget})
    return kwargs

prepare_data

prepare_data(value, data, serialize)
Source code in hypha/apply/categories/blocks.py
def prepare_data(self, value, data, serialize):
    if not data:
        return data
    if isinstance(data, str):
        data = [data]
    category = self.get_instance(id=value["category"])
    data = category.options.filter(id__in=data).values_list("value", flat=True)
    return data

get_display_value

get_display_value(value)
Source code in hypha/apply/categories/blocks.py
def get_display_value(self, value):
    # Fall back on the category's own name and help text for empty values.
    category_fields = {"field_label": "name", "help_text": "help_text"}

    missing = [field for field in category_fields if not value.get(field)]
    if not missing:
        return value

    # Look the category up once, however many fields fall back on it.
    category = value["category"]
    if isinstance(category, int) or isinstance(category, str):
        category = self.get_instance(id=category)

    defaults = {
        field: getattr(category, category_fields[field]) for field in missing
    }

    # Return a copy, so that the fallbacks are never written back to the
    # stored form definition.
    block = getattr(value, "block", None)
    if block is None:
        display_value = dict(value)
    else:
        display_value = value.__class__(block, value.items())
    display_value.update(defaults)
    return display_value

render

render(value, context)
Source code in hypha/apply/categories/blocks.py
def render(self, value, context):
    return super().render(self.get_display_value(value), context)

get_searchable_content

get_searchable_content(value, data)
Source code in hypha/apply/categories/blocks.py
def get_searchable_content(self, value, data):
    return None

no_response

no_response()
Source code in hypha/apply/categories/blocks.py
def no_response(self):
    return "-"

get_slug

get_slug(struct_value)
Source code in hypha/apply/stream_forms/blocks.py
def get_slug(self, struct_value):
    return force_str(slugify(anyascii(struct_value["field_label"])))

get_widget

get_widget(struct_value)
Source code in hypha/apply/stream_forms/blocks.py
def get_widget(self, struct_value):
    return self.widget

get_field

get_field(struct_value)
Source code in hypha/apply/stream_forms/blocks.py
def get_field(self, struct_value):
    field_kwargs = self.get_field_kwargs(struct_value)
    return self.get_field_class(struct_value)(**field_kwargs)

decode

decode(value)

Convert JSON representation into actual python objects

Source code in hypha/apply/stream_forms/blocks.py
def decode(self, value):
    """Convert JSON representation into actual python objects"""
    return value

serialize

serialize(value, context)
Source code in hypha/apply/stream_forms/blocks.py
def serialize(self, value, context):
    field_kwargs = self.get_field_kwargs(value)
    return {
        "question": field_kwargs["label"],
        "answer": context.get("data"),
        "type": self.name,
    }

serialize_no_response

serialize_no_response(value, context)
Source code in hypha/apply/stream_forms/blocks.py
def serialize_no_response(self, value, context):
    return {
        "question": value["field_label"],
        "answer": "-",
        "type": "no_response",
    }

get_categories_as_choices

get_categories_as_choices()
Source code in hypha/apply/categories/blocks.py
def get_categories_as_choices():
    Category = resolve_model_string("categories.Category")
    return [(cat.id, cat.name) for cat in Category.objects.all()]