user3595632
user3595632

Reputation: 5730

How can I call render_option() of forms.Select in Django?

class MySelect(forms.Select):
    def __init__(self, *args, **kwargs):
        self.variations = kwargs.pop('variations')
        super(MySelect, self).__init__(*args, **kwargs)

    def render_option(self, selected_choices, option_value, option_label):
        return '<option whatever> {} </option>'.format(self.variations[0])

class CartItemForm(forms.ModelForm):

    class Meta:
        model = CartItem
        fields = (
            'variation',
            'width',
            'height',
            'quantity',
        )


    def __init__(self, *args, **kwargs):
        product = kwargs.pop('product')
        try:
            cart = kwargs.pop('cart')
            self.cart = cart
        except:
            pass

        super().__init__(*args, **kwargs)    

        variation_field = self.fields['variation']
        variation_field.queryset = Variation.objects.filter(
            product=product
        )
        variation_field.widget = MySelect(variations=variation_field.queryset)

    def save(self):
        cart_item = super().save(commit=False)
        cart_item.cart = self.cart
        cart_item.save()

        return cart_item

But it doesn't call render_option() so it doesn't show anything in template...

What's wrong with that?

Upvotes: 3

Views: 506

Answers (1)

Csaba Toth
Csaba Toth

Reputation: 10697

The question is faulty. When you customize a Widget then you need to override the proper functions. Then the framework will call it for you at the right moment, but you never have to call them explicitly.

What happened is that you encountered (maybe inherited, as in my case) a code sample which meant to work with earlier versions of Django. In those earlier versions the render_option was the right function, but in my case I don't see it any more in Django 1.11 (https://docs.djangoproject.com/en/2.1/releases/1.11/#changes-due-to-the-introduction-of-template-based-widget-rendering). The only proper thing is to convert the sample, find the existing function(s) we can override to achieve the desired results.

Upvotes: 2

Related Questions