Dynamic Form Fields in Django using JavaScript

780 views
Skip to first unread message

AJ

unread,
Jul 3, 2011, 1:35:40 PM7/3/11
to django...@googlegroups.com
I am thinking of creating an app like Wufoo which requires adding dynamic elements in the form based on user interaction. So, to begin with I will have an empty form (with no fields). Then user will add a text-input, a text-area etc. using JavaScript on the page, on the fly.

I know that Django forms have the CSRF token within the forms.

* I want to know if adding more fields to the form will somehow invalidate the form generated by Django.

I am saving text inputs and text areas in different model classes. Also, the class for the form itself is the main class.

class UserForms (models.Model):
    name = models.CharField(max_length=1000)
    description = models.TextField(blank=True, null=True)
  ...


class Text (models.Model):
    name = models.CharField(max_length=1000)
    text = models.TextField()
    created_datetime = models.DateTimeField(auto_now_add=True, editable=False)
    modified_datetime = models.DateTimeField(auto_now=True, editable=False)
    active = models.BooleanField(default=True)
    user = models.ForeignKey(User, unique=False)
    form = models.ForeignKey(UserForms, unique=False)
...

You could also point me to a tutorial or keywords that I should be using to search for this kind of behaviour.

If you want additional information, please let me know.

Thanks.
AJ







Shawn Milochik

unread,
Jul 3, 2011, 1:40:24 PM7/3/11
to django...@googlegroups.com
As long as, when you instantiate your Django forms.Form instance when
the HTML form is posted, you create the fields passed in the form data
and instantiate the fields to match you should be fine.

Just go ahead and do it, and if you run into any snags post to the forum.

Shawn

AJ

unread,
Jul 3, 2011, 4:30:50 PM7/3/11
to django...@googlegroups.com
Hi Shawn,

Thanks for your reply. To begin with, I am trying this with a small test app.

I have this so far. I tried with two textarea elements on a page and tried to save them but I cannot figure out how to save two elements. Each element list corresponds to one model instance or table row for Text model. So, I need to have two save() in the view, correct?

Model:


class Text (models.Model):
    name = models.CharField(max_length=1000)
    text = models.TextField()
    created_datetime = models.DateTimeField(auto_now_add=True, editable=False)
    modified_datetime = models.DateTimeField(auto_now=True, editable=False)
    active = models.BooleanField(default=True)
   
    def __unicode__(self):
        return self.name

class TextForm (ModelForm):
    class Meta:
        model = Text
        exclude = ('active','created_datetime', 'modified_datetime', )


View:

def home(request):
    user = request.user
    if request.method == 'POST':
        #Indvidual form value is accessible.
        return HttpResponse(request.REQUEST['id_name_1'])
       
        #I realized this is the usual model way which I cannot use
        """
        text_form = TextForm(request.POST)
        if text_form.is_valid():
            text_form.save()
            return render_to_response('home.html', {'user':user,})
        else:
            return HttpResponse("text for not valid")
        """
    else:
        text_form = TextForm()
        return render_to_response('home.html', {'text_form':text_form,})


Form:

<form method="post" id="text_form" action=".">
        {% csrf_token %}
        <div class="form">
            <div class="form_added">
<!--  element set 1 -->
                <fieldset id="fieldset1">
                <p>
                    <label for="id_name_1">Name:</label>
                    <input id="id_name_1" type="text" name="id_name_1" maxlength="1000">
                </p>
                <p>
                    <label for="id_text_1">Text:</label>
                    <textarea id="id_text_1" rows="10" cols="40" name="id_text_1"></textarea>
                </p>
                <p>
                    <label for="id_active_1">Active:</label>
                    <input checked="checked" type="checkbox" name="id_active_1" id="id_active_1">
                </p>
                </fieldset>
            </div>
           
            <div class="form_added">
<!--  element set 2 -->
                <fieldset id="fieldset2">
                <p>
                    <label for="id_name_2">Name:</label>
                    <input id="id_name_2" type="text" name="id_name_2" maxlength="1000">
                </p>
                <p>
                    <label for="id_text_2">Text:</label>
                    <textarea id="id_text_2" rows="10" cols="40" name="id_text_2"></textarea>
                </p>
                <p>
                    <label for="id_active_2">Active:</label>
                    <input checked="checked" type="checkbox" name="id_active_2" id="id_active_2">
                </p>
                </fieldset>
            </div>
           
        </div>
        <p><input type="submit" value="Save folio" id="text_form_submit"/></p>
    </form>





--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.


AJ

unread,
Jul 3, 2011, 4:34:30 PM7/3/11
to django...@googlegroups.com
I do realize that I need the number of elements so that I can loop over that many times...

AJ

unread,
Jul 3, 2011, 6:46:12 PM7/3/11
to django...@googlegroups.com
Nevermind. I did not know about and eventually solved it with formsets. Thanks.
Reply all
Reply to author
Forward
0 new messages