save() writes a Django model instance to the database. Changing an attribute changes only the in-memory Python object; calling save() synchronizes that change with the stored row. section 4.5
Use save() in two common ways:
- Call it on an existing model instance after changing one or more attributes. section 4.5
- Call it on a valid ModelForm, which saves and returns the corresponding model object. section 7.2.4 section 7.6
- Use form.save(commit=False) when required model fields are not included in the form; assign them first, then save the instance. section 7.2.4
Updating a musician
dad = Musician.objects.get(id=4) dad.birth = date(1938, 2, 23) dad.save() The next query returns the updated birth date because save() sent the changed value to the database. section 4.5
Listing 7.10 View for displaying and submitting SeekingAdForm
# RiffMates/content/views.py
from django.contrib.auth.decorators import login_required
...
from content.forms import CommentForm, SeekingAdForm
from content.models import MusicianBandChoice, SeekingAd
@login_required #1
def seeking_ad(request):
if request.method == 'GET':
form = SeekingAdForm() #2
else: # POST
form = SeekingAdForm(request.POST) #3
if form.is_valid(): #4
ad = form.save(commit=False) #5
ad.owner = request.user #6
ad.save() #7
return redirect("list_ads") #8
# Was a GET, or Form was not valid #9
data = {
"form": form,
}
return render(request, "seeking_ad.html", data)
A form view validates submitted data, creates an unsaved ad with commit=False, assigns request.user to owner, saves it, and redirects to the listing. section 7.2.4
