applegrew / django-select2

This is a Django integration for Select2
MIT License
710 stars 316 forks source link

How to customize select2 widgets (i.e. language, css properties) when declaring a form in forms.py #579

Closed jpm92 closed 4 years ago

jpm92 commented 4 years ago

Hello, I've found the docs a bit lacking regarding all the options that can be passed to the select2 widget (such as https://select2.org/configuration/options-api) in order to configure it. It would be great to expand the docs with such info. I'm particulary interested in changing the widgets css properties (specially width, since I get very narrow wdigets) and also changing the language. I haven't been able to find such information in the docs and I think it could help this amazing app to expand. Thanks for the work!

ArionMiles commented 4 years ago

some example code with the widgets you're trying to customize would be helpful

jpm92 commented 4 years ago

Sorry! There you have an example, thanks!

models.py

class PedidoFungible(models.Model):
    producto = models.ForeignKey(ProductoFungible, on_delete=models.SET_NULL, null=True)
    autor = models.ForeignKey(User, on_delete=models.SET_NULL, blank = True, null = True)
    fecha = models.DateTimeField(auto_now_add=True)
    unidades = models.IntegerField(default=1, blank = False)
    almacen = models.ForeignKey(Almacen, null=True, on_delete=models.SET_NULL, blank=True)
    proforma = models.ForeignKey(Proforma, blank = True, null=True, on_delete=models.SET_NULL)

    ESTADO = (
        ('a', _('Pendiente')),
        ('b', _('Incluído en proforma')),
        ('r', _('Recibido'))
    )

    estado = models.CharField(
        max_length=1,
        choices=ESTADO,
        blank=False,
        default = 'a',
        help_text=_('Estado de la solicitud.'),
    )

    class Meta:
        verbose_name = _("Pedido fungible")
        verbose_name_plural = _("Pedidos de fungible")

    def __str__(self):
        """String for representing the MyModelName object (in Admin site etc.)."""
        return self.producto.nombre_amistoso

forms.py

from django_select2.forms import Select2Widget
class PedidoFungibleForm(ModelForm):
    class Meta:
        model = PedidoFungible
        fields = ['producto', 'unidades']
        widgets = {
            'producto': Select2Widget
        }
ArionMiles commented 4 years ago

for language, why don't you try:

Select2Widget({'data-language': 'es'})

in your forms.py. I'm assuming you want to have language as Spanish.

List of default supported languages: https://github.com/applegrew/django-select2/blob/master/django_select2/conf.py#L108

jpm92 commented 4 years ago

for language, why don't you try:

Select2Widget({'data-language': 'es'})

in your forms.py. I'm assuming you want to have language as Spanish.

Working! That was easy! (I imagined it should be something like that) Seeing how it works, I think I can use dropdownCss property of select2 to add some specific css to the widget, although I'm not sure which class I have to override yet. Thanks again!

ArionMiles commented 4 years ago

For custom width, use: data-width: 'resolve'

options for this setting are element, style, resolve or <value> where value can be percentage

ref: https://select2.org/appearance#container-width

ArionMiles commented 4 years ago

Seeing how it works, I think I can use dropdownCss property of select2 to add some specific css to the widget

Yes.

Try data-dropdown-css for this. Let me know if it works, since this is a guess from my side, and I'm not sure either.

jpm92 commented 4 years ago

Seeing how it works, I think I can use dropdownCss property of select2 to add some specific css to the widget

Yes.

Try data-dropdown-css for this. Let me know if it works, since this is a guess from my side, and I'm not sure either.

Whenever I tried to use data-dropdown-css the widget stopped working. Maybe I was writing it wrongly. I had something like this:

class PedidoFungibleForm(ModelForm):
    class Meta:
        model = PedidoFungible
        fields = ['producto', 'unidades']
        widgets = {
            'producto': Select2Widget(
                {'data-language': 'es',
                 'data-placeholder': _('Busque fungibles'),
                 'data-dropdown-css': {'data-width': 'style'},
                 }
            )
        }

I finally made it work with this:

class PedidoFungibleForm(ModelForm):
    class Meta:
        model = PedidoFungible
        fields = ['producto', 'unidades']
        widgets = {
            'producto': Select2Widget(
                {'data-language': 'es',
                 'data-placeholder': _('Busque fungibles'),
                 'data-width': 'style',
                 }
            )
        }

Thanks a lot! Now it looks quite acceptable! (although it might need more tweaking to make it look better) Regards, J.

ArionMiles commented 4 years ago

Cool, and I have no idea why dropdownCss would be used instead of specifying the attributes, so the approach you've taken makes more sense to me.

If this is resolved you can close the issue, cheers!