Opened 3 months ago

Last modified 2 months ago

#21801 new Cleanup/optimization

SingleObjectMixin get_context_data fails with self.object not initialized

Reported by: anonymous Owned by: nobody
Component: Documentation Version: 1.6
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


I'm not sure if this needs to be addressed in the documentation or in the code, but there's a bit of a gotcha in the SingleObjectMixin code, related to the implementation of get_context_data().

The get_context_data() of SingleObjectMixin looks for self.object to attach the retrieved object to the view. However, the object attribute is not actually set anywhere in the SingleObjectMixin. A little digging says that BaseDetailView addresses this by manually setting self.object to self.get_object() in the get() function. However, that mandates the semi-redundant setting of an attribute that may not be used elsewhere, and also requires one of dispatch, get, or post to be defined. None of this is mentioned in the documentation, though after going back I noticed that there's an unexplained self.object = self.get_object() in the documentation for using mixins.

There are a couple potential ways to deal with this, but I think the simplest way is probably this:

def get_context_data(self, **kwargs):
    Insert the single object into the context dict.
    context = {}
        obj = self.object
    except AttributeError:
        obj = self.get_object()
    if obj:
        context['object'] = obj
        context_object_name = self.get_context_object_name(obj)
        if context_object_name:
            context[context_object_name] = obj
    return super(SingleObjectMixin, self).get_context_data(**context)

I suspect it won't break any existing code, and it'll allow SingleObjectMixin to be used without having to redefine on of the functions that comes before get_context_data() in the chain.

Attachments (0)

Change History (4)

comment:1 Changed 3 months ago by wraus@…

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

Oops, forgot to set the reporter field. Posting here just in case.

comment:2 Changed 2 months ago by mjtamlyn

  • Triage Stage changed from Unreviewed to Accepted

comment:3 Changed 2 months ago by mjtamlyn

  • Type changed from Uncategorized to Bug

comment:4 Changed 2 months ago by timo

  • Component changed from Generic views to Documentation
  • Type changed from Bug to Cleanup/optimization

Decided to go the documentation route on the PR.

Add Comment

Modify Ticket

Change Properties
<Author field>
as new
The owner will be changed from nobody to anonymous. Next status will be 'assigned'
as The resolution will be set. Next status will be 'closed'

E-mail address and user name can be saved in the Preferences.

Note: See TracTickets for help on using tickets.