Forms with fields created dynamically client side

28 views
Skip to first unread message

Jon Dufresne

unread,
Jul 26, 2013, 6:56:33 PM7/26/13
to django...@googlegroups.com
Hi,

I am creating a form for the user to add, edit, and remove all tags in the database. The tag models are handled by taggit. The form will look like like

_Tag1_    [del]
_Tag2_    [del]
______    <--- User enters next tag here

[add tag]

Clicking add tag will fire some javascript to add a new text input to the form. I trying to create this form in Django to handle the request. This is what I have so far. I am curious if I am going about this the right way. It all seems very... roundabout. Thoughts? One part that bothers me is I must inspect the incoming data to decide how many form elements to create.

Coming from PHP, I would create form names with array notation (tags[pk] = name) and iterate over the array during the request.

The existing_tag dictionary allows me to map form names to tag objects. The new_tags list allows me to iterate over tag fields that must be created as new tags.

class TagsForm(forms.Form):
    def __init__(self, data=None, *args, **kwargs):
        super(TagsForm, self).__init__(data, *args, **kwargs)

        self.existing_tags = {}
        self.new_tags = []

        for tag in Tag.objects.all():
            name = 'tag%i' % tag.pk
            self.fields[name] = forms.CharField(
                initial=tag.name,
                required=False)
            self.existing_tags[name] = tag

        if data:
            for name in data:
                if name.startswith('newtags'):
                    self.fields[name] = forms.CharField(required=False)
                    self.new_tags.append(name)
        else:
            name = 'newtags'
            self.fields[name] = forms.CharField(required=False)
            self.new_tags.append(name)

Reply all
Reply to author
Forward
0 new messages