Django ModelForm: What is save(commit=False) used for?

后端 未结 5 1531
遇见更好的自我
遇见更好的自我 2020-11-28 20:51

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

5条回答
  •  迷失自我
    2020-11-28 21:25

    Here it is the answer (from docs):

    # Create a form instance with POST data.
    >>> f = AuthorForm(request.POST)
    
    # Create, but don't save the new author instance.
    >>> new_author = f.save(commit=False)
    

    The most common situation is to get the instance from form but only 'in memory', not in database. Before save it you want to make some changes:

    # Modify the author in some way.
    >>> new_author.some_field = 'some_value'
    
    # Save the new instance.
    >>> new_author.save()
    

提交回复
热议问题