0Pricing
Django Academy · Aula

form.save() e commit=False

Persista dados e ajuste instâncias antes de salvar

form.save() e commit=False é uma aula grátis de Django Academy no CoddyKit. Esta é a aula 2 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Django Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Django Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

Saving in One Line

The big payoff of a ModelForm is save(). After a form validates, one call writes the data straight to the database as a new row. 💾

if form.is_valid():
    form.save()

save() Returns the Object

Calling save() hands back the saved model instance. Grab it when you want to redirect to the new object or read its fresh id.

post = form.save()
print(post.id)

Validate Before You Save

Always gate save() behind is_valid(). Saving an invalid form raises an error, so check validity first every single time.

if form.is_valid():
    form.save()

Editing an Existing Row

When the form was built with an instance, save() updates that row instead of creating a new one. Same method, different outcome.

form = PostForm(request.POST, instance=post)
if form.is_valid():
    form.save()

Sometimes You Need a Pause

Often a model has a field the form should not collect, like the author. You need to set it yourself before the row hits the database.

Enter commit=False

Calling save(commit=False) builds the model instance from the form but does not write it to the database yet. You hold it in memory.

post = form.save(commit=False)

Set Fields the Form Skipped

With the unsaved instance in hand, you can attach extra data. Here we set the author from the logged-in user before saving.

post = form.save(commit=False)
post.author = request.user

Finish the Save

After tweaking the instance, call its own save() method to commit it. Now both the form data and your extra field land together.

post.author = request.user
post.save()

The Full Pattern

This three-step commit=False pattern is the everyday way to mix form input with server-set values cleanly and safely.

post = form.save(commit=False)
post.author = request.user
post.save()

Many-to-Many Caveat

One gotcha: with commit=False, many-to-many links are not saved yet. Call save_m2m() after saving the instance to attach them.

post.save()
form.save_m2m()

Redirect After Success

Once the row is saved, send the user onward. A redirect after a successful POST prevents accidental double submissions.

post.save()
return redirect("post_detail", pk=post.pk)

Quick Check

What does save(commit=False) give you the chance to do?

Recap: Saving Forms

Great progress! After is_valid(), save() writes the row. Use commit=False to set extra fields first, then save the instance, and save_m2m() if needed. ✅

Perguntas Frequentes

A aula “form.save() e commit=False” é grátis?

Sim — o texto completo de “form.save() e commit=False” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Django Academy, atualize para CoddyKit PRO. O curso de Django Academy inclui 4 aulas no total.

O que vou aprender em “form.save() e commit=False”?

Persista dados e ajuste instâncias antes de salvar Você pratica Django Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Django Academy?

Nenhuma experiência prévia é necessária. Django Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 2 de 4.

Quanto tempo leva a aula “form.save() e commit=False”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Django Academy?

Sim. Cada aula de Django Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Declarando um ModelForm e Meta.fields
  2. form.save() e commit=False
  3. Validação personalizada com métodos clean
  4. Widgets, rótulos e textos de ajuda
← Voltar para Django Academy