Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django form, custom SelectField and SelectMultipleField

I am using Django everyday now for three month and it is really great. Fast web application development.

I have still one thing that I cannot do exactly how I want to. It is the SelectField and SelectMultiple Field.

I want to be able to put some args to an option of a Select.

I finally success with the optgroup :

class EquipmentField(forms.ModelChoiceField):
    def __init__(self, queryset, **kwargs):
        super(forms.ModelChoiceField, self).__init__(**kwargs)
        self.queryset = queryset
        self.to_field_name=None

        group = None
        list = []
        self.choices = []

        for equipment in queryset:
            if not group:
                group = equipment.type

            if group != equipment.type:
                self.choices.append((group.name, list))
                group = equipment.type
                list = []
            else:
                list.append((equipment.id, equipment.name))

But for another ModelForm, I have to change the background color of every option, using the color property of the model.

Do you know how I can do that ?

Thank you.

like image 225
Natim Avatar asked Dec 10 '09 02:12

Natim


People also ask

How do I customize Modelan in Django?

To create ModelForm in django, you need to specify fields. Just associate the fields to first_name and lastName. Under the Meta class you can add : fields = ['first_name','lastName']. @Shishir solution works after I add that line. or you can try solution in Jihoon answers by adding vacant fields.

What is form Is_valid () in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

How do I change the date format in Django?

To customize the format a DateField in a form uses we can set the input_formats kwarg [Django docs] on the field which is a list of formats that would be used to parse the date input from the user and set the format kwarg [Django docs] on the widget which is the format the initial value for the field is displayed in.

What is the difference between form and ModelForm in Django?

The main difference between the two is that in forms that are created from forms. ModelForm , we have to declare which model will be used to create our form. In our Article Form above we have this line " model = models. Article " which basically means we are going to use Article model to create our form.


1 Answers

What you need to do, is to change the output which is controlled by the widget. Default is the select widget, so you can subclass it. It looks like this:

class Select(Widget):
    def __init__(self, attrs=None, choices=()):
        super(Select, self).__init__(attrs)
        # choices can be any iterable, but we may need to render this widget
        # multiple times. Thus, collapse it into a list so it can be consumed
        # more than once.
        self.choices = list(choices)

    def render(self, name, value, attrs=None, choices=()):
        if value is None: value = ''
        final_attrs = self.build_attrs(attrs, name=name)
        output = [u'<select%s>' % flatatt(final_attrs)]
        options = self.render_options(choices, [value])
        if options:
            output.append(options)
        output.append('</select>')
        return mark_safe(u'\n'.join(output))

    def render_options(self, choices, selected_choices):
        def render_option(option_value, option_label):
            option_value = force_unicode(option_value)
            selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
            return u'<option value="%s"%s>%s</option>' % (
                escape(option_value), selected_html,
                conditional_escape(force_unicode(option_label)))
        # Normalize to strings.
        selected_choices = set([force_unicode(v) for v in selected_choices])
        output = []
        for option_value, option_label in chain(self.choices, choices):
            if isinstance(option_label, (list, tuple)):
                output.append(u'<optgroup label="%s">' % escape(force_unicode(option_value)))
                for option in option_label:
                    output.append(render_option(*option))
                output.append(u'</optgroup>')
            else:
                output.append(render_option(option_value, option_label))
        return u'\n'.join(output)

It's a lot of code. But what you need to do, is to make your own widget with an altered render method. It's the render method that determines the html that is created. In this case, it's the render_options method you need to change. Here you could include some check to determine when to add a class, which you could style.

Another thing, in your code above it doesn't look like you append the last group choices. Also you might want to add an order_by() to the queryset, as you need it to be ordered by the type. You could do that in the init method, so you don't have to do it all over when you use the form field.

like image 146
googletorp Avatar answered Sep 28 '22 12:09

googletorp