Django Class Views and Reverse Urls

Posted by kalhartt on Stack Overflow See other posts from Stack Overflow or by kalhartt
Published on 2012-11-29T22:37:53Z Indexed on 2012/11/29 23:04 UTC
Read the original article Hit count: 431

Filed under:
|
|
|

I have a good many class based views that use reverse(name, args) to find urls and pass this to templates. However, the problem is class based views must be instantiated before urlpatterns can be defined. This means the class is instantiated while urlpatterns is empty leading to reverse throwing errors. I've been working around this by passing lambda: reverse(name, args) to my templates but surely there is a better solution.

As a simple example the following fails with exception: ImproperlyConfigured at xxxx The included urlconf mysite.urls doesn't have any patterns in it

mysite.urls

from mysite.views import MyClassView

urlpatterns = patterns('',
    url(r'^$' MyClassView.as_view(), name='home')
)

views.py

class MyClassView(View):
    def get(self, request):
        home_url = reverse('home')
        return render_to_response('home.html', {'home_url':home_url}, context_instance=RequestContext(request))

home.html

<p><a href={{ home_url }}>Home</a></p>

I'm currently working around the problem by forcing reverse to run on template rendering by changing views.py to

class MyClassView(View):
    def get(self, request):
        home_url = lambda: reverse('home')
        return render_to_response('home.html', {'home_url':home_url}, context_instance=RequestContext(request))

and it works, but this is really ugly and surely there is a better way. So is there a way to use reverse in class based views but avoid the cyclic dependency of urlpatterns requiring view requiring reverse requiring urlpatterns...

© Stack Overflow or respective owner

Related posts about python

Related posts about django