On Sun, Jul 15, 2007 at 02:59:57PM -0500, Carl Karsten wrote:
>
> How can I use a method as a view? (so that I can subclass and extend later.)
>
> foo works, the other 2 give errors:
>
> # msg/urls.py
> from django.conf.urls.defaults import *
> urlpatterns = patterns('msg.views',
> (r'^detail/(?P<object_id>[-\w]+)/$', 'foo'),
> (r'^detail/x/(?P<object_id>[-\w]+)/$', 'MsgViews.message_detail'),
> (r'^detail/y/(?P<object_id>[-\w]+)/$', MsgViews.message_detail),
> )
Try this:
--------------------------------------------------------------------------------
from django.conf.urls.defaults import *
msg_views = MsgViews()
urlpatterns = patterns('msg.views',
(r'^detail/(?P<object_id>[-\w]+)/$', 'foo'),
(r'^detail/x/(?P<object_id>[-\w]+)/$', msg_views.message_detail),
(r'^detail/y/(?P<object_id>[-\w]+)/$', msg_views.message_detail),
)
--------------------------------------------------------------------------------
Alternatively, you can make message_detail a static method:
--------------------------------------------------------------------------------
class MsgViews(object):
@static_method
def message_detail(request, object_id=None):
m=get_object_or_404(Message, pk=object_id)
return render_to_response('message_detail.html', {'message': m})
--------------------------------------------------------------------------------
I'm not even sure if this sort of thing is possible, but it might be:
--------------------------------------------------------------------------------
class MsgViews(object):
@static_method
def __call__(request, object_id=None):
m=get_object_or_404(Message, pk=object_id)
return render_to_response('message_detail.html', {'message': m})
--------------------------------------------------------------------------------
The only reason I can think of for doing that is that you wouldn't have to
import MsgViews in your urls.py, you could just specify a string.
Now, after all that, I'm still a little confused as to why you would want to do
all of this? You say so that you can extend your view functions, but classes
are extensible because their methods can be replaced, and you already _can_
replace plain view functions...
-Forest
signature.asc
Description: Digital signature

