Custom Widget for CharField Multiple

19 views
Skip to first unread message

Farhan Khan

unread,
Dec 28, 2016, 2:52:56 PM12/28/16
to Django users
Hi,
I am trying to create a `CharFieldMultiple`, equivalent to the MultipleHiddenInput or SelectMultiple.

The goal is to have multiple CharField returned as a list, but have not been able to recreate it. My code thus far is:

class CharFieldMultiple(forms.widgets.Input):
   
def render(self, name, value, attrs=None):
       
if value is None:
            value
= []
        final_attrs
= self.build_attrs(attrs, type=self.input_type, name=name)
        inputs
= []
       
for i, v in enumerate(value):
            input_attrs
= dict(value=force_text(v), **final_attrs)
            inputs
.append(format_html('<input{} />', flatatt(input_attrs)))
       
return mark_safe('\n'.join(inputs))

I am trying to figure out how 'value' is set. I noticed that when I manually put value = ['a','b','c'], I will get 3 CharFields, great! But I cannot figure out how to pass that value parameter.

The type-field is still set to None, but I can figure that out later.
Thanks in advance!

- Farhan

roboslone

unread,
Dec 29, 2016, 12:13:52 AM12/29/16
to django...@googlegroups.com
Hi! If I understand this correctly, subclassing `forms.widgets.Input` was a wrong idea.
As you can see in Input's source (https://docs.djangoproject.com/en/1.10/_modules/django/forms/widgets/#Input), it always renders single <input> tag, so you'd always get single value attribute from it, which is a string, not a list.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2ecc728a-8d13-492d-91cf-e2fe155fc04b%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages