-1

I have a form in Django, which has two textfields. The user can type the values and submit the form.

Now I want to create a functionality using jquery, where the user will be able to click a button and add extra input fields with additional values.

The number of the extra input fields is not predefined. My question is if there is a way in Django to create these extra fields in a way that they become part of the form. Is this possible?

user1919
  • 3,818
  • 17
  • 62
  • 97
  • wow. There are other questions with similar topic and they get upvoted instead.. http://stackoverflow.com/questions/6142025/dynamically-add-field-to-a-form – user1919 Jun 23 '16 at 18:11

1 Answers1

1

If you are looking for a django way of solving this problem then it would look like something like this:

def create_user(request):
    extra_questions = get_questions(request)
    form = UserCreationForm(request.POST or None, extra=extra_questions)
    if form.is_valid():
        for (question, answer) in form.extra_answers():
            save_answer(request, question, answer)
        return redirect("create_user_success")

    return render_to_response("signup/form.html", {'form': form})


class UserCreationForm(forms.Form):
    username = forms.CharField(max_length=30)
    password1 = forms.CharField(widget=forms.PasswordInput)
    password2 = forms.CharField(widget=forms.PasswordInput)

    def __init__(self, *args, **kwargs):
        extra = kwargs.pop('extra')
        super(UserCreationForm, self).__init__(*args, **kwargs)

        for i, question in enumerate(extra):
            self.fields['custom_%s' % i] = forms.CharField(label=question)

If you are looking for a jquery solution, then you can do following, on your create_user modify and send a form response:

def create_user(request):
    extra_questions = get_questions(request)
    form = UserCreationForm(request.POST or None, extra=extra_questions)
    if form.is_valid():
        for (question, answer) in form.extra_answers():
            save_answer(request, question, answer)
        return redirect("create_user_success")

    form_html = form.as_ul() #returns a form in html
    return HttpResponse(form_html)    

And then using jquery get the form html and append:

$('#submitform').click(function () {
    $.ajax({
        url: "getinfo.asp",
        data: {
            txtsearch: $('#appendedInputButton').val()
        },
        type: "POST",
        dataType: "html",
        success: function (data) {
            var result = $('<div />').append(data).find('#showresults').html();
            $('#showresults').html(result);
        },
        error: function (xhr, status) {
            alert("Sorry, there was a problem!");
        },
        complete: function (xhr, status) {
            //$('#showresults').slideDown('slow')
        }
    });
});
sadaf2605
  • 7,332
  • 8
  • 60
  • 103