4

Suppose there are two models: Author and Book. Sure enough Book has a foreign key to an Author. There is a create view in which user gives a name of the author and uploads a file with the list of books it has.

So I am trying to figure out the best way to create a form. Right now I have:

class AddForm(ModelForm):
     books = FileField()
     class Meta:
          model = Author

     def clean_books(self):
          return [book.strip() for book in self.cleaned_data['books'].file]

The problem is where should I put the actual creation of Books model objects? Looks like it should be in a save method, something like:

def save(self, commit=True):
    author = super().save(commit=True)
    Book.objects.bulk_create([Book(author=author, title=book.title, ...) for book in self.cleaned_data['books']])
    return author

But is it ok? What really annoys me is the commit argument. It's totally ignored and it may confuse others if they supply commit=False. How do I take into account commit argument and do not break the logic?

1 Answer 1

1

Take look at inline formsets. Using them you can add bunch of inline forms inside your main form. That formset will handle for you all processing of data and saving Book instances into database. It's like inline in django admin.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately I do not understand how to use it with my concrete example. Can you provide an example given I use CreateView CBV?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.