Editing an Event
Part of the Forms section of Coddy's Django journey. Lesson 13 of 20.
Each event page now has an Edit this event link to /events/1/edit/. The URL, the link and the template are ready, and edit_event already finds the event the URL names. The rest of the view is yours.
A ModelForm edits an existing row when you hand it that row as instance. For a note in a notes app:
note = get_object_or_404(Note, pk=4)
form = NoteForm(instance=note) # filled in with the note's values
form = NoteForm(request.POST, instance=note) # the new values, for this note
if form.is_valid():
form.save() # updates note 4, adds no rowWithout data, NoteForm(instance=note) draws the form filled in with the row's current values. With data, instance=note makes form.save() update that row instead of creating a new one.
An edit page needs both. Forget the instance on the GET and the visitor sees an empty form; forget it on the POST and saving adds a copy.
Challenge
EasyFinish edit_event in events/views.py:
- A GET shows the form filled in with the event's details.
- A valid POST saves the changes to this event, adds no new one, and redirects to its page.
- An invalid POST shows the page again with the errors.
The template needs form and event. Press Run, then press Edit this event.
Try it yourself
from django.shortcuts import get_object_or_404, redirect, render
from .forms import EventForm
from .models import Event
def event_list(request):
q = request.GET.get("q", "")
events = Event.objects.all()
if q:
events = events.filter(title__icontains=q)
return render(request, "events/event_list.html", {"events": events, "q": q})
def event_detail(request, pk):
event = get_object_or_404(Event, pk=pk)
return render(request, "events/event_detail.html", {"event": event})
def new_event(request):
if request.method == "POST":
form = EventForm(request.POST)
if form.is_valid():
event = form.save()
return redirect("events:detail", pk=event.pk)
else:
form = EventForm()
return render(request, "events/new_event.html", {"form": form})
def edit_event(request, pk):
event = get_object_or_404(Event, pk=pk)
# Build the form for this event, check it and save it, like new_event.
return render(request, "events/edit_event.html", {"event": event})
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Forms
Practice on your own: Django playground