Ninja Turtle
Ninja Turtle

Reputation: 156

Submit fields added through javascript to the request object

What I am trying to do is, I am adding an author's field through javascript when the user clicks on the icon contained in the span. But the problem is that the fields added through javascript on submission of the form are neither obtained in the form object nor the request.POST object. I have two problems mainly:

  1. I want to be able to pass the values to the server in the fields added through javascript and be able to access them in the views.py
  2. I also want to know if there is some neater way to do it.

views.py

def addbook(request):
    if request.method=='POST':
        print(request.POST)
        form=BookForm(request.POST)
        # process accordingly.
    else:
        form = BookForm()
        return render(request,'book.html',{'form':form})

forms.py

class BookForm(forms.Form):
    author_name=forms.CharField(max_length=20)

book.html

<form action='' method="POST">
    <div id='authorfield'>{{ form.author_name }}</div>
    <a href='#'><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></a>
</form>

book.js

$('span').click( function(e) {
    e.preventDefault();
    $("#authorfield").after(" <div><input type='text' class='form-control' placeholder='Author name'></div>");

});

Upvotes: 0

Views: 58

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

You need to have a name attribute in the input element that is added by your JS.

However I'm not sure this will do what you want; you already have an author_name field, so it's not clear why you want to add another one.

Upvotes: 2

Related Questions