An ownership check ensures that an authenticated user may edit only resources they own. In Django, combine the requested object’s ID with owner=request.user when fetching it. section 7.2.5
A practical edit flow:
- Use separate add and edit routes that call one view, with an object ID identifying edit mode. section 7.2.5
- Fetch the object with get_object_or_404(), filtering by both its ID and the authenticated owner. section 7.2.5
- Apply the ownership check for both GET and POST requests, then bind the ModelForm to the existing instance. section 7.2.5
- Display the Edit link only when the listed ad belongs to request.user. section 7.2.5
Django ownership filter
ad = get_object_or_404(SeekingAd, id=ad_id, owner=request.user) prevents another authenticated user’s ad from being loaded for editing. section 7.2.5
Listing 7.12 View for displaying and submitting SeekingAdForm
# RiffMates/content/views.py
...
from django.shortcuts import render, redirect, get_object_or_404
...
@login_required
def seeking_ad(request, ad_id=0): #1
if request.method == 'GET':
if ad_id == 0: #2
form = SeekingAdForm()
else:
ad = get_object_or_404(SeekingAd, id=ad_id,
owner=request.user) #3
form = SeekingAdForm(instance=ad) #4
else: # POST
if ad_id == 0:
form = SeekingAdForm(request.POST) #5
else:
ad = get_object_or_404(SeekingAd, id=ad_id,
owner=request.user) #6
form = SeekingAdForm(request.POST,
instance=ad) #7
...
Trace the edit view’s ownership check, form prepopulation, and POST handling in the complete listing. section 7.2.5
