Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementation of formfield_for_choice_field makes overriding choices clumsy #447

Closed
Daspy11 opened this issue Jun 5, 2024 · 1 comment
Labels
bug Something isn't working

Comments

@Daspy11
Copy link

Daspy11 commented Jun 5, 2024

I have an inline admin where I'm trying to override the choices used. The issue with the implementation of this method in Unfold's base in admin.py is that if you modify the choices kwarg, it will be overridden by the base choices unless you also pass the widget kwarg, and doing that requires importing some internal Unfold stuff in an unclean way.

Current

    def formfield_for_choice_field(
        self, db_field: Field, request: HttpRequest, **kwargs
    ) -> TypedChoiceField:
        # Overrides widget for CharFields which have choices attribute
        if "widget" not in kwargs:
            if db_field.name in self.radio_fields:
                kwargs["widget"] = UnfoldAdminRadioSelectWidget(
                    radio_style=self.radio_fields[db_field.name]
                )
            else:
                kwargs["widget"] = UnfoldAdminSelectWidget()

            kwargs["choices"] = db_field.get_choices(
                include_blank=db_field.blank, blank_choice=[("", _("Select value"))]
            )

        return super().formfield_for_choice_field(db_field, request, **kwargs)

What it should be

    def formfield_for_choice_field(
        self, db_field: Field, request: HttpRequest, **kwargs
    ) -> TypedChoiceField:
        if "widget" not in kwargs:
            if db_field.name in self.radio_fields:
                kwargs["widget"] = UnfoldAdminRadioSelectWidget(
                    radio_style=self.radio_fields[db_field.name]
                )
            else:
                kwargs["widget"] = UnfoldAdminSelectWidget()
        if "choices" not in kwargs:
            kwargs["choices"] = db_field.get_choices(
                include_blank=db_field.blank, blank_choice=[("", _("Select value"))]
            )

        return super().formfield_for_choice_field(db_field, request, **kwargs)
@lukasvinclav lukasvinclav added the bug Something isn't working label Jul 5, 2024
@lukasvinclav
Copy link
Contributor

Thanks for report. Fixed #539

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants