Answer a question

Why would I ever use save(commit=False) instead of just creating a form object from the ModelForm subclass and running is_valid() to validate both the form and model?

In other words, what is save(commit=False) for?

If you don't mind, could you guys provide hypothetical situations where this might be useful?

Answers

That's useful when you get most of your model data from a form, but you need to populate some null=False fields with non-form data.

Saving with commit=False gets you a model object, then you can add your extra data and save it.

This is a good example of that situation.

Here's the documentation on the save method. Note that if your form includes many-to-many fields, you'll also want to call form.save_m2m() after saving the model instance.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐