Wednesday, December 28, 2016

Re: Custom Widget for CharField Multiple

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.

On 28 Dec 2016, at 22:52, Farhan Khan <khanzf@gmail.com> wrote:

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

--
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+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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.

No comments:

Post a Comment