Passing extra context data to class-based generic views?

774 views
Skip to first unread message

David Chandek-Stark

unread,
Apr 6, 2011, 12:02:00 PM4/6/11
to django...@googlegroups.com
Function-based generic views provided an "extra_context" keyword argument to add variables to the template context.  It appears that under the initial implementation of class-based generic views in Django 1.3, there are two major differences:

1. To add extra context, you have to subclass and override get_context_data(); and,
2. Extra variables are added to the "params" context variable, not directly (so to speak) to the context.

Do I have this right?  If so, #1 seems to violate the DRY principle.  Why not add an "extra_context" attribute to the TemplateResponseMixin class?

Thanks,
David

Russell Keith-Magee

unread,
Apr 6, 2011, 7:34:27 PM4/6/11
to django...@googlegroups.com
On Thu, Apr 7, 2011 at 12:02 AM, David Chandek-Stark
<dchand...@gmail.com> wrote:
> Function-based generic views provided an "extra_context" keyword argument to
> add variables to the template context.  It appears that under the initial
> implementation of class-based generic views in Django 1.3, there are two
> major differences:
> 1. To add extra context, you have to subclass and override
> get_context_data(); and,
> 2. Extra variables are added to the "params" context variable, not directly
> (so to speak) to the context.
> Do I have this right?  If so, #1 seems to violate the DRY principle.

I don't think DRY means what you think it means. (1) doesn't force you
to repeat anything -- it's just requires a particular way of defining
extra context.

>  Why
> not add an "extra_context" attribute to the TemplateResponseMixin class?

Because extra context can't always be expressed like that. One of the
problems with function-based generic views is that there was certain
types of context data -- for example, anything that required a runtime
lookup (such as calls to reverse()) or anything that required access
to request variables (e.g., the current user).

That said -- there's an argument to be made that get_context should
fall back in the same way that get_template_names() falls back to the
template_name attribute. That way, any view for which a simple context
is possible could continue to use the simple approach, but there's
flexibility if you need it.

If you open a ticket, this idea won't be forgotten; it's also a fairly
minor change, so if you want to try your hand at a patch, it would be
an easy way to get involved with Django development.

Yours,
Russ Magee %-)

Greg

unread,
Jun 9, 2011, 9:42:23 PM6/9/11
to django...@googlegroups.com
I've created a reusable view which allows for an extra_context argument, see https://github.com/gregplaysguitar/django-baseclasses/blob/master/baseclasses/views.py

+1 on this functionality being added to django itself though.
Reply all
Reply to author
Forward
0 new messages