0

Models:

class Author(models.Model):
    name = models.CharField(max_length=150)
    age = models.IntegerField()

class Book(models.Model):
    title = models.CharField(max_length=150)
    number = models.IntegerField()
    author = models.ManyToManyField(Author)

Goal:

http://feb.imghost.us/HaAo.png

How can I create this form? (should allow to add many Authors before I save whole form)

1 Answers1

1

Say you have a book with mulitple authors, You want to save multiple authors to same book object, if that is the case when user adds the author save the author object and use jquery to save the newly created author object id in a hidden field ( create a hidden input tag with author id) and when user saves the book retrieve all the hidden author ids and save the book with the authors.

loki
  • 387
  • 2
  • 8
  • Good idea. Thanks. But how jquery can store these ID? If I add new Author then my page will refresh. Can you provide some example? – user3052801 Feb 24 '14 at 07:57
  • In this case you have to load the page via ajax. when call ajax in success function create a input tag. if needed instead of input tag you can create a dropdown of authors created and show it user in front end and get all drop down author ids while saving book. – loki Feb 24 '14 at 09:09
  • $('').attr({ type: 'hidden', id: 'foo', name: 'bar' }).appendTo('form'); – loki Feb 24 '14 at 09:38
  • to create input hidden tag $('').attr({ type: 'hidden', id: 'foo', name: 'bar' }).appendTo('form'); to load the page use ajax $.ajax({ url: "Your URL", type: "POST", data: { : },// your data to post success: function (result){// put your input tag creation code here} )}; – loki Feb 24 '14 at 09:45
  • Only problem is when user create new Authors and not save Book form – user3052801 Feb 24 '14 at 09:57
  • That should not be a problem. Everytime you save author u have to check for duplicates. if author is already present use that and save the book next time if user submits else author record will be left orphan. You set a monthly job to clean DB if required. – loki Feb 24 '14 at 10:01