[Django]-Django Form based on multiple models

4👍

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.

0👍

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.

Leave a comment