from django import forms

from adhocracy4.categories import models as category_models


class CategorizableFieldMixin:
    category_field_name = 'category'

    def __init__(self, *args, **kwargs):
        module = kwargs.pop('module')
        super().__init__(*args, **kwargs)
        queryset = category_models.Category.objects.filter(module=module)
        self.fields[self.category_field_name] = forms.ModelChoiceField(
            queryset=queryset,
            empty_label=None,
            required=False,
        )

    def show_categories(self):
        module_has_categories = len(self.fields['category'].queryset) > 0
        return module_has_categories

from adhocracy4.categories import models as category_models


class CategorizableFieldMixin:
    category_field_name = 'category'

    def __init__(self, *args, **kwargs):
        module = kwargs.pop('module')
        super().__init__(*args, **kwargs)

        field = self.fields[self.category_field_name]
        field.queryset = category_models.Category.objects.filter(module=module)

        required = field.queryset.exists()
        field.empty_label = None
        field.required = required
        field.widget.is_required = required

    def show_categories(self):
        field = self.fields[self.category_field_name]
        module_has_categories = field.queryset.exists()
        return module_has_categories

Modify generated category form field instead of reinitialize it
Modify generated category form field instead of reinitialize it

The category fields had not been translated as the field had been
reinitialized instead of modified. With this PR the auto generated field
(with its localized verbose_name) will be kept and adapted to the
filtered queryset.

Furthermore the required parameter is set to true if there are any
categories for the module.
