liveBook · Manning

Ownership check

As explained in Django in Action

An ownership check verifies that the authenticated user is authorized to modify the requested resource.

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

How Django in Action covers it

How deep it goes
Checks ownership during GET and POST database retrieval, while stopping short of broader authorization design.
Examples
Uses RiffMates SeekingAd records, edit routes, get_object_or_404(), and conditional Edit links.
What you can do after
Apply it via Django by filtering object retrieval with both the resource identifier and request.user.
How it connects
Connects authentication, authorization, Django ORM queries, ModelForm instances, URL routing, and template conditionals.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.