Mridang Agarwalla
Mridang Agarwalla

Reputation: 44958

Django Form based on multiple models

If I have two models in Django application like this:

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    author = models.ForeignKey(Author)
    title = models.CharField(max_length=100)

How can I create a single form that allows you add both an Author and a Book simultaneously. If the author exists in the system, I could simply display the book Form and link that to the author but it is very often that I need to allow my users to create the book and the author simultaneously.

How can I do this?

Thanks.

Upvotes: 3

Views: 2605

Answers (2)

Dmitry Demidenko
Dmitry Demidenko

Reputation: 3407

You can write a custom form, which will check if the author exists in the system use existing, if no, create new with provided name.

class CustomForm(forms.ModelForm):
    author = forms.CharField()

    def save(self, commit=True):
       author, created = Author.objects.get_or_create(name=self.cleaned_data['author'])

       instance = super(CustomForm,self).save(commit=commit)
       instance.author = author
       if commit:
          instance.save()
       return instance

    class Meta:
        model=Book

Not sure this code is working, but I suppose it can explain my idea.

Upvotes: 4

Trent Gm
Trent Gm

Reputation: 2477

You can create a view that handles multiple forms - see http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ for an excellent example.

You'd have to ensure that the rendering of the form objects are done in the template with only one tag and one submit button.

Upvotes: 0

Related Questions