form.save() e commit=False
Salvare i dati e modificare le istanze prima del salvataggio
form.save() e commit=False è una lezione Django Academy gratuita su CoddyKit. Questa è la lezione 2 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Django Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Django Academy include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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.userFinish 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. ✅
Domande Frequenti
La lezione «form.save() e commit=False» è gratuita?
Sì — il testo completo di «form.save() e commit=False» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Django Academy, passa a CoddyKit PRO. Il corso Django Academy include 4 lezioni in totale.
Cosa imparerò in «form.save() e commit=False»?
Salvare i dati e modificare le istanze prima del salvataggio Eserciti Django Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Django Academy?
Non è richiesta alcuna esperienza precedente. Django Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.
Quanto tempo richiede la lezione «form.save() e commit=False»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Django Academy?
Sì. Ogni lezione Django Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Dichiarare un ModelForm e Meta.fields
- form.save() e commit=False
- Validazione personalizzata con i metodi clean
- Widget, etichette e testo di supporto