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)

-- 
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+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to